Summary of Android implementation Back functional code snippets

  • 2020-06-03 08:27:12
  • OfStack

Methods to realize Back key function are as follows:

1: Override onBackPressed method


@Override
 public void onBackPressed() {
  // do something what you want
  super.onBackPressed();
 }

2: The test framework Instrumentation was used to simulate the action of pressing any key. It was noted that this method could not be used in the main thread, and only new threads could be started. The problem was that the response speed was slow, which was not recommended in the project.
Call the onBack() method; Produces the back key click effect


public void onBack(){
 new Thread(){
  public void run() {
  try{
   Instrumentation inst = new Instrumentation();
   inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
  }
  catch (Exception e) {
         Log.e("Exception when onBack", e.toString());
       }
  }
 }.start();

 }

3: This method is collected on the network without code verification.


try{
  Runtime runtime=Runtime.getRuntime();
  runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
 }catch(IOException e){
  Log.e("Exception when doBack", e.toString());
 }

4: Rewrite dispatchKeyEvent


@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			//do something what you want
			return true;// return true , consumes the event, does not continue to call onBackPressed
		}
		return super.dispatchKeyEvent(event);
	}

5: This method is not fully functional with the Back key. It can only turn off the current Activity, which is valid for an application with a single Activity, but not for an application with multiple Activity.


public void exitProgrames(){
android.os.Process.killProcess(android.os.Process.myPid());
}

Additional permissions are required to use this method: < uses-permission android:name="android.permission.RESTART_PACKAGES" / >


Related articles: