一個Android程序僅僅只能前臺 運行是遠遠不夠的,咱們更但願它在後臺運行,既能夠接收消息,又不耽誤咱們去使用別的軟件,這就要求咱們要實現兩點:
1,後臺運行程序,藉助service實現
2,通知欄通知消息,系統的notification
##service實現程序後臺運行
實現service程序 後臺運行,首先要解決幾個問題:
-如何判斷程序是否後臺運行?
-如何在程序後臺運行時去開啓服務?
後臺進程是指程序對用戶不可見的狀態,在程序中又該如何去判斷呢?其實很簡單,我也搜了一些代碼,可是都達不到我想要的效果,不如本身動腦。咱們能夠註冊一個廣播去監聽activity的某些生命週期,當程序運行到某個生命週期時(stop或者destroy),能夠發送廣播,而後執行開啓服務方法。
這樣的話就很靈活了,若是你想要程序不論在任什麼時候候均可以接收到通知欄消息,那隻須要在onCreate方法中開啓一個能夠發送notification的廣播,諸如此類。
我是在activity調用destroy後開啓服務,廣播接收器代碼以下:ide
/** * 監聽activity的結束 */ private BroadcastReceiver mFinishReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //開啓一個發送notification的service Intent intentService = new Intent(MainActivity.this,NotifyService.class); startService(intentService); //必定要註銷廣播 unregisterReceiver(mFinishReceiver); } };
在程序的onCreate方法中註冊該廣播:ui
IntentFilter filter = new IntentFilter("finish"); registerReceiver(mFinishReceiver, filter);
由於activity的生命週期,因此在activity的onDestroy方法中去發送廣播,通知廣播接收器程序已經finish了,能夠開啓服務,所實現的效果就是當程序結束後,所開啓的服務會一直運行在後臺進行監聽,並經過通知欄發送消息this
@Override protected void onDestroy() { super.onDestroy(); //發送廣播 sendBroadcast(new Intent("finish")); }
notification通知消息:
接下來的這些代碼須要寫在服務裏
要使用通知欄能夠分如下幾步:
第一步,獲取系統的通知欄管理對象:code
private NotificationManager manager; manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
第二步,獲取通知欄Builder對象(是v4 包下的)對象
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
第三步,獲取到builder對象後, 就能夠對通知欄進行一個界面和通知形式的一些設置了
builder對象提供了不少方法,在這裏介紹一些經常使用方法生命週期
//設置手機上LED燈的閃爍頻率及燈的顏色, setLights(@ColorInt int argb, int onMs, int offMs)
該方法的參數分析:
argb:LED燈的顏色
onMs:LED燈亮的時間,以毫秒爲單位
offMs:LED燈滅的時間,以毫秒爲單位進程
//定義通知欄所顯示的內容 setTicker(CharSequence tickerText)
//設置通知到來時的一些選項 mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND);
該方法有四個取值,DEFAULT_SOUND(默認的提示音),DEFAULT_VIBRATE(震動),DEFAULT_LIGHTS(燈閃爍),DEFAULT_ALL(擁有所有設置選項)
第四步,在builder設置好後就能夠發送通知請求 了:get
//發送通知請求 manager.notify(1,mBuilder.build());
一個完整的發送通知欄的代碼以下,固然下拉時的顯示風格也能夠自定義it
//跳轉意圖 Intent intent = new Intent(NotifyService.this,MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,intent,0); NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); //通知欄顯示內容 builder.setTicker("notify_activity"); //通知消息下拉是顯示的文本內容 builder.setContentText("content"); //通知欄消息下拉時顯示的標題 builder.setContentTitle("title"); //接收到通知時,按手機的默認設置進行處理,聲音,震動,燈 builder.setDefaults(Notification.DEFAULT_ALL); //通知欄顯示圖標 builder.setSmallIcon(R.drawable.notification_template_icon_bg); builder.setContentIntent(pendingIntent); notification = builder.build(); //點擊跳轉後消失 notification.flags |= Notification.FLAG_AUTO_CANCEL; manager.notify(1,notification);