Override hardware buttons on Android
Is it possible to programmatically override the functions of the hardware buttons on the robot? Specifically, I want to be able to programmatically override the camera buttons on the phone. Is this possible?
resolvent:
How to handle camera button events
Once the camera button is pressed, a broadcast message will be sent to all applications listening to it. You need to use the broadcast receiver and abortbroadcast() function
1) Create a class that extends broadcastreceiver and implements onReceive method
As soon as the broadcast message is received, the code in the onReceive method will run. In this case, I wrote a program to start an activity called myapp
Just click the hardware camera button and the system will launch the default camera application. This may cause conflicts and prevent your activities. For example, if you want to create your own camera application, it may not start because the default camera application will use all resources. In addition, there may be other applications listening to the same broadcast. To prevent this function from being called “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 line is added to the manifest file to inform the system that your program is ready to receive broadcast messages
Add this row to receive inferences when the hardware button is clicked
<action android:name="android.intent.action.CAMERA_BUTTON" />
HDC is the class created in step 1 (don't forget ".")
<receiver android:name=".HDC" >
Call the "abortbroadcast()" function to prevent other applications from responding to the broadcast. What if your application is the last one to receive messages? To prevent this, you must set some priorities to ensure that your application receives it before any other program. To set the priority, add this line. The current priority is 10000, which is very high, and you can change it according to your requirements
<intent-filter android:priority="10000">