2012-12-15 66 views
0

我有一个在Android设备启动后运行的服务。这每天执行两个通知。但我有一个问题:它看起来像服务崩溃或自动重新启动。此外,通知不会在指定的时间执行。我怎样才能解决这个问题?有时我会看到敬酒Service CreatedService 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); 
    } 
}; 

回答

1

如果您的通知需要在特定时间运行,您应该使用AlarmManager安排他们。这会被Android保留下来,以便您的服务可以自由被杀死,并且必要时警报将会重新启动。

这听起来像你现在让你的服务24/7全天候运行,以便它可以每天做两件事;这是一个糟糕的Android公民!改为使用AlarmManager将解决您的问题,并且可以让您停止浪费资源。

+0

mhmh..my服务在我的应用外运行。当用户重新启动自己的设备时,无法打开应用程序。如果用户没有打开应用程序如何运行通知?我需要一项服务。或者弄错了什么?谢谢。 –

+0

如果您的服务正在启动(通过BOOT_COMPLETED或其他方式),该服务可以安装AlarmManager。 – mah

+0

我的服务以BOOT_COMPLETED开头。如何通过服务“安装”警报管理器?我的代码不一样吗?谢谢。 –

相关问题