我只是在尝试这个小示例项目,它所做的一切: Activity 一有一个发送广播的按钮。 Activity 二在收到时会显示 toast 。 下面是代码,广播永远不会收到。我做错了什么?
发送广播
public class SendBroadcast extends Activity {
public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void sendBroadcast(View v){
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
sendBroadcast(broadcast);
}
}
收到
public class ToastDisplay extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);
}
};
@Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(SendBroadcast.BROADCAST_ACTION);
registerReceiver(receiver, filter);
super.onResume();
}
@Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
}
list
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SendBroadcast" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ToastDisplay">
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"></action>
</intent-filter>
</activity>
</application>
最佳答案
What do I do wrong?
ToastDisplay 的源代码是可以的(我的类似并且可以工作),但它只会接收一些东西,如果它当前在前台(你在 onResume 中注册接收器)。但如果显示不同的 Activity (在本例中为 SendBroadcast Activity ),它就无法接收任何内容。
相反,您可能想要 startActivity从第一个 Activity 开始的 ToastDisplay?
BroadcastReceiver 和 Activity 在不同的用例中有意义。 In my application我需要从后台 GPS 跟踪服务接收通知并在 Activity 中显示它们(如果 Activity 在前台中)。
无需在 list 中注册接收器。在我的用例中,它甚至会有害 - 我的接收器操纵 Activity 的 UI,如果 Activity 当前未显示,则在 onReceive 期间 UI 将不可用。相反,我在 onResume 和 onPause 中为 Activity 注册和取消注册接收器,如中所述 BroadcastReceiver documentation :
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
关于Activity 中的 Android BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4555215/