我尝试使用 将广播从服务发送到活动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));
}
};
我用过registerReceiver
inonResume
和unregisterReceiver
inonPause
方法
registerReceiver(receiver, new IntentFilter(NotifyService.NOTIFICATION));
但是该onReceive
方法没有被调用,
我已使用本网站的第 7 部分
我错过了什么?
编辑
我有任何替代解决方案吗?我尝试通知服务活动以更新数据。