Android全域退出的兩種方法

來源:互聯網
上載者:User

標籤:

第一種方法參考《第一行代碼》78頁

建立一個ActivityCollector類,提供靜態方法addActivity,fininshAll(以list為容器)

然後我們建立的Activity都繼承一個BaseActivity,在BaseActivity中的oncreate方法中,使用ActivityCollector的addActivity(this),

想要隨時全域退出只要調用ActivityCollector.finishAll()

 

 

今天在看到另一個和Activity啟動模式有關的全域退出方法

 

 

 

我們寫了三個Activity,然後設定textView的點擊事件,跳轉下一個Activity,這時候我們想在第二個或第三個Activity直接退出,該怎麼做

 

第一步:設定MainActivity的 android:launchMode="singleTask"

 

singleTask
  • 判斷Activity所需任務棧內是否已經存在,如果存在,就把該Activity切換到棧頂(會導致在它之上的都會出棧)
  • 如果所需任務棧都不存在,就會先建立任務棧再建立該Activity
  • 可以理解為 頂置Activity+singleTop 的模式

 

第二步:我們建立一個BackUtils類

import android.app.Activity;import android.content.Intent;public class BackUtils {    public static void allBack(Activity activity){        Intent intent=new Intent(activity, MainActivity.class);        activity.startActivity(intent);    }}

類中的AllBack方法就是去啟動MainActivity。

我們可以在其他Activity中複寫

@Override
    public void onBackPressed() {
        
        super.onBackPressed();
        BackUtils.allBack(this);
    }

這時候,可以思考到,MainActivity是singletask,這樣來到MainActivy,棧中MainActivy上面的都會出棧,但是這時候還剩下一個MainActivity,

我們做的就是要來到MainActivity後立即銷毀它。

這時,剛好存在方法

@Override
    protected void onNewIntent(Intent intent) {
        
        super.onNewIntent(intent);
        finish();
    }

 

對於這個方法

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the Intent.FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity. In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume being called after this method.

 

這裡的onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.我們的MainActivity使我們進去App的第一個介面,所以必然已經存在,當設定singleTop或者singleTask時,會調用onNewIntent()。

我們只要在onNewIntent()調用finish。

 

Android全域退出的兩種方法

聯繫我們

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