Android安全退出應用程式

來源:互聯網
上載者:User

  1. 殺死進程。 這種方法是沒有效果的只能殺死當前的Activity無法關閉程式,在1.5的時候有用,Google設計的時候規定程式不能自殺android.os.Process.killProcess(android.os.Process.myPid()).
  2. 終止當前正在啟動並執行Java虛擬機器,導致程式終止. 這種方法也是沒有效果的,因為Android用的是dalvik虛擬機器 System.exit(0);
  3. 強制關閉與該包有關聯的一切執行 這種方法只能殺死別人,無法殺死自己
    java ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); manager.restartPackage(getPackageName()); 同時需要申請許可權

    既然上面介紹的三種方法都沒有效果,那麼怎麼才能退出應用程式呢?
    就是自訂一個Application,在該Application中去定義一個List的集合來記錄中每一個開啟的Activity,在退出的時候去遍曆這個List集合,然後挨個的進行mActivity.finish()方法,這要求在每開啟一個Activity的時候都加入到List集合中,並且在Activity退出的時候從List集合中將其移除。
    ```java public class Activity01 extends Activity {

    @Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    MyApp myApp = (MyApp) getApplication();    myApp.activies.add(this);}@Overrideprotected void onDestroy() {    super.onDestroy();    MyApp myApp = (MyApp) getApplication();    myApp.activies.remove(this);}public void click1(View view){    Intent intent = new Intent(this,Activity01.class);    startActivity(intent);}public void click2(View view){    Intent intent = new Intent(this,Activity02.class);    startActivity(intent);}public void exit(View view){    MyApp myApp = (MyApp) getApplication();     for(Activity ac : myApp.activies){         ac.finish();     }}

    }

    public class Activity02 extends Activity {

    @Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main2);    MyApp myApp = (MyApp) getApplication();    myApp.activies.add(this);}public void click1(View view) {    Intent intent = new Intent(this, Activity01.class);    startActivity(intent);}public void click2(View view) {    Intent intent = new Intent(this, Activity02.class);    startActivity(intent);}public void exit(View view) {    MyApp myApp = (MyApp) getApplication();    for (Activity ac : myApp.activies) {        ac.finish();    }}@Overrideprotected void onDestroy() {    super.onDestroy();    MyApp myApp = (MyApp) getApplication();    myApp.activies.remove(this);}

    }

    public class MyApp extends Application { //存放當前應用程式裡面開啟的所有的activity public List activies; @Override public void onCreate() { activies = new ArrayList(); super.onCreate(); } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.