<uses-permission android:name="android.permission.RESTART_PACKAGES" />
如果想直接退出程序可以创建出来整个应用程序的全局的实例
创建类App.java:
package cn.itcast.lunch; import java.util.ArrayList; import android.app.Activity; import android.app.Application; public class App extends Application { // 创建出来整个应用程序的全局的实例 ArrayList<Activity> activities; @Override public void onCreate() { // TODO 自动生成的方法存根 activities = new ArrayList<Activity>(); super.onCreate(); } }在每个activity中重写onCreate()方法和onDestroy()方法:
public void onCreate(Bundle savedInstanceState) { App app = (App) getApplication(); app.activities.add(this); super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onDestroy() { App app = (App) getApplication(); app.activities.remove(this); super.onDestroy(); }退出程序代码:
App app = (App) getApplication();
for (Activity a : app.activities) {
a.finish();
}
在资源文件夹下新建menu文件夹,新建menu.xml文件:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/close_all" android:icon="@drawable/ic_launcher" android:title="完全退出"/> <item android:id="@+id/close_this" android:icon="@drawable/ic_launcher" android:title="退出当前"/> </menu>应用部分代码:
package cn.itcast.lunch; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; public class Demo1Activity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { App app = (App) getApplication(); app.activities.add(this); super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onDestroy() { App app = (App) getApplication(); app.activities.remove(this); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO 自动生成的方法存根 MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.close_all: //ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); // 只能杀死别的application 不能杀死自己 // manager.restartPackage(getPackageName()); App app = (App) getApplication(); for (Activity a : app.activities) { a.finish(); } return true; case R.id.close_this: finish(); return true; default: return super.onOptionsItemSelected(item); } } public void startDemo1(View view) { Intent intent = new Intent(this, Demo1Activity.class); startActivity(intent); } public void startDemo2(View view) { Intent intent = new Intent(this, Demo2Activity.class); startActivity(intent); } }截图: