Android:从意向服务启动服务
我已经在我的应用程序中运行了位置API的活动识别意图服务表单。我想在用户活动更改时启动服务。但我似乎无法让它工作。以下是我尝试过的: 在活动识别意图服务的意图服务类中:(编辑:将日志添加到if条件。)Android:从意向服务启动服务,android,service,intentservice,Android,Service,Intentservice,我已经在我的应用程序中运行了位置API的活动识别意图服务表单。我想在用户活动更改时启动服务。但我似乎无法让它工作。以下是我尝试过的: 在活动识别意图服务的意图服务类中:(编辑:将日志添加到if条件。) @覆盖 受保护的手部内容无效(意图) { //获取更新 ActivityRecognitionResult=ActivityRecognitionResult.extractResult(意图); //从更新中的活动列表中获取最可能的活动 DetectedActivity mostProbable
@覆盖
受保护的手部内容无效(意图)
{
//获取更新
ActivityRecognitionResult=ActivityRecognitionResult.extractResult(意图);
//从更新中的活动列表中获取最可能的活动
DetectedActivity mostProbableActivity=result.getMostProbableActivity();
//获取活动的类型
int currentActivity=mostProbableActivity.getType();
if(currentActivity==车辆中检测到的活动)
{
Log.w(“Rakshak”,“在if条件下”);由于在onHandleIntent返回后IntentService的上下文被破坏,因此
Intent i=新Intent(this,MyService.class)
不再有效了
尝试通过getApplicationContext()创建您的意图
Intent i=newintent(getApplicationContext(),MyService.class)
这可能会解决这个问题。currentActivity变量的值是多少?它在关于“if语句”的行中设置。我知道“if代码”会被调用,因为通知会被发送。您可以共享您的AndroidManifest吗?另外,您需要将此操作设置为“开始”吗?我已经添加了(我认为是)Android清单文件中的相关位。我已经注册了该服务,并拥有必要的权限。如果您需要查看更多的清单,请告诉我。至于setAction(“开始”),不,我认为我可以使用它。但是如果我可以将其放入,我想。尝试在您的服务中添加一个针对该操作的意图过滤器“开始”。
@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>