定义一个android基类退出app
Activity基类:
package com.mayi.close_activity_by_broadcast.base; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; public class BaseActivity extends Activity { protected static final String TAG = "BaseActivity"; BroadcastReceiver mybroad=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Log.i(TAG, "退出APP"); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); IntentFilter filter=new IntentFilter(); filter.addAction("Exit APP"); this.registerReceiver(mybroad, filter); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); this.unregisterReceiver(mybroad); } }
test页面:
package com.mayi.close_activity_by_broadcast; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import com.mayi.close_activity_by_broadcast.base.BaseActivity; public class MainActivity extends BaseActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.exitapp).setOnClickListener(this); findViewById(R.id.otherActivity).setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.exitapp: Intent exit=new Intent(); exit.setAction("Exit APP"); sendBroadcast(exit); break; case R.id.otherActivity: Intent intent=new Intent(getApplicationContext(), Other.class); startActivity(intent); default: break; } } }