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);

这可能会解决此问题.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...