我想每隔X分钟运行一些任务。我正在使用AlarmManager
,当应用正在运行或在后台运行时它可以正常工作。但是,在我从正在运行的应用列表中删除应用后,它就会停止工作。
闹钟设置:
Intent intent = new Intent(context , SoundNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0 , intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE , 15);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() , pendingIntent);
}
else {
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() , pendingIntent);
}
System.out.println("Alarm is set : " + c.getTime());
manifest.xml:
<receiver android:name="info_tech.com.fazeker.SoundNotificationReceiver"
android:exported="true"
android:enabled="true">
</receiver>
答案 0 :(得分:0)
use service like :
public class TestJobService extends JobService {
private static final String TAG = "SyncService";
@Override
public boolean onStartJob(JobParameters params) {
// We don't do any real 'work' in this sample app. All we'll
// do is track which jobs have landed on our service, and
// update the UI accordingly.
Log.i(TAG, "on start job: " + params.getJobId());
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "on stop job: " + params.getJobId());
return true;
}
MainActivity mActivity;
private final LinkedList<JobParameters> jobParamsMap = new LinkedList<JobParameters>();
public void setUiCallback(MainActivity activity) {
mActivity = activity;
}
}
答案 1 :(得分:0)
我知道已经晚了,但是我解决了在onDestroy中调用警报的相同问题:
BaseActivity中的OnDestroy:
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG,getClasName()+ ".onDestroy Calleding: ");
AlarmManager_Custom alarm = new AlarmManager_Custom(new Intent(this,BC_Custom.class),this);
}
我在Kotlin的AlarmManager:
class AlarmManager_Custom(val intent: Intent, val context: Context) {
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
val alarm = context.getSystemService(ALARM_SERVICE) as AlarmManager
private var calendar = Calendar.getInstance()
fun setTimeCalendar() {
calendar.timeInMillis = System.currentTimeMillis()
calendar.add(Calendar.MINUTE, 1)
if (Build.VERSION.SDK_INT < 23) {
if (Build.VERSION.SDK_INT >= 19) {
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
} else {
alarm.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
}
} else {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
}
}
}
我的BroadCastReceiver:
public class BC_Custom extends BroadcastReceiver {
@SuppressLint("UnsafeProtectedBroadcastReceiver")
@Override
public void onReceive(Context context, Intent intent) {
Log.i("TAG_RECEIVER", "broad cast called");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, UpdateDados.class));
} else {
context.startService(new Intent(context,UpdateDados.class));
}
}
}