最近有個項目的要求是在程序退出之后,任然可以每天定時發通知,我們可以想下,其實就是后台開一個服務,然后時間到了就發下通知。
1.首先我們需要用到Service類。
先上代碼在慢慢解釋
1 package com.example.androidnotification; 2 3 import java.util.Timer; 4 import java.util.TimerTask; 5 import android.app.Notification; 6 import android.app.NotificationManager; 7 import android.app.PendingIntent; 8 import android.app.Service; 9 import android.content.Intent; 10 import android.os.IBinder; 11 import android.util.Log; 12 13 public class PushService extends Service { 14 15 static Timer timer = null; 16 //清除通知 17 public static void cleanAllNotification() { 18 NotificationManager mn= (NotificationManager) MainActivity.getContext().getSystemService(NOTIFICATION_SERVICE); 19 mn.cancelAll(); 20 if (timer != null) { 21 timer.cancel(); 22 timer = null; 23 } 24 } 25 26 //添加通知 27 public static void addNotification(int delayTime,String tickerText,String contentTitle,String contentText) 28 { 29 Intent intent = new Intent(MainActivity.getContext(), PushService.class); 30 intent.putExtra("delayTime", delayTime); 31 intent.putExtra("tickerText", tickerText); 32 intent.putExtra("contentTitle", contentTitle); 33 intent.putExtra("contentText", contentText); 34 MainActivity.getContext().startService(intent); 35 } 36 37 public void onCreate() { 38 Log.e("addNotification", "===========create======="); 39 } 40 41 @Override 42 public IBinder onBind(Intent arg0) { 43 // TODO Auto-generated method stub 44 return null; 45 } 46 47 public int onStartCommand(final Intent intent, int flags, int startId) { 48 49 long period = 24*60*60*1000; //24小時一個周期 50 int delay=intent.getIntExtra("delayTime",0); 51 if (null == timer ) { 52 timer = new Timer(); 53 } 54 timer.schedule(new TimerTask() { 55 56 @Override 57 public void run() { 58 // TODO Auto-generated method stub 59 NotificationManager mn= (NotificationManager) PushService.this.getSystemService(NOTIFICATION_SERVICE); 60 Notification.Builder builder = new Notification.Builder(PushService.this); 61 Intent notificationIntent = new Intent(PushService.this,MainActivity.class);//點擊跳轉位置 62 PendingIntent contentIntent = PendingIntent.getActivity(PushService.this,0,notificationIntent,0); 63 builder.setContentIntent(contentIntent); 64 builder.setSmallIcon(R.drawable.ic_launcher); 65 builder.setTicker(intent.getStringExtra("tickerText")); //測試通知欄標題 66 builder.setContentText(intent.getStringExtra("contentText")); //下拉通知啦內容 67 builder.setContentTitle(intent.getStringExtra("contentTitle"));//下拉通知欄標題 68 builder.setAutoCancel(true); 69 builder.setDefaults(Notification.DEFAULT_ALL); 70 Notification notification = builder.build(); 71 mn.notify((int)System.currentTimeMillis(),notification); 72 } 73 },delay, period); 74 75 return super.onStartCommand(intent, flags, startId); 76 } 77 78 @Override 79 public void onDestroy(){ 80 Log.e("addNotification", "===========destroy======="); 81 super.onDestroy(); 82 } 83 }
自定義了一個類PushService繼續Service,定義了兩個類來實現添加通知和取消通知
//delayTime 延遲多久執行。
//tickerText
//contentTitle 通知欄的標題
//contentText 通知欄的內容
addNotification(int delayTime,String tickerText,String contentTitle,String contentText)
//清除通知
cleanAllNotification()
====================================
Service的啟動,startService來啟動服務只執行一次onCreate方法,但是每次調用一次startService就會執行一次onStartCommand函數。
2.注冊服務類
在AndroidManifest.xml中的application字段中加入如下信息來注冊這個服務類。
<service android:enabled="true" android:name=".PushService" android:process="system"></service>
這邊有一點非常重要的是 android:process="system" ,設置為system,否則按退出鍵使用如下方式來執行會導致程序崩潰,而且服務也會被終止,
android.os.Process.killProcess(android.os.Process.myPid());或者System.exit(0)
因為service是和主線程在一起的,主線程被終止了,服務線程也會停止掉,就無法在后台執行了,所以我們必須把服務注冊到系統中。
我們啟動服務使用startservice方式,因為使用bindservice會跟所綁定的context一起死亡的,bindservice的概念是"不求同生,但求同死",所以使用bindservice時候注意不能設置android:process="system"