接收方,服务,报警管理器和状态栏通知

时间:2012-06-05 00:21:17

标签: android notifications broadcastreceiver android-service alarmmanager

我有一个接收器和服务在设备启动时运行,但是让我们说用户永远不会关闭他的设备,我应该怎么处理?

如何使用来自我的接收器/服务的alarmmanager安排状态栏通知?

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);
        }
    }
}

1 个答案:

答案 0 :(得分: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);