Overriding the hardware buttons on Android
Is it possible to override the function of a hardware button programmically on a droid? Specifically, I'd like to be able to o开发者_运维问答verride the camera button on my phone programmically. Is this possible?
How to Handle Camera Button Events
As soon as camera button is pressed a broadcast message is sent to all the applications listening to it. You need to make use of Broadcast receivers and abortBroadcast() function.
1) Create a class that extends BroadcastReceiver and implement onReceive method.
The code inside onReceive method will run whenever a broadcast message is received. In this case I have written a program to start an activity called myApp.
Whenever hardware camera button is clicked the default camera application is launched by the system. This may create a conflict and block your activity. E.g If you are creating your own camera application it may fail to launch because default camera application will be using all the resources. Moreover there might be other applications which are listening to the same broadcast. To prevent this call the function "abortBroadcast()", this will tell other programs that you are responding to this broadcast.
public class HDC extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Prevent other apps from launching
abortBroadcast();
// Your Program
Intent startActivity = new Intent();
startActivity.setClass(context, myApp.class);
startActivity.setAction(myApp.class.getName());
startActivity.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(startActivity);
}
}
}
2) Add below lines to your android manifest file.
<receiver android:name=".HDC" >
<intent-filter android:priority="10000">
<action android:name="android.intent.action.CAMERA_BUTTON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
The above lines are added to your manifest file to tell the system that your program is ready to receive broadcast messages.
This line is added to receive an intimation when hardware button is clicked.
<action android:name="android.intent.action.CAMERA_BUTTON" />
HDC is the class created in step 1(do not forget the ".")
<receiver android:name=".HDC" >
The "abortBroadcast()" function is called to prevent other applications from responding to the broadcast. What if your application is the last one to receive the message? To prevent this some priority has to be set to make sure that your app receives it prior to any other program. To set priority add this line. Current priority is 10000 which is very high, you can change it according to your requirements.
<intent-filter android:priority="10000">
精彩评论