4月7日学习日志
今天学习了监听广播。
public class MyBRReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"网络状态发生改变~",Toast.LENGTH_SHORT).show(); } }
public class MainActivity extends AppCompatActivity { MyBRReceiver myReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //核心部分代码: myReceiver = new MyBRReceiver(); IntentFilter itFilter = new IntentFilter(); itFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(myReceiver, itFilter); } //别忘了将广播取消掉哦~ @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(myReceiver); } }