使用adb命令启动service报app is in background uid null解决

在本地调试app中的一个service时,使用adb shell am startservice弹出报错

错误信息如下:app is in background uid null,如图:

查了一些帖子发现提供的2018年左右的解决方案为:

Settings->Build,Execution,Deployment->Instant Run

关掉 Enable Instant Run to hot swap code/ 

尝试失效。

后续找到解决方案:

adb shell am start-foreground-service -n com.demo.screenrecorder/com.demo.screenrecorder.RecordService

使用这个start-foreground-service来替换startservice可以解决这个问题。特此记录。

PS:Android O 推出出了Background Execution Limits,减少后台应用内存使用及耗电,一个很明显的应用就是不准后台应用通过startService启动服务。

解决方案就是及时调用startForeground,对于O以后的还要注意Notification需要一个ChannelID

@Override

public void onCreate() {

super.onCreate();

    try {

String CHANNEL_ONE_ID ="com.demo.screenrecorder";

        String CHANNEL_ONE_NAME ="Channel One";

        NotificationChannel notificationChannel =null;

        notificationChannel =new NotificationChannel(CHANNEL_ONE_ID,

                CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_DEFAULT);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        assert manager !=null;

        manager.createNotificationChannel(notificationChannel);

        startForeground(1, new NotificationCompat.Builder(this, CHANNEL_ONE_ID).build());

    }catch (Exception e) {

Log.e(TAG, e.getMessage());

    }

initView();

}

推荐阅读:Android O 后台startService限制简析

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

推荐阅读更多精彩内容