【发布时间】:2014-04-27 06:59:44
【问题描述】:
我尝试使用IntentService 将广播从服务发送到活动,为此我使用了以下代码:
public class NotifyService extends IntentService {
public NotifyService() {
super("NotifyService");
}
// will be called asynchronously by Android
@Override
protected void onHandleIntent(Intent intent) {
Log.d("onHandleIntent", "start service");
publishResults();
}
private void publishResults() {
result = Activity.RESULT_OK;
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
然后我在 Activity 类中定义我的接收器,例如:
public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "receiver");
Bundle bundle = intent.getExtras();
if (bundle != null) {
int resultCode = bundle.getInt(NotifyService.RESULT);
if (resultCode == RESULT_OK) {
Toast.makeText(Home.this, "after service work.", Toast.LENGTH_LONG)
.show();
}
}
stopService(new Intent(Home.this,NotifyService.class));
}
};
我在onResume 中使用了registerReceiver,在onPause 方法中使用了unregisterReceiver
registerReceiver(receiver, new IntentFilter(NotifyService.NOTIFICATION));
但是onReceive 方法没有被调用,
我用过This Site的第7节
我错过了什么?
编辑
我有其他解决方案吗?我已尝试通过服务通知活动以更新数据。
【问题讨论】:
-
你确定你的服务已经启动了吗?
Log.d("onHandleIntent", "start service");此日志已打印? -
是的@ArtemZinnatullin
-
当您的接收器未注册时,您是否正在发送广播意图?因为你的代码看起来很正常:)
-
@ArtemZinnatullin 我在
onResume方法中注册了接收器,并且我在活动运行时发送广播,所以我认为接收器没有注册是没有原因的。感谢回复 -
您不必在
IntentService上显式使用stopService,这已经为您处理好了。虽然我怀疑这是你问题的根源......
标签: android intentservice android-intentservice