廣播service 和activity 之間的通訊
阿新 • • 發佈:2019-01-04
廣播service 和activity 之間的通訊
文章目錄
在avtivity 裡面建立內部的廣播接收者 broadcastReceive
動態註冊的時候一定要先註冊
注意在靜態註冊的時候因為是內部類,所以內部類在宣告時一定要寫成靜態內部類 (加上static))
靜態註冊
private WiFiConnectChangedReceiver wifiReceiver; private void registerWiFiConnectReceiver(){ IntentFilter filter = new IntentFilter(); filter.addAction("com.test");//只接受這個廣播 if (wifiReceiver == null) { wifiReceiver = new WiFiConnectChangedReceiver(); } registerReceiver(wifiReceiver, filter); } public static class WiFiConnectChangedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals("com.test")) { Log.e("ceshi","接收到"); } } }
動態註冊
private Context mContext; private MyRefreshReceiver refreshListReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext=this; IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction("com.test2"); refreshListReceiver=new MyRefreshReceiver(); this.registerReceiver(refreshListReceiver,intentFilter); } public class MyRefreshReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("資料","沒有"); Toast.makeText(context,"收到動態註冊",Toast.LENGTH_LONG).show(); } }