Android使用廣播退出應用

來源:互聯網
上載者:User

應用開發時需要處理安全退出應用,之前研究過Foursquare的代碼,發現它用的是廣播機制來處理退出應用。


public class BaseActivity extends Activity{    private static final String TAG = BaseActivity.class.getSimpleName();        public static final String INTENT_ACTION_LOGGED_OUT = "INTENT_ACTION_LOGGED_OUT";        private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver()    {        @Override        public void onReceive(Context context, Intent intent)        {            Log.d(TAG, "onReceive: " + intent);            finish();        }    };        @Override    protected void onCreate(Bundle arg0)    {                super.onCreate(arg0);        registerReceiver(mLoggedOutReceiver, new IntentFilter(                INTENT_ACTION_LOGGED_OUT));    }        @Override    protected void onPause()    {                super.onPause();        if (isFinishing())        {            unregisterReceiver(mLoggedOutReceiver);        }    }    }

讓每個Activity繼承BaseActivity, 當推出應用的時候,發送一條廣播,應用就能安全的退出。


網上有另外一種退出方法:在Application中用List記錄開啟的Activity的context,在退出的時候,遍曆List,依次fiinish activity,這種方法的問題是會一直持有改Activity的context, 使之不能及時釋放資源,如果跳轉的頁面很多的話容易照成OOM

聯繫我們

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