Android to monitor the home key method for detailed _android

Source: Internet
Author: User

This example analyzes the way Android listens on the home key. Share to everyone for your reference, specific as follows:

How do I know if the home button is clicked? When doing launcher, look at the source code to find out why

If your activity has these attributes

<activity
 android:name= "com.woyou.activity.HomeActivity"
 android:launchmode= "SingleInstance" >
 <intent-filter>
  <action android:name= "Android.intent.action.MAIN"/>
  <category Android:name= "Android.intent.category.DEFAULT"/>
  <category android:name= "Android.intent.category.HOME" "/>
  <category android:name=" Android.intent.category.LAUNCHER "/>
 </intent-filter>
</activity>

When the system clicks the Home button, the system sends a intent to the activity with these properties

Then you rewrite the Onnewintent method of the activity.

This method will callback the Onnewintent

Verified available!

Here's the way I've been writing to monitor the home button, which I've written before is not very useful. This is the way to listen to the home key in a broadcast way, which is better

1. First, create a broadcast recipient

Private Broadcastreceiver Mhomekeyeventreceiver = new Broadcastreceiver () {
  String System_reason = "REASON";
  String System_home_key = "HomeKey";
  String System_home_key_long = "Recentapps";
  @Override public
  void OnReceive (context context, Intent Intent) {
   String action = intent.getaction ();
   if (Action.equals (intent.action_close_system_dialogs)) {
    String reason = Intent.getstringextra (System_reason);
    if (textutils.equals (reason, System_home_key)) {
      //indicates that the home key is pressed, the program is in the background
     Toast.maketext ( Getapplicationcontext (), "Home", 1). Show ();
    else if (textutils.equals (reason, System_home_key_long)) {
     //Represents the long press home key, displays the most recently used program list
    }
}} };

2. Registration Monitor

can be registered in the activity or in the service

Registered broadcast
Registerreceiver (Mhomekeyeventreceiver, New Intentfilter (
  intent.action_close_system_dialogs));

The complete code is as follows:

Package Com.example.homedemo;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import Android.text.TextUtils;
Import Android.view.Menu;
Import Android.widget.Toast; public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {SUPER.ONCR
  Eate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
 Registered broadcast Registerreceiver (mhomekeyeventreceiver, New Intentfilter (Intent.action_close_system_dialogs));  /** * Monitor Whether click on the home button to push the client to the background/private broadcastreceiver mhomekeyeventreceiver = new Broadcastreceiver () {String
  System_reason = "REASON";
  String System_home_key = "HomeKey";
  String System_home_key_long = "Recentapps";
   @Override public void OnReceive (context context, Intent Intent) {String action = intent.getaction (); if (Action.equals (intent.action_close_sYstem_dialogs)) {String reason = Intent.getstringextra (System_reason); if (textutils.equals (reason, System_home_key)) {//indicates that the home key is pressed, the program is in the background toast.maketext (Getapplicationcontext (), "ho
    Me ", 1). Show ();
}else if (textutils.equals (reason, System_home_key_long)) {//Indicates the most recently used list of Programs}}} by pressing the home key for a long time;

 }

Here is the previous written listening mode, now most of them are not good, this time as an update:

Monitoring the home key has been bothering this everyone, but also let everyone very tangled problem, from my article clicks on the volume, I know how difficult this problem can be solved.

Here is another change, the first part is to solve 2.2 or before the system version of Home monitoring, the second part is 4.0.x of home monitoring

The first part:

If you want to monitor the home key, there are several ways to implement it

The first way: Android to listen to the home key, plus permissions, must obtain the right to handle the home key events to operate on the home key,

Valid only for 2.2 and previous systems.

1, plus permission

<uses-permission 
android:name= "Android.permission.DISABLE_KEYGUARD"/>

is to let the keyboard guard lose the ability, according to English general is this meaning

2, overload the following two methods @override

public boolean onKeyDown (int keycode, keyevent event) {
 if (keyevent.keycode_home==keycode) {
  //write the action or task to perform
   android.os.Process.killProcess (Android.os.Process.myPid ());
 }
 Return Super.onkeydown (KeyCode, event);
}
@Override public
void Onattachedtowindow () {
  This.getwindow (). SetType (WindowManager.LayoutParams.TYPE_ Keyguard);
  Super.onattachedtowindow ();
}

The second way: may need to modify the source code, modify the system's source, so more trouble, do not recommend the use of the first way on the line

There are other alternative is the implementation of the way, is based on their own business, you can determine the click of the home key.

Because this article is written earlier, did not test 2.3 and after the version, writing wrong, here sorry. Then want to monitor the home key should only modify the source code. A deep friend of Android research can try. Find the place to block the home button, give me dms, thank you. I hope we can put this entangled in a lot of programmers to solve the problem, is to the programmer to reduce the tangle of work, we work together to solve it.

Part II:

The first part of the way one of the

Code is ported to 4.0.1 after This.getwindow (). SetType (WindowManager.LayoutParams.TYPE_KEYGUARD); This line of error,

Error tip: Java.lang.IllegalArgumentException:Window type can not being changed after the ' Window is added.

There are two ways to handle it.

Method One, modify Phonewindowmanager.java

if (keycode = = keyevent.keycode_home) {
 //Send a broadcast here
}

In the application to receive the broadcast after the corresponding processing, is generally done when the system will be to change the source code.

Method Two, detection log, according to log to determine whether there is a click on the home button

 private Boolean istesting = true; class Catchlogthread extends Thread {@Override Publ
  IC void Run () {Process mlogcatproc = null;
  BufferedReader reader = null;
  String Line; while (istesting) {try {//Get logcat log information Mlogcatproc = Runtime.getruntime (). EXEC (new string[] {"Logcat", "Act
    Ivitymanager:i *:s "});
    reader = new BufferedReader (New InputStreamReader (Mlogcatproc.getinputstream ())); while (line = Reader.readline ())!= null) {if (Line.indexof ("Android.intent.category.HOME") > 0) {istesti
      ng = false;
      Handler.sendmessage (Handler.obtainmessage ());
     Runtime.getruntime (). EXEC ("logcat-c");//delete log break;
   A catch (Exception e) {e.printstacktrace ());
}
  }
 }
};
  Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {log.i (TAG, "Home Key Press");
Do something here};

}; 

This way comes from this article "Android 4.0.x Home key event interception/monitoring"
How to get log: Android Development's method of obtaining Logcat log information in program

This way first to share here to everyone, after testing, and then modify the change in the time when it is convenient to use

More interested readers of Android-related content can view this site: Android Development Primer and Advanced tutorial, Android resource Operation tips Summary, Android View view tips Summary and Android control usage summary

I hope this article will help you with the Android program.

Related Article

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.