【发布时间】:2013-02-12 15:59:11
【问题描述】:
我在按下时设法通过我的应用程序获取了我的headset buttons get recognized,但其中一个按钮需要调用 MyCustomActivity 中的方法。问题是 onReceive 的第一个参数是一个 Context,它不能强制转换为 Activity 并使用 MyCustomActivity 的 inner class won't work in Android 4.1,除非它是静态的(同样的问题是无法访问 MyCustomActivity 的方法。 p>
所以留给我的唯一选择(为了同时支持 2.x 和 4.1)是将活动作为参数传递给 RemoteControlReceiver。
但是当实例化它的唯一方法是通过时,我该怎么做:
private ComponentName mRemoteControlReceiver = new ComponentName(this, RemoteControlReceiver.class);
哪个不接受任何附加参数?
知道如何解决这个限制吗?
注意:如果我尝试将 RemoteControlReceiver 定义为具有带参数的构造函数,则会收到以下异常:
E/AndroidRuntime(2836): java.lang.RuntimeException: Unable to instantiate receiver com.example.RemoteControlReceiver: java.lang.InstantiationException: can't instantiate class com.example.RemoteControlReceiver; no empty constructor
Caused by:
E/AndroidRuntime(2836): Caused by: java.lang.InstantiationException: can't instantiate class com.example.RemoteControlReceiver; no empty constructor
E/AndroidRuntime(2836): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(2836): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime(2836): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2205)
因此很明显,这个新的 registerMediaButtonEventReceiver 要求(在 Android 4.1 中引入)需要一个空构造函数。
有没有办法解决这个问题?
例如,有没有办法获得对实际 RemoteControlReceiver 对象的引用(通过mAudioManager.registerMediaButtonEventReceiver() 间接实例化)?这样我就可以在实例化之后使用访问器设置 RemoteControlReceiver 的数据成员?
【问题讨论】:
-
可以在Activity的onResume/onCreate中创建并注册BroadcastReceier,在onPause/onStop中取消注册。通过这种方式,当前活动可以照顾其生命周期,并且接收者应该能够与其容器(活动)进行通信。
-
@SudarNimalan 我已经尝试过了。这个only works in Android 2.x。它在 4.1 中不起作用。我需要能够以某种方式让
RemoteControlReceiver(不是BroadcastReceiver!)知道MyCustomActivity。谢谢。 -
这是一个艰难的问题,但这里有一个想法:你能检查通过 Intent onReceive 传递的Extra 吗?或者使用这个GlobalVariable trick?
-
看到这个答案可能对你有帮助。 stackoverflow.com/questions/15059886/…
标签: java android broadcastreceiver android-audiomanager