ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Android:从Intent服务启动服务

2019-11-21 15:28:48  阅读:372  来源: 互联网

标签:intentservice android service


我已经在我的应用程序中运行了位置识别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);

这可能会解决此问题.

标签:intentservice,android,service
来源: https://codeday.me/bug/20191121/2052650.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有