0

我有一个在设备启动时运行的接收器和服务,但是假设用户从不关闭他的设备,我应该如何处理?

如何从我的接收器/服务中使用警报管理器安排状态栏通知?

package it.bloomp.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class EventsNotificationService extends Service {

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

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service created.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service destroyed.");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onCreate();
        System.out.println("Service started.");
    }
}

...

package it.bloomp.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class EventsNotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, EventsNotificationService.class);
            context.startService(serviceIntent);
        }
    }
}
4

1 回答 1

0

您可以使用适合您要求的其他类型的广播接收器。或者您可以使用 Timer 类设置一个时间段来定期运行您的任务,如下所示;

Timer time;
time..scheduleAtFixedRate(new TimerTask() {            
        @Override
        public void run() {
           //Your task         
        }
    }, 0/*Start delay*/, 1000/*Delay period*/);

更新: 要安排通知,您可以执行以下操作:

Intent intentSafety_Check_Service = new Intent(Activity_Add_Safety_Check.this, Safety_Check_Service.class);

    pendingIntent = PendingIntent.getService(Activity_Add_Safety_Check.this,                Integer.parseInt(currCheckID), intentSafety_Check_Service, 0);

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();

    calendar.setTimeInMillis(/*Your alarm date converted in milliseconds*/);

    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
于 2012-06-05T06:06:21.773 回答