Android exit Program (lower)-broadcast mechanism and android Mechanism
Overview:
Based on the previous blog 《Android exit Program (on)-singleton ModeWe learned how to exit our application by using singleton and loop traversal. This blog will solve the problem from another perspective-broadcast. That is, when receiving a broadcast that closes the Activity, it closes the current Activity.
Class chart display and description:
From the above class diagram, we can see that we have done a processing here, which is essential for Learning Object-oriented Coder. Here is an extension of Activity-BaseActivity. If we want to add an internal ExitappReceiver class to each Activity, this will inevitably increase the amount of code and will not be easy to maintain in the future. Therefore, ExitappReceiver is encapsulated into a base class, and other activities that need to be disabled can inherit from it.
Sample Code:
Here, only two key codes are posted:
1. Receive events
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. trigger event:
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); }}