android 後台服務定時通知

來源:互聯網
上載者:User

標籤:des   android   style   blog   http   color   io   os   使用   

   最近有個項目的要求是在程式退出之後,任然可以每天定時發通知,我們可以想下,其實就是後台開一個服務,然後時間到了就發下通知。

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     @Override42     public IBinder onBind(Intent arg0) {43         // TODO Auto-generated method stub44         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             @Override57             public void run() {58                 // TODO Auto-generated method stub59                 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     @Override79     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是和主線程在一起的,主線程被終止了,服務線程也會停止掉,就無法在後台執行了,所以我們必須把服務註冊到系統中

工程源碼

android 後台服務定時通知

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.