运行在前台的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就好了。


欢迎多多交流.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容