java 强制下线_Android连载24-本地广播和强制下线功能

packagecom.example.broadcasttest2;importandroid.app.Activity;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.net.ConnectivityManager;importandroid.net.NetworkInfo;importandroid.os.Bundle;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.Toast;public class MainActivity extendsActivity {privateIntentFilter intentFilter;privateLocalReceiver localReceiver;privateLocalBroadcastManager localBroadcastManager;privateNetworkChangeReceiver networkChangeReceiver;

@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

intentFilter= newIntentFilter();

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

networkChangeReceiver= newNetworkChangeReceiver();

registerReceiver(networkChangeReceiver,intentFilter);

localBroadcastManager= LocalBroadcastManager.getInstance(this);//获取实例

Button button=(Button) findViewById(R.id.button);

button.setOnClickListener(newOnClickListener() {

@Overridepublic voidonClick(View v) {//下面这行代码是用来全局广播的//Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");//下面这行代码是用来本地广播的(也就是app内部传递广播)

Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");

localBroadcastManager.sendBroadcast(intent);//发送本地广播//sendBroadcast(intent);//我们关闭上面一行代码,然后写另一种方法sendOrderedBroadcast,发送有序广播

sendOrderedBroadcast(intent,null);

}

});

intentFilter= newIntentFilter();

intentFilter.addAction("com.example.broadcasttest.LOCAL_BROACAST");

localReceiver= newLocalReceiver();

localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册本地广播监听器

}

@Overrideprotected voidonDestroy() {super.onDestroy();//unregisterReceiver(networkChangeReceiver);

localBroadcastManager.unregisterRecerver(localReceiver);

}class NetworkChangeReceiver extendsBroadcastReceiver{

@Overridepublic voidonReceive(Context context,Intent intent) {

ConnectivityManager connectionMananger=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo=connectionMananger.getActiveNetworkInfo();if(networkInfo != null &&networkInfo.isAvailable()) {

Toast.makeText(context,"network is available", Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(context,"network is unavailable", Toast.LENGTH_SHORT).show();

}

}

}class LocalReceiver extendsBroadcastReceiver {

@Overridepublic voidonReceive(Context context,Intent intent) {

Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值