400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

Android8.0中怎么开启service

本篇文章为大家展示了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. 添加权限



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,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。


网站栏目:Android8.0中怎么开启service
网页URL:http://www.bluegullmedia.com/article/igishe.html

其他资讯

让你的专属顾问为你服务

0.0500s