代码之家  ›  专栏  ›  技术社区  ›  Karzel

未创建在单独进程上运行的Android服务

  •  0
  • Karzel  · 技术社区  · 7 年前

    我已经按照Radioondra57的步骤 Intent Service not working in doze mode 我遇到了一个问题,在启动服务之后,从未调用此服务的onCreate。这是我的设置:

    显示:

        <service
            android:name=".service.Smart113MainService"
            android:enabled="true"
            android:exported="true"
            android:process=":antiDozeProcessName"
            android:label="LocationService">
        </service>
    

     private void startServices() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startService(new Intent(this, Smart113MainService.class));
        } 
     }
    

    服务:

        @Override
    public void onCreate() {
        super.onCreate();
        doingSomeStuff();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(Smart113NotificationFactory.locationSharingNotificationId, notification.logIntoAppNotification(this).build());
        doingMoreStuff();
        return START_STICKY;
    }
    

    这是不是因为我没有按照发送的意图设置操作?这是我在代码中看到的唯一区别。。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Khemraj Sharma    7 年前
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
      startService(new Intent(this, Smart113MainService.class));
    }
    else {
      startForegroundService(new Intent(this, Smart113MainService.class));
    }
    

    移动 startForeground 编码到 onCreate()

    @Override
    public void onCreate() {
        ...
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(NOTIFICATION_ID, notification);
        }
        ...
    }
    

    删除通知 onDestroy()

    @Override
    public void onDestroy() {
        ...
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              stopForeground(true); //true will remove notification
        }
        ...
    }
    

    您没有在不同的进程中获得调试点,因为您正在从附加调试器中选择主进程。选择要调试的正确进程。