我想创建可以从广泛的接收器类(重复警报)访问的全局变量。要创建全局变量,我使用了这个类:
public class GVar extends Application {
private Integer Hour;
private Integer Minute;
public void setHour(Integer hour) {
Hour = hour;
}
public void setMinute(Integer minute) {
Minute = minute;
}
public Integer getHour() {
return Hour;
}
public Integer getMinute() {
return Minute;
}
}
然后我的闹钟看起来像这样:
public class Alarm extends BroadcastReceiver {
private static Integer counter=0;
@Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
//start activity
Integer H=((GVar) this.getApplication()).getHour();
Intent intentone = new Intent(context.getApplicationContext(), UssdCallActivity.class);
intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentone);
//startActivity()
//Toast.makeText(context, "Alarm! ("+counter.toString()+")", Toast.LENGTH_SHORT).show(); // For example
counter++;
wl.release();
}
getApplication()方法无法解决。 从MainActivity类调用时,同样的方法也有效。