要在Android應用中接收廣播,可以通過以下步驟來實現:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 在這里處理接收到的廣播消息
}
}
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.MY_ACTION"/>
</intent-filter>
</receiver>
private MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("com.example.MY_ACTION");
registerReceiver(myReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
通過以上步驟,您的Android應用就可以成功接收到指定類型的廣播消息了。