因此,我制作了一个应用程序,单击按钮后,即可使用“警报管理器”设置重复任务。
在创建时:
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
servicePendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
在按钮上单击:
alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
firingCal= Calendar.getInstance();
firingCal.setTimeInMillis(System.currentTimeMillis());
firingCal.set(Calendar.HOUR_OF_DAY, 1); // At the hour you want to fire the alarm
firingCal.set(Calendar.MINUTE, 47); // alarm minute
firingCal.set(Calendar.SECOND, 0); // and alarm second
long intendedTime = firingCal.getTimeInMillis();
long interval = 1000 * 60 * 1;
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, intendedTime, interval, servicePendingIntent);
在AlarmReceiver类中:
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, WallpaperService.class);
context.startService(myIntent);
Log.d(TAG,"Am apelat serviciul");
context.stopService(myIntent);
}
在WallpaperService类中,我只是发出一个get请求并设置一个墙纸。
public class WallpaperService extends Service {
String requestLink="";
boolean requestFinished = false;
public final String TAG = "Service";
public static int SERVICE_ID = 1;
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"Wallpaper Service started");
Toast.makeText(WallpaperService.this,"Service started",Toast.LENGTH_LONG);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"In onStartCommand");
taskToBeRepeated();
stopSelf();
return START_STICKY;
}
.....
}
其行为是,当我启动该应用程序并单击该按钮时,警报管理器在第一次启动时一切正常(在后台运行该应用程序)。第二次接收器触发时,我在磁贴中收到错误。更具体地说:
java.lang.RuntimeException:无法启动接收器com.example.dailywallpaper.AlarmReceiver:java.lang.IllegalStateException:不允许启动服务意图{cmp = com.example.dailywallpaper / .WallpaperService}:应用程序在后台uid UidRecord {3e313bf u0a357 RCVR bg:+ 1m21s273ms空闲更改:未处理的过程:1 seq(0,0,0)}
似乎是什么问题?为何先工作然后又给出错误?我该如何解决?
答案 0 :(得分:0)
您需要阅读android官方文档,了解有关在android 8及更高版本中使用后台服务或警报的政策,并使您的应用适应此限制。
我建议您仔细阅读这两篇文章:
https://developer.android.com/guide/components/services
https://developer.android.com/about/versions/oreo/background