广播service 和activity 之间的通信

广播service 和activity 之间的通信

文章目录

    • 广播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();
    }
}

你可能感兴趣的:(Android开发)