1.创建PollingThread类,在log打印出“New message!”
class PollingThread extends Thread { @Override public void run() { Log.i("zzf", "Polling..."); } }
2.创建PollingReceiver,用于接收Service传递信息并重新执行PollingService
public class PollingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Log.i("zzf", "Receive!"); Intent i = new Intent(context, PollingService.class); context.startService(i); } }
3.创建PollingService定时轮询任务对象
public class PollingService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub //创建PollingThread子线程,用于执行任务 new PollingThread().start(); // 获取AlarmManager系统服务 AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // 包装需要执行Service的Intent Intent i = new Intent(this, PollingReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0); int anSeconds = 5 * 1000; // 5秒 // 触发时间 long triggerAtTime = SystemClock.elapsedRealtime() + anSeconds; manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent); return super.onStartCommand(i, flags, startId); }
4.在MainActivity中启动PollingService
Log.i("zzf","Start polling service..."); Intent intent = new Intent(this, PollingService.class); startService(intent);
时间: 2024-12-16 15:13:25