运行在前台的Service

前言: 

service作为Activity四大组件之一,其作用性也是不言而喻的,最近用到service发现一脸懵啊,写一篇文章来记录一下。

本文主要是写了一个类似墨迹天气启动后显示在通知栏的Service。主要是创建一个类去继承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);

//创建任务栈

        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就好了。


运行在前台的Service_第1张图片

欢迎多多交流.

你可能感兴趣的:(运行在前台的Service)