ブロードキャスト受信機の動的登録、ネットワークの変化の傍受

3371 ワード

1:NetChangeReceiver.java
public class NetChangeReceiver extends BroadcastReceiver{



    @Override

    public void onReceive(Context context, Intent intent) {

        ConnectivityManager cm = (ConnectivityManager)

                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if(netInfo!=null && netInfo.isAvailable()){

            Toast.makeText(context, " ", Toast.LENGTH_SHORT).show();

        }else{

            Toast.makeText(context, " ", Toast.LENGTH_SHORT).show();

        }

    }

    

}

2:MainActivity.java
public class MainActivity extends Activity {

    IntentFilter intentFilter;

    NetChangeReceiver netChangeReceiver;

    

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        intentFilter = new IntentFilter();

        // , android.net.conn.CONNECTIVITY_CHANGE , 

        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        netChangeReceiver = new NetChangeReceiver();

        // 

        registerReceiver(netChangeReceiver, intentFilter);

    }

    

    

    @Override

    protected void onDestroy() {

        super.onDestroy();

        // 

        unregisterReceiver(netChangeReceiver);

    }

}

3:最後に権限の宣言を忘れないでください.
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>