Android: 从Intent服务启动服务

4
我已经在我的应用程序中启动了来自位置API的活动识别意图服务。我希望在用户活动发生变化时启动服务。但是我似乎无法让它起作用。以下是我尝试过的内容:
在活动识别意图服务的Intent Service类中:(编辑:在if条件中添加了日志。)
 @Override
 protected void onHandleIntent(Intent intent) 
 {
        // Get the update
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

        // Get the most probable activity from the list of activities in the update
        DetectedActivity mostProbableActivity = result.getMostProbableActivity();

        // Get the type of activity
        int currentActivity = mostProbableActivity.getType();      

        if(currentActivity == DetectedActivity.IN_VEHICLE)
        {
            Log.w("Rakshak", "in the if condition"); <-- this gets posted.
            sendNotification(); // this just send a notification that the service has started. 
            Intent i = new Intent(this, MyService.class);
            intent.setAction("start");
            startService(i);   <-- this dose'nt start the service. 

        }
}

在清单文件中:

 <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

 <application
     ....

     <service android:name="driver.rakshak.drivetrackeradmin.MyService"/>    

    <service android:name="driver.rakshak.drivetrackeradmin.ActivityRecognitionIntentService"/>  
 </application>

我有一个按钮,用户可以点击手动启动服务,这个功能正常工作。但当我想要自动启动服务时,它就不起作用了。
应用程序没有崩溃,所以我没有任何日志错误可供发布。
如果您需要查看更多代码,请告诉我。
谢谢。

你的 currentActivity 变量的值是多少? - r4jiv007
它被设置在关于“if语句”的那一行。我知道“if代码”被调用了,因为通知被发送了。 - DrkStr
请问您能分享一下您的AndroidManifest文件吗?另外,您需要设置这个动作为“start”吗? - leandrocastelli
我已经添加了(我认为的)Android清单文件中相关的部分。我已经注册了服务并拥有必要的权限。如果您需要查看更多清单,请告诉我。至于setAction(“start”),不,我认为我可以在没有它的情况下使其工作。但是如果我可以有它,我想要它。 - DrkStr
尝试为您的服务添加一个意图过滤器,以便针对“start”操作进行过滤。 - leandrocastelli
没有起作用。:( 我在应用程序UI中有一个按钮,允许用户手动启动此服务,这很好地工作。只有在意图服务中我想自动启动服务时它才不起作用。 - DrkStr
1个回答

3

由于IntentService的上下文在onHandleIntent返回后被销毁,因此通过以下方式创建的Intent不再有效:

Intent i = new Intent(this, MyService.class);

尝试通过getApplicationContext()创建Intent:

Intent i = new Intent(getApplicationContext(), MyService.class);

这可能会解决此问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接