我在Android设备启动后运行的服务。这每天执行两个通知。但我有一个问题:看起来服务崩溃或自动重启。此外,通知也不会在指定时间执行。我怎样才能解决这个问题?有时我会看到吐司Service Created
和Service Started
。谢谢!
代码:
public class UnUsedService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private PendingIntent pendingIntent;
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 05); //midday
cal1.set(Calendar.MINUTE, 45);
cal1.set(Calendar.SECOND, 00);
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, 17);//8pm for example
cal2.set(Calendar.MINUTE, 30);
cal2.set(Calendar.SECOND, 00);
AlarmManager am = (AlarmManager)getApplicationContext().getSystemService (Context.ALARM_SERVICE);
Intent intent2 = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),cal2.getTimeInMillis(), pi);
}
};
答案 0 :(得分:1)
如果您的通知需要在特定时间运行,则应使用AlarmManager来安排它们。这将由Android保留,以便您的服务可以自由地被杀死,警报将在必要时重新启动它。
听起来你现在正在让你的服务全天候运行,以便它可以每天做两次事情;这是一个糟糕的Android公民!使用AlarmManager
代替将解决您的问题并让您停止浪费资源。