我想构建一个简单的静态方法,从当前手机获取下一个预定闹钟。非静态实现,在 Main_Activity
中一切正常,但现在作为静态方法在单独的类中出现错误:“android.content.Context.getContentResolver() ' 在空对象引用上”。
我想我对 Context
的理解还不够好。
我发现了这个:Static way to get 'Context' on Android?但我认为这不是正确的方法,我想我只是遗漏了一些东西,有人可以帮忙吗?
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
public class Controller extends AppCompatActivity {
private static Controller staticController = new Controller();
/**
* Finds out what the next user scheduled alarm is.
*
* @return (String) next time the user has scheduled an alarm on his device.
*/
protected static String nextAlarm() {
String nextAlarmTime = null;
// deprecated method will also detect non native alarm clocks!
nextAlarmTime = Settings.System.getString(staticController.getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
// fallback if deprecated method does not find valid alarm time!
// if (nextAlarmTime == null) {
// AlarmManager am = (AlarmManager) staticController.getSystemService(Context.ALARM_SERVICE);
// AlarmManager.AlarmClockInfo alarmInfo = am.getNextAlarmClock();
// Long alarm_next = alarmInfo.getTriggerTime();
// nextAlarmTime = (new Date(alarm_next)).toString();
// }
return nextAlarmTime;
}
// Do I need onCreate here ?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
(我不知道这是否重要,但 Atm Controller 类没有作为 Activity 包含在 list 文件中。我刚刚创建了一个新类并从 AppCompatActivity 扩展)
最佳答案
上面评论中提到的 CommonsWare 在这种情况下似乎是正确的,
Why are you not passing a Context (or ContentResolver) as a parameter to nextAlarm()?
我把它改成了:
import android.app.AlarmManager;
import android.content.Context;
import android.provider.Settings;
import java.util.Date;
public class Controller extends { **//does not need to be a Activity any more**
/**
* Finds out what the next user scheduled alarm is.
*
* @return (String) next time the user has scheduled an alarm on his device.
*/
protected static String nextAlarm(Context context) { //**pass Context from other Activity**
String nextAlarmTime = null;
// deprecated method will also detect non native alarm clocks!
nextAlarmTime = Settings.System.getString(context.getContentResolver(), //**reference parameter here**
Settings.System.NEXT_ALARM_FORMATTED);
// fallback if deprecated method does not find valid alarm time!
if (nextAlarmTime == null) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // **reference parameter again**
AlarmManager.AlarmClockInfo alarmInfo = am.getNextAlarmClock();
Long alarm_next = alarmInfo.getTriggerTime();
nextAlarmTime = (new Date(alarm_next)).toString();
}
return nextAlarmTime;
}
}
然后在一些 Activity 中通过 Controller.nextAlarm(this))
简单地调用它。
关于java - 了解 Android 上下文 : (null object reference),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36888528/