前言:?
service作為Activity四大組件之一钦讳,其作用性也是不言而喻的,最近用到service發(fā)現(xiàn)一臉懵啊伴找,寫一篇文章來記錄一下锰镀。
本文主要是寫了一個類似墨跡天氣啟動后顯示在通知欄的Service斟赚。主要是創(chuàng)建一個類去繼承Service.代碼實例如下:
public class WeatherServiceextends Service {
private final static StringTAG = WeatherService.class.getSimpleName();
private static final int NOTIFY_ID =123;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
? ? public void onCreate() {
super.onCreate();
showNotification();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void showNotification() {
NotificationCompat.Builder mBuilder =new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setContentTitle("天氣").setContentText("今天晴朗");
Intent resultIntent =new Intent(this, MainActivity.class);
//創(chuàng)建任務棧
? ? ? ? TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
manager.notify(NOTIFY_ID, notification);
startForeground(NOTIFY_ID, notification);
}
@Nullable
@Override
? ? public IBinder onBind(Intent intent) {
return null;
}
}
然后不要忘記了在AndroidManifest下去注冊該Service.
最后在Activity里面啟動service就好了着降。
歡迎多多交流.