android退出應用:彈出對話方塊退出應用
阿新 • • 發佈:2019-01-24
(1)定義棧,寫一個Exitactivity 類,利用單例模式管理Activity,在每個在
Activity 的onCreate()方法中呼叫Exitactivity.getInstance().addActivity(this)方法,在退
出時呼叫Exitactivity.getInstance().exit()方法,就可以完全退出應用程式了。這個主要建立了一個對話方塊退出activity
(2)Exitactivity類:
package com.liuzuyi.exit; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.Application; public class Exitactivity extends Application { private List<Activity> activityList=new LinkedList<Activity>(); private static Exitactivity instance; private Exitactivity() { } //單例模式中獲取唯一的ExitApplication 例項 public static Exitactivity getInstance() { if(null == instance) { instance = new Exitactivity(); } return instance; } //新增Activity 到容器中 public void addActivity(Activity activity) { activityList.add(activity); } //遍歷所有Activity 並finish public void exit() { for(Activity activity:activityList) { activity.finish(); } System.exit(0); } }
MainActivity:
package com.liuzuyi.exit; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private Button next; private Button exit; int i = 0; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); next=(Button)findViewById(R.id.button2); exit=(Button)findViewById(R.id.button1); next.setOnClickListener(l); exit.setOnClickListener(ll); Exitactivity.getInstance().addActivity(this); } OnClickListener l = new OnClickListener() { public void onClick(View v) { Intent intent=new Intent(MainActivity.this,TwoActivity.class); startActivity(intent); } }; OnClickListener ll = new OnClickListener() { @Override public void onClick(View v) { builddialog(); } }; public void builddialog() { AlertDialog.Builder ad = new Builder(MainActivity.this) ; ad.setTitle("退出應用"); ad.setMessage("是否退出應用?"); ad.setPositiveButton("確認", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Exitactivity.getInstance().exit(); } } ); ad.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.create().show(); } }
其他的兩個activity也是同樣的,可以參考上面的activity