即使应用程序被系统

时间:2017-07-31 05:31:18

标签: java android broadcastreceiver alarmmanager

我有应用程序,其主要功能取决于警报但有时不会发出警报,我说它是因为系统在警报触发之前杀死你的应用程序,我怎么能确保警报即使在应用程序被杀后也应该触发,这是我和#39; m设置闹钟

 public static void setEndAlarm(){
    AlarmManager alarmManager = (AlarmManager)  MyApplication.getContext().getSystemService(Context.ALARM_SERVICE);
    Calendar time = Calendar.getInstance();
    time.setTimeInMillis(System.currentTimeMillis());
    time.set(Calendar.HOUR_OF_DAY, SharedPrefUtils.getEndHour(MyApplication.getContext()));
    time.set(Calendar.MINUTE, SharedPrefUtils.getEndMin(MyApplication.getContext()));
    time.set(Calendar.SECOND, 0);
    alarmManager.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), endPendingIntent(MyApplication.getContext()));
}

private static PendingIntent endPendingIntent(Context context){
    Intent intent = new Intent(context, ClsEndBroadcastReciever.class);

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

和获得这样的上下文:

public class MyApplication extends Application {

private static Context mContext;

@Override
public void onCreate() {
    super.onCreate();
    mContext = getApplicationContext();
}

public static Context getContext() {
    return mContext;
}
}

广播接收器:

public class ClsEndBroadcastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    FirebaseJobDispatcher dispatcher = new 
 FirebaseJobDispatcher(new GooglePlayDriver(context));

    dispatcher.cancel("notification");
    Toast.makeText(context, "End Time", Toast.LENGTH_SHORT).show();
}
}

2 个答案:

答案 0 :(得分:0)

如果没有系统权限,我认为你不能可靠地做到这一点。

尝试使用IntentService和START_STICKY(https://developer.android.com/reference/android/app/Service.html)来确保应用程序不会被杀死。

答案 1 :(得分:0)

如果您在BroadcastReceiver中指定了Manifest,那么即使您的应用尚未处于有效状态,它也会被调用。

<强>清单

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!-- Activities and Services -->

    <receiver android:name=".AlarmBroadcastReceiver"/>

</application>

<强> AlarmBroadcastReceiver

public class AlarmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // do what you want to do here.
        // if the work load is heavy then launch service for it here

    }
}