【问题标题】:How to know whether an Android foreground service was started by OS or some user action?如何知道 Android 前台服务是由操作系统启动还是由某些用户操作启动的?
【发布时间】:2017-11-13 19:19:39
【问题描述】:

无论我的 Android 应用是运行还是关闭,我都需要保持服务运行(获取最新的位置更新)。

我终于为此使用了基于通知的前台服务,并且它可以很好地完成这项工作,除非并且直到应用程序关闭。 那么会发生什么:

  • 当应用在 UI 上或后台运行时,服务会完美地获取位置。
  • 当应用程序关闭时,即从最近的应用程序中删除,服务会以某种方式重新启动并且无法获取位置更新。

现在,我想了解该服务是由我的应用程序还是由 Android 操作系统启动的。有没有办法弄清楚?

我尝试了以下方法,但问题是intent 在由服务启动时并不总是为空。

public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(Constants.TAG + this.getClass().getSimpleName(), "Inside onStartCommand");

    if (null == intent) {

        Log.w(Constants.TAG, "Service was stopped and automatically restarted by the system.");
        BackgroundTaskHandler.startLocationMonitorServiceBySelf(this, 20 * 1000); // start after 20 sec
        Log.w(Constants.TAG, "Stopped self. Restarting again via alarm.");
        stopSelf();

    } else {
        // Other piece of code to setup location client 
        // and configure notification intent
    }

    return START_STICKY;
}

【问题讨论】:

    标签: android service foreground-service


    【解决方案1】:

    您可以更具体地检查 Intent 是否包含您的 Activity 设置的额外集合,而不是检查 Intent 是否为空。

    在你的活动中:

    Intent intent = new Intent(mContext, YourService.class);
    intent.putExtra("IntentFlag", "MainActivity");
    

    为您服务:

    if (intent.getStringExtra("IntentFlag").equals("MainActivity"))
    {
        //Service started by activity
    }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      相关资源
      最近更新 更多