1 /** 2 * 后台执行的定时任务 3 */ 4 public class LongRunningService extends Service { 5 6 @Override 7 public IBinder onBind(Intent intent) { 8 return null; 9 } 10 11 @Override 12 public int onStartCommand(Intent intent,int flags,int startId) { 13 14 new Thread(){ 15 public void run() { 16 Log.i("TAG","LongRunningService exec at " + new Date().toString()); 17 }; 18 }.start(); 19 20 //获取Alarm管理对象 21 AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE); 22 23 //设置执行的时间间隔 24 long triggerAtTime = SystemClock.elapsedRealtime() + 5 * 1000; 25 26 //获取一个能够执行广播的 PendingIntent。 这样当定时任务被触发的时候,广播接收器的 27 onReceive()方法就可以得到执行。 28 Intent intent2 = new Intent(this,AlarmReceiver.class); 29 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent2, 0); 30 31 //设置一个定时任务 32 manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent); 34 return super.onStartCommand(intent,flags,startId); 35 } 36 }
2 public class AlarmReceiver extends BroadcastReceiver { 3 @Override 4 public void onReceive(Context context,Intent intent) { 5 Intent intent2 = new Intent(context, LongRunningService.class); 6 context.startService(intent2); 7 } 8 }
1 /** 2 * 前台服务 3 */ 4 public class ForegroundService extends Service { 5 6 @Override 7 public IBinder onBind(Intent intent) { 8 return null; 9 } 10 11 @Override 12 public void onCreate() { 13 Intent intent = new Intent(this,MainActivity.class); 14 PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0); 15 16 Notification nf = new Notification(R.drawable.p1,"有一条通知",System.currentTimeMillis()); 18 nf.setLatestEventInfo(this,"这是通知的标题","这是通知的内容",pendingIntent); 19 nf.flags = Notification.FLAG_AUTO_CANCEL; 20 //调用这个方法将服务变为前台服务,并在系统通知栏显示出来 21 startForeground(1,nf); 22 23 super.onCreate(); 24 } 25 }