BroadcastReceiver don't receive keypress on Camera button

ⅰ亾dé卋堺 提交于 2019-12-12 10:20:19

问题


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.

  1. Creating BroadcastReceiver class

    public 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();
        }
    }
    
  2. Register BrodcastReceiver in onCreate 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);      
    }
    
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!