微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android:从Intent服务启动服务

我已经在我的应用程序中运行了位置识别API的活动识别意图服务.我想在用户活动更改时启动一项服务.但我似乎无法使其正常工作.这是我尝试过的:

在活动识别意图服务的意图服务类中:(编辑:将日志添加到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>

我有一个按钮,用户可以单击该按钮以手动启动该服务,并且工作正常.只有在我希望该服务自动启动时,它才起作用.

该应用程序不会崩溃,因此从发布的日志中没有任何错误.

让我知道是否需要查看更多代码.

干杯.

解决方法:

由于在onHandleIntent返回之后IntentService的Context被销毁,因此由

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

不再有效.

尝试通过getApplicationContext()创建您的Intent

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

这可能会解决此问题.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐