Android implementation back function code fragment summary _android

Source: Internet
Author: User

The function methods of implementing the back key are:

One: Rewrite the onbackpressed method

Copy Code code as follows:

@Override
public void onbackpressed () {
Do something what for you want
Super.onbackpressed ();
}

Second: Use test framework instrumentation, simulate any key press action, note that this method can not be used in the main thread, only open new threads, the problem is that the reaction is slow, the project is not recommended.
Call the Onback () method, and generate a back-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 ();

 }

Three: This method is collected on the network, no code verification.

try{
  Runtime runtime=runtime.getruntime ();
  Runtime.exec ("Input keyevent" + keyevent.keycode_back);
 } catch (IOException e) {
  log.e ("Exception when Doback", e.tostring ());
 }

Four: 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 your want
			return true;//returns True, consumes the event, does not continue to invoke onbackpressed
		}
		Super.dispatchkeyevent (event);
	}

Five: This method is not the full meaning of the back key function, this method can only close the current activity, that is, for a single activity of the application is effective, if there are many external activity of the application it is powerless.

Copy Code code as follows:

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"/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.