Service
1.Service 前臺服務與Notification
我們在用很多應用的時候,發現他們啟動的時候,會在通知欄生成一個和該App的通知,來繼續執行Service,比如墨跡天氣,很多音樂App.這種叫前臺服務,其實這種Service有一個很好的一點,就是不會因為Service自身的優先級低,而被系統KILL,而前臺服務就不會。
前臺服務的寫法很容易,只需要在onCreate()中,建立一個通知,然后用startForeground()設置為前臺服務即可。
下面直接放出代碼,結合代碼注釋看看就好了,關于通知更多的內容可以看看
這里只列出Service的onCreate()部分代碼
@Override
public void onCreate() {
super.onCreate();
//設定一個PendingIntent,來表示點擊通知欄時跳轉到哪里
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification.Builder builder = new Notification.Builder(this);
//建立一個notificationManager來管理通知的出現
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//構造通知的樣式,包括圖片,標題,內容,時間。
builder.setSmallIcon(R.mipmap.ic_launcher).
setWhen(System.currentTimeMillis()).
setContentTitle("我是標題").
setContentText("我是內容").
setTicker("在啟動時彈出一個消息").//這個Android5.0以上可能會失效
setWhen(System.currentTimeMillis()).
setContentIntent(contentIntent);
//最后通過build建立好通知
Notification notification = builder.build();
//通過manager來顯示通知,這個1為notification的id
notificationManager.notify(1,notification);
//啟動為前臺服務,這個1為notification的id
startForeground(1,notification);
}
2.后臺定時服務
后臺定時服務其實并不是特殊的Service,只是Service的常見的一種應用,放到后臺做定時更新,輪詢等。這次的Service要配合Alarm以及簡單的廣播機制來實現。
步驟主要如下:
第一步 獲得Service
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
第二步 通過set方法設置定時任務
int time = 1000;
long triggerAtTime = SystemClock.elapsedRealtime() + time;
Intent i = new Intent(this,AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
第三步 定義一個Service,在onStartCommand中開辟一個事務線程,用于處理一些定時邏輯
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//執行想做的操作,比如輸出時間
}
}).start();
//步驟二里面的代碼
return super.onStartCommand(intent, flags, startId);
}
第四步 定義一個Broadcast,用于啟動Service
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,LongRunningService.class);
context.startService(i);
}
}
浙公網安備 33010602011771號