问题
I am trying to play some tone when my application is in background and I press on "Camera" button for that I am doing this simple steps.
Creating
BroadcastReceiver
classpublic class CameraButtonListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ToneGenerator tone = new ToneGenerator(AudioManager.STREAM_DTMF, 100); tone.startTone(0,2000); abortBroadcast(); } }
Register
BrodcastReceiver
inonCreate
methode.@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MediaButtonBrodcastReceiver receiver = new MediaButtonBrodcastReceiver(); IntentFilter filter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON); filter.setPriority(25645895); registerReceiver(receiver,filter); }
Adding brodcast receiver to android manifest.
<receiver android:enabled="true" android:exported="true" android:name=".CameraButtonListener"> <intent-filter android:priority="25645895"> <action android:name="android.intent.action.CAMERA_BUTTON" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
After I launch my application, then press menu button and application goes to the background, after I press on Camera Button and nothing heppens, only camera application is opened. Maybe I am doing something wrong or I have missed something ?
I use Sony Ericsson XPeria Arc phone with Android 2.3.4 OS version.
回答1:
Get rid of the <category>
element in your <receiver>
element, if you are using step #3. That broadcast probably does not have a category -- you usually only see categories on Intent
objects used for startActivity()
.
Note that your step #2 does not specify a category with its IntentFilter
, which is fine.
回答2:
Here, read up on Android Services. Services are used if you want your application to keep performing tasks while in the background. In this case, you want to know when something happens even if your application is not currently in the foreground. This is how to do it.
来源:https://stackoverflow.com/questions/13238645/broadcastreceiver-dont-receive-keypress-on-camera-button