我无法注册我的BroadcastReceiver。每当我尝试执行我的代码时,它会在logcat中显示“无法注册接收器”。
这是我在注册接收器的代码:
public class Preferences extends PreferenceActivity {
private Button button;
ListPreference lp;
private Context context;
private long duration;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
context = this;
lp = (ListPreference) findPreference("autoduration");
final Intent intent = new Intent(context, BackService.class);
lp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newSelection = newValue.toString();
int index = lp.findIndexOfValue(newSelection);
stopService(intent);
if (index == 0) {
duration = 15000;
} else if (index == 1) {
duration = 12000;
} else if (index == 2) {
duration = 10000;
} else if (index == 3) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver receiver = new ScreenReceiver();
registerReceiver(receiver, filter);
}
intent.putExtra("duration", duration);
startService(intent);
return true;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
这是我的接收者:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean screenOn = true;
private static final String TAG = "ScreenReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOn = true;
Log.e(TAG, "I am receiver");
} else {
screenOn = false;
}
}
}
答案 0 :(得分:2)
在取消注册之前,您的注册码可以被调用2次以上。你确定这不是问题吗?
答案 1 :(得分:0)