我正在尝试在服务中执行某些操作后更新UI(Activity)。这是一个非常简单的例子,但它似乎对我不起作用。我在这里缺少什么?
ExampleService:
public class ExampleService extends IntentService{
@Override
protected void onHandleIntent(Intent intent) {
notifyActivity();
}
private void notifyActivity() {
Intent broadcast = new Intent(this, ExampleActivity.class);
sendBroadcast(broadcast);
}
}
为ExampleActivity:
public class ExampleActivity extends ListActivity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
registerReceiver(receiver, filter);
}
}
答案 0 :(得分:1)
您不能以这种方式向匿名动态接收器发送广播。您需要在Intent
中定义一个操作字符串,并在IntentFilter
中使用该操作字符串。
您可以考虑在此方案中使用LocalBroadcastManager
,以获得更好的性能。 Here is a sample project证明了这一点。