标签:接收 取消 xtend adc over man tin 权限 public
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private NetworkChangedReceiver networkChangedReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangedReceiver = new NetworkChangedReceiver();
registerReceiver(networkChangedReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangedReceiver);
}
class NetworkChangedReceiver extends BroadcastReceiver
{
@Override
public void onReceive (Context context,Intent intent)
{
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null && networkInfo.isAvailable())
{
Toast.makeText(context,"good",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(context,"bad",Toast.LENGTH_LONG).show();
}
}
}
}
之后再Mainfest中声明权限
并说明要监听的广播
sendOrderedBroadcast(intent,null); 发送有序广播
abortBroadcast() 截断广播
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到本地广播管理器的实例
localBroadcastManager = LocalBroadcastManager.getInstance(this);
//动态注册本地广播接收器
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
//发送本地广播
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消动态网络变化广播接收器的注册
localBroadcastManager.unregisterReceiver(localReceiver);
}
class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
}
}
}
标签:接收 取消 xtend adc over man tin 权限 public
原文地址:https://www.cnblogs.com/lancelee98/p/9468119.html