android 基于BroadcastReceiver广播 完全退出应用的实现代码 亲测可以

关于android退出系统的代码网上很多

但大部分是不行的,比如 

 

System.exit(0);//只能退出当前activity

还有

ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

activityMgr.restartPackage(getPackageName());

等都能对当前activity,可有时我们的activity 实例不只一个


这里有一个很好的办法就是使用广播BroadcastReceiver(广播的介绍自己去google下),这里直接贴出代码,代码可以在一个基础Activity然后其他Activity继承改基类, 也可以写到每个activity里,以下代码是直接写到activity里

MainActivity.java

public class MainActivity extends  Activity{
       public final static String BORADCAST_ACTION_EXIT = "com.wangzhj.exit";//关闭活动的广播action名称
       ........
       @Override
	protected void onCreate(Bundle savedInstanceState) {
		........
           // 在当前的activity中注册广播  
            IntentFilter filter = new IntentFilter();
            filter.addAction(BORADCAST_ACTION_EXIT);//为BroadcastReceiver指定一个action,即要监听的消息名字
            registerReceiver(mBoradcastReceiver,filter); //动态注册监听  静态的话 在AndroidManifest.xml中定义
	}
	private BroadcastReceiver mBoradcastReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(BORADCAST_ACTION_EXIT)){//发来关闭action的广播
				finish();
			}
		}
	};
	@Override
	protected void onDestroy() {
 		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mBoradcastReceiver); //取消监听
	}
	//返回按钮 退出系统
	@Override
	public void onBackPressed() {  
		new AlertDialog.Builder(this)
		.setTitle("提示")
		.setMessage("请确认退出系统?")
		.setPositiveButton("退出", new DialogInterface.OnClickListener() { 
								        @Override 
								        public void onClick(DialogInterface dialog, int which) { 
								        	Intent intent = new Intent();
								        	intent.setAction(BORADCAST_ACTION_EXIT);
								        	sendBroadcast(intent);//发送退出系统广播  每个接收器都会收到 调动finish()关闭activity
								        	finish();
								        }
									})
		.setNegativeButton("按错了...", null)
		.show();
    }
.......
}

另外一个activity.java

public class OtherActivity extends Activity {
         .......
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
              // 在当前的activity中注册广播  
              IntentFilter filter = new IntentFilter();
              filter.addAction(MainActivity.BORADCAST_ACTION_EXIT);//为BroadcastReceiver指定一个action,即要监听的消息名字
              registerReceiver(mBoradcastReceiver,filter); //动态注册监听  静态的话 在AndroidManifest.xml中定义
	}
	private BroadcastReceiver mBoradcastReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(MainActivity.BORADCAST_ACTION_EXIT)){//发来关闭action的广播
				finish();
			}
		}
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mBoradcastReceiver); //取消监听
	}
........

}

如果有多个activity都加上以上代码就可以实现程序完全退出功能。



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