Android退出當前應用程式的方法

來源:互聯網
上載者:User

Android的視窗類別提供了曆史棧,我們可以通過stack的原理來巧妙的實現,這裡我們在D視窗開啟A視窗時在Intent中直接加入標誌Intent.FLAG_ACTIVITY_CLEAR_TOP,再次開啟A時將會清除該進程空間的所有Activity。
在D中使用下面的代碼:
Intent intent = new Intent();
intent.setClass(D.this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG設定
startActivity(intent);
finish();關掉自己
在A中加入代碼:
Override

protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub

super.onNewIntent(intent);

//退出

if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0) {

finish();

}

}

A的Manifest.xml配置成android:launchMode="singleTop"

原理總結:
一般A是程式的進入點,從D起一個A的activity,加入標識Intent.FLAG_ACTIVITY_CLEAR_TOP這個過程中會把棧中B,C,都清理掉。因為A是android:launchMode="singleTop"
不會調用oncreate(),而是響應onNewIntent()這時候判斷Intent.FLAG_ACTIVITY_CLEAR_TOP,然後把A finish()掉。
棧中A,B,C,D全部被清理。所以整個程式退出了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.