Service详解
1 /**
2 * 后臺執(zhí)行的定時任務(wù)
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 //設(shè)置執(zhí)行的時間間隔
24 long triggerAtTime = SystemClock.elapsedRealtime() + 5 * 1000;
25
26 //獲取一個能夠執(zhí)行廣播的 PendingIntent。 這樣當(dāng)定時任務(wù)被觸發(fā)的時候,廣播接收器的
27 onReceive()方法就可以得到執(zhí)行。
28 Intent intent2 = new Intent(this,AlarmReceiver.class);
29 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent2, 0);
30
31 //設(shè)置一個定時任務(wù)
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 * 前臺服務(wù) 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,"這是通知的標(biāo)題","這是通知的內(nèi)容",pendingIntent); 19 nf.flags = Notification.FLAG_AUTO_CANCEL; 20 //調(diào)用這個方法將服務(wù)變?yōu)榍芭_服務(wù),并在系統(tǒng)通知欄顯示出來 21 startForeground(1,nf); 22 23 super.onCreate(); 24 } 25 }?
轉(zhuǎn)載于:https://www.cnblogs.com/yangang2013/p/4937680.html
總結(jié)
- 上一篇: PHP 设计模式六大原则
- 下一篇: BZOJ1652 [Usaco2006