Android知识整理

Android 8.0 后台Service限制

2018-11-05  本文已影响0人  天真的小罗罗

Android O 后台启动Service崩溃问题

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

解决方法

public static void start() {
        Intent intent = new Intent(AppContext.me(), ScoreRefreshServer.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            AppContext.me().startForegroundService(intent);
        } else {
            AppContext.me().startService(intent);
        }
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
               //NotificationCompat.Builder builder =
               //new NotificationCompat.Builder(this, CHANNEL_ID)
               //         .setContentTitle("")
               //         .setContentText("");
            NotificationChannel channel = new NotificationChannel(AppEnv.UMENG_CHANNEL, getString(R.string.yoyo_name), NotificationManager.IMPORTANCE_MIN);
            channel.enableVibration(false);//去除振动

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) manager.createNotificationChannel(channel);

            Notification.Builder builder = new Notification.Builder(getApplicationContext(), AppEnv.UMENG_CHANNEL)
//                    .setContentTitle("正在后台运行")
                    .setSmallIcon(R.mipmap.logo);
            startForeground(1, builder.build());//id must not be 0,即禁止是0
}
上一篇下一篇

猜你喜欢

热点阅读