我是Android App Development的新手。我正在开发一个应用程序,其中我有一个接收器类。我厌倦了if声明。即使满足条件,其中的代码也不会执行。以下是我的代码:
MyReceiver.java
package eg.app7;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
public static boolean screenOff;
DevicePolicyManager dpm;
SharedPrefs sharedPrefs;
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"Changed",Toast.LENGTH_SHORT).show();
System.out.println("onReceive ");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
// The below if statement is my problem
if(sharedPrefs.getBoolValue(context,"hhmmkey")) {
Intent i = new Intent(context, TimePinService.class);
context.startService(i);
}
}
}
请指导我错在哪里
答案 0 :(得分:0)
您确定已将ACTION_SCREEN_OFF
和ACTION_SCREEN_ON
添加到IntentFilter吗?
public void registerMyReceiver() {
MyReceiver myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(myReceiver, intentFilter);
}
答案 1 :(得分:0)
感谢您提出的所有建议。但我找到了一个很好的解决办法我将if块放在服务类中,然后由接收器类启动该服务。效果很好!