美文网首页
运行在前台的Service

运行在前台的Service

作者: PlutoWnn | 来源:发表于2018-01-19 14:19 被阅读14次

前言: 

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永久运行

    想service永久运行我们可以在service里播放无声音乐或者使用前台服务,但是单单做这些service还是无...

  • Service

    Service介绍 运行于后台,没有前台界面的组件,用于运行需要在后台运行的代码。 在Activity中开启线程下...

  • 运行在前台的Service

    前言: service作为Activity四大组件之一,其作用性也是不言而喻的,最近用到service发现一脸懵啊...

  • Android笔记13:服务

    Service 就是默默运行在后台的组件,可以理解为是没有前台的activity,适合用来运行不需要前台界面的代码...

  • 服务简介

    服务Service 就是默默运行在后台的组件,可以理解为是没有前台的activity,适合用来运行不需要前台界面的...

  • Service

    Service 就是默默运行在后台的组件,可以理解为是没有前台的activity,适合用来运行不需要前台界面的代码...

  • 组件间通信方案(二):Android与Serivice通信

    在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实...

  • 进程保活

    Android 进程的 优先级 前台进程正在和用户交互 的act,前台运行的service,广播接受者的 onRe...

  • Notification

    前台服务通知 如果您的应用正在运行“前台服务”(一种长时间在后台运行且用户可察觉到的 [Service](http...

  • 前台 service

    private void startForeground() { String channelId ="com.t...

网友评论

      本文标题:运行在前台的Service

      本文链接:https://www.haomeiwen.com/subject/ftbooxtx.html