Android8.0中怎么开启service

发布时间:2021-06-26 14:40:05 作者:Leah
来源:亿速云 阅读:389

本篇文章为大家展示了Android8.0中怎么开启service,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

原因

Android 8.0 有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。 在系统创建服务后,应用有5秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

遇到的问题

但是目前在调用:context.startForegroundService(intent)时报如下ANR,startForegroundService()文档说明在service启动后要调用startForeground()。

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

完整解决步骤:

1. 添加权限

<!--android 9.0上使用前台服务,需要添加权限,此权限为级别为nomarl-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

2. 启动server(引用启动5秒内要启动server)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       context.startForegroundService(new Intent(context, MyService.class));
   } else {
       context.startService(new Intent(context, MyService.class));
   }

然后必须在Myservice中调用startForeground():

3. Server中onCreate方法中调用startForeground()

public static final String CHANNEL_ID_STRING = "service_01";
private Notification notification;
   @Override
   public void onCreate() {
       super.onCreate();
       //适配8.0service
       NotificationManager notificationManager = (NotificationManager) MyApp.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
       NotificationChannel mChannel = null;
       if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
           mChannel = new NotificationChannel(CHANNEL_ID_STRING, getString(R.string.app_name),
                   NotificationManager.IMPORTANCE_LOW);
           notificationManager.createNotificationChannel(mChannel);
           notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
           startForeground(1, notification);
       }
}

4. 在onStart里再次调用startForeground()

@Override
public void onStart(Intent intent, int startId) {
   super.onStart(intent, startId);

   if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
       startForeground(1, notification);
   }

}

注解:

上述内容就是Android8.0中怎么开启service,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Service 中的Intent service
  2. Android8.0适配那点事(二)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android service

上一篇:如何解决vue中echart 在子组件中只显示一次的问题

下一篇:Android中怎么实现事件分发机制

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》