android 服务启动活动,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");

sendNotification(); // this just send a notification that the service has started.

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

intent.setAction("start");

startService(i);

}

}

在清单中:

....

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

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

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

干杯.

解决方法:

由于在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值