如何防止在Android中重新启动服务?

时间:2014-10-08 13:40:10

标签: android android-service

我有一项服务,可以在特定时间显示通知,并有一个broadcastreceiver来启动此服务。当应用程序启动时,服务启动并显示通知并显示设备上运行的应用程序中的服务,但有时在正在运行的应用程序服务中是重新启动并且消息不会显示。

我的服务代码是:

public class NotificationService extends Service {
private boolean flag=false;
public static NotificationCompat.Builder mBuilder;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Timer timer=new Timer();
    final Context context=getApplicationContext();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if(CheckTime()){
                //Intent intent = new Intent(context, NotificationReciver.class);
                //sendBroadcast(intent);
                showNotification();
            }
        }
    },0,(1000*60));

    return START_NOT_STICKY;
}

private boolean CheckTime(){
    final Context context=getBaseContext();
    Calendar calendar=Calendar.getInstance();
    int hour=calendar.get(Calendar.HOUR_OF_DAY);
    int minute=calendar.get(Calendar.MINUTE);

    if(hour==16 && minute==11){
        return true;
    }else {
        return false;
    }
}

private void showNotification() {
    Context context=getApplicationContext();
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Intent intent=new Intent(context, QuestionActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent,0);

    mBuilder = new NotificationCompat.Builder(context).
            setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Feelinger")
            .setContentText("How are you feeling today?")
            .setSound(alarmSound)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setVibrate(new long[]{300, 200, 200, 200});

    android.app.NotificationManager mNotificationManager = (android.app.NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(100, mBuilder.build());
}

和BroadcastReceiver代码是:

public class NotificationManager extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context,NotificationService.class));
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

写内部服务

@Override
public int onStartCommand (Intent intent, int flags, int startId)
{
    return START_NOT_STICKY;
}