无法将方法与MainActivity类分开

时间:2019-05-13 13:12:02

标签: java android alarmmanager android-context android-alarms

在试图实现AlarmManager类方法的地方创建了新的Java类。我想创建用于创建,编辑和删除警报的功能。所有代码都在MainActivity类中时,一切工作正常。

新类具有传递上下文的构造函数。应用程序成功构建后,警报不起作用。

我在MainActivity上调用setShowDataEvent方法:

AlarmController alarmController = new AlarmController(this);
alarmController.setShowDataEvent(startTime, finishTime);

这是AlarmController类:

private final String TAG = "AlarmController";

Context context;
PendingIntent pendingIntent;
AlarmManager mAlarmManager;


public AlarmController(Context context){
    this.context = context;
    this.mAlarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
}

public void setShowDataEvent(long startTime, long finishTime){


    newAlarmIntentData(startTime);
    mAlarmManager.setExact(AlarmManager.RTC, startTime, pendingIntent);

    newAlarmIntentData(finishTime);
    mAlarmManager.setExact(AlarmManager.RTC, finishTime, pendingIntent);
    Log.d(TAG, "setShowDataEvent has been executed");
}

private void newAlarmIntentData(long time){
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra("showData", true);
    intent.putExtra("time", time);

    pendingIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_ONE_SHOT);
}

1 个答案:

答案 0 :(得分:0)

AlarmManager移至构造函数并重新启动AndroidStudio后,所有命令均开始工作。我已经向意图添加了相同的数据,所以现在有两个不同的PendingIntent

intent.setData(Uri.parse("myalarms://" + time));