java - 从 Broadcastreceiver 调用服务未按预期工作

标签 java android alarmmanager

我希望我的服务在警报管理器指定的时间运行。但在我的情况下,它在我指定的时间运行,如果我在指定的服务运行时间后打开应用程序。我希望它只在指定的时间运行,并且应该每天重复。我不知道我写的代码有什么问题。感谢您的帮助。

这是我的服务类:

public class AutoLogout extends Service {

private SQLiteHandler db;
private SessionManager session;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // SqLite database handler
    db = new SQLiteHandler(getApplicationContext());
    // session manager
    session = new SessionManager(getApplicationContext());
    logoutUser();
   Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_SHORT).show();
    return Service.START_STICKY;
}

/**
 * Logging out the user. Will set isLoggedIn flag to false in shared
 * preferences Clears the user data from sqlite users table
 */
private void logoutUser() {
    session.setLogin(false);
    db.deleteData();
    // Launching the login activity
    Intent intent = new Intent(this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    stopService(new Intent(getApplicationContext(),AutoLogout.class));
    Toast.makeText(getApplicationContext(),"Service stopped",Toast.LENGTH_SHORT).show();
}
}

这是我的 BroadcastReciever 类:

public class AlarmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "MyReceiver Started", Toast.LENGTH_SHORT).show();
        Intent intent1 = new Intent(context,AutoLogout.class);
        context.startService(intent1);
    }
}

CategoryActivity.java 我在 oncreate 方法中调用报警管理器:

public class CategoryActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category);
    Calendar cal_alarm = Calendar.getInstance();
            cal_alarm.set(Calendar.HOUR_OF_DAY,14);
            cal_alarm.set(Calendar.MINUTE,46);
            cal_alarm.set(Calendar.SECOND,00);
            Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis() , pendingIntent);

}
}

这是在我的 list 文件中:

    <service android:name=".services.AutoLogout" />
    <receiver android:name=".services.AlarmBroadcastReceiver"/>

最佳答案

问题的发生是因为每次打开设置闹钟的 Activity 时,它都会重新初始化闹钟 - 但是,每次打开 Activity 时闹钟都会错误地立即触发,因为正确的闹钟时间(14: 46:00) 可能在当天已经过去,当您为已经过去的时间设置 AlarmManager 警报时,它会立即触发。

为了解决这个问题,我们需要检查当天的闹钟时间是否已经过去,如果已经过去,则将闹钟设置为 日的 14:46:00 :

if (cal_alarm.getTimeInMillis() < System.currentTimeMillis()) {
        cal_alarm.add(Calendar.DATE, 1);
}

这是它在您的 CategoryActivity 中的样子:

public class CategoryActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        Calendar cal_alarm = Calendar.getInstance();
        cal_alarm.setTimeInMillis(System.currentTimeMillis()); // i added this to ensure the calendar is being configured correctly
        cal_alarm.set(Calendar.HOUR_OF_DAY,14);
        cal_alarm.set(Calendar.MINUTE,46);
        cal_alarm.set(Calendar.SECOND,00);

        //check if time has already passed today, adjust alarm to tomorrow if it has
        if (cal_alarm.getTimeInMillis() < System.currentTimeMillis()) {
            cal_alarm.add(Calendar.DATE, 1);
        }

        Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis() , pendingIntent);
    }
}

if 语句只是检查当前时间是否大于 cal_alarm 设置的时间,如果是,则设置 14:46 的闹钟: 00 明天。如果您需要更多说明,请随时提出!

关于java - 从 Broadcastreceiver 调用服务未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42853309/

相关文章:

java - Android:获取我无法捕获的 IllegalStateException

java - JNI char [](char 数组)的方法描述符是什么?

android - 使用警报管理器在主线程外每隔 X 分钟启动一次服务?

android - AlarmManager 不启动 BroadcastReceiver

java - 删除文件中的重复数据

java - 在 Android 中切换 View 时出现 StackOverflowError(在 Sprint HTC 上测试)

android - 调用需要 API 级别 23(当前最小值为 14) : android. app.Activity#requestPermissions,checkSelfPermission

android - Android Oreo 中的通知

java - 在 Gradle 插件中获取项目源目录

java - 在两个线程和主程序之间共享一个对象