Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android退出程序(下)——利用廣播機制

Android退出程序(下)——利用廣播機制

編輯:關於Android編程

概述:

基於上一篇博客《Android退出程序(上)——單例模式》的學習,我們知道了如何利用單例和循環遍歷的方式來退出我們的應用程序。這篇博客則要從另一個角度來解決問題——廣播。即是,接收到一個關閉Activity的廣播時,就去關閉當前Activity。


類圖展示及說明:

vcHL0ru49rv5tKHA4NbQo6zIu7rzyMPG5Mv70OjSqsq1z9a52LHVYWN0aXZpdHm1xEFjdGl2aXR5wLS8zLPQy/y+zbrDwcuhozwvcD4KPHA+PGJyPgo8L3A+CjxoMT60+sLryr7A/aO6PC9oMT4KPHA+1eLA79a7zPmz9sG9uPaxyL3Pudi8/LXEtPrC66O6PC9wPgo8aDI+MS6908rVysK8/jwvaDI+CjxwPjxwcmUgY2xhc3M9"brush:java;">public class BaseActivity extends Activity { public static final String TAG = BaseActivity.class.getName(); public static final String BROAD_CAST_MESSAGE = TAG + ".BROAD_CAST_MESSAGE"; private ExitappReceiver mReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(); } private void registerReceiver() { IntentFilter filter = new IntentFilter(); try { if (mReceiver != null) { unregisterReceiver(mReceiver); } } catch (Exception e) { e.printStackTrace(); } mReceiver = new ExitappReceiver(); filter.addAction(BROAD_CAST_MESSAGE); registerReceiver(mReceiver, filter); } @Override protected void onDestroy() { if (mReceiver != null) { unregisterReceiver(mReceiver); } super.onDestroy(); } class ExitappReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(BROAD_CAST_MESSAGE)) { finish(); } } } }

2.觸發事件:

public class TwoActivity extends BaseActivity {

    private int getLayoutResID() {
        return R.layout.activity_two;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(getLayoutResID());
        
        Button nextButton = (Button) findViewById(R.id.activity_two_button);
        nextButton.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                sendBroadcast();
            }
        });
    }
    
    private void sendBroadcast() {
        Intent intent = new Intent();
        intent.setAction(BaseActivity.BROAD_CAST_MESSAGE);
        sendBroadcast(intent);
    }
}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved