请我还在学习java / android app开发,我的代码中有这些错误。请帮忙。
我的代码看起来像这样
package com.creditswitch;
import android.app.Activity;
import android.content.BroadcastReceiver;
import java.io.PrintStream;
import android.content.IntentFilter;
public class MainActivity extends Activity {
BroadcastReceiver mReceiver;
protected void onResume() {
MyApplication.activitycontext = this;
System.out.println("On Resume of base activity");
if(mReceiver == null) {
mReceiver = new ConnectionChangeReceiver();
registerReceiver(mReceiver, localString1); //THIS LINE IS GIVING ERROR: localString1 cannot be resolved to a variable
System.out.println("Register Receiver");
}
super.onResume();
}
protected void onPause() {
System.out.println("On Pause of base activity");
if(mReceiver != null) {
unregisterReceiver(mReceiver);
System.out.println("Unregister Receiver");
mReceiver = 0x0; // THIS LINE IS GIVING ERROR: Type mismatch: cannot convert from int to BroadcastReceiver
}
super.onPause();
}
}
答案 0 :(得分:2)
首先应该声明localString1类型为intentFilter,因为registerReceiver方法接受两个参数: 1 BraodcastReceiver 2 IntentFilter实例 您可以创建一个intent过滤器,如下所示:
static final String MY_ACTION = "com.my.defined.MY_ACTION";
IntentFilter intentFilter = new IntentFilter(MY_ACTION);
您必须在androidmanifest.xml的标记中提供相同的操作,这可以如此处所示完成。
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.my.defined.MY_ACTION" />
</intent-filter>
</receiver>
第二件事是你没有正确初始化mReceiver对象。它的类型为broadcastReceiver,你不能用整数值实例化它
要初始化它,你必须执行以下操作(或在类型BroadcastReceiver上创建一个匿名内部类):
创建一个扩展BroadcastReceiver并覆盖其onreceive方法的类
公共类MyBroadcast扩展了BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// your code here
}
现在创建此类的对象,而不是在
的broadcastReceiver上 MyBroadcast mReceiver = new MyBroadcast();
更喜欢在你活动的oncreate方法中这样做。
现在您可以调用注册接收方法,如下所示:
registerReceiver(mReceiver,intentFilter);
答案 1 :(得分:1)
错误1
localString1 needs to be defined and initialized
错误2
0x0 is a hexadecimal value, thus cant be a assigned to a variable of type BroadcastReceiver
答案 2 :(得分:0)
您应该替换此代码:
registerReceiver(mReceiver, localString1);
用这个:
static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter filter = new IntentFilter(SOME_ACTION);
registerReceiver(mReceiver, filter);
至于第二个错误你想做什么? 如果你想将mReceiver设置为null,只需给出:
mReceiver = null;