每天安排警报(无需重新启动正在运行的应用程序)

时间:2015-07-30 07:13:34

标签: android scheduled-tasks alarmmanager background-process

我的闹钟有问题,我不想每天都显示通知,所以我尝试了这些代码:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 00);
Intent downloader = new Intent(getApplicationContext(), NotificationDemandeReceiver.class);
final PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0,
        downloader, 0);
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);

    Intent myIntent = new Intent(this , NotificationDemandeService.class);
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 19);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 00);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);
  • 这两个代码的问题是:如果我安排到19:00,如果此时应用程序没有运行,通知将会显示。

  • 如果应用程序在预定时间运行,则会显示通知,但如果我关闭应用程序并再次运行,则会再次显示通知!

所以我这样做了:

// Construct an intent that will execute the AlarmReceiver
Intent nintent = new Intent(getApplicationContext(), NotificationDemandeReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent npIntent = PendingIntent.getBroadcast(this, NotificationDemandeReceiver.REQUEST_CODE,
        nintent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long nfirstMillis = System.currentTimeMillis(); // first run of alarm is immediate
int nintervalMillis = 1000 * 60 * 60 * 24; // 10 minutes
AlarmManager nalarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
nalarm.setRepeating(AlarmManager.RTC_WAKEUP, nfirstMillis, nintervalMillis, npIntent);
  • 此处,当我启动应用程序时运行警报,但如果应用程序在预定时间运行,则会显示通知,但如果我关闭应用程序并再次运行,则会再次显示通知!

Alarme属于一个函数public void scheduleAlarm(){}我在Splashscreen上调用它:

Thread logoTimer = new Thread() {
    public void run() {
        try {
            int logoTimer = 0;
            while (logoTimer < 10000) {
                sleep(100);
                logoTimer = logoTimer + 1000;
            };

            List<Demande> demandesRenvoie = db.getAllDemandesRenvoie();
            if (!(demandesRenvoie.isEmpty())) {
                scheduleAlarm();
            }
            startActivity(new Intent("android.intent.action.ACCUEIL"));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            finish();
        }
    }
};

那么如何每天安排一个警报,并且没有&#34;重启&#34;关闭运行应用程序后?

更新(使用API​​ 14)

Splashscreen(我开始2个服务,一个用于ksoapservice(每10分钟一次),另一个用于通知(每天)):

public class Splashscreen extends Activity {

    DatabaseHandler db = new DatabaseHandler(this);

    //Initialisation de l activite avec les donnees necessaires
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);

        Thread logoTimer = new Thread() {
            public void run() {
                try {
                    int logoTimer = 0;
                    while (logoTimer < 10000) {
                        sleep(100);
                        logoTimer = logoTimer + 1000;
                    };

                    List<Demande> demandesRenvoie = db.getAllDemandesRenvoie();
                    if (!(demandesRenvoie.isEmpty())) {
                        scheduleAlarm();
                    }
                    startActivity(new Intent("android.intent.action.ACCUEIL"));
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    finish();
                }
            }
        };

        logoTimer.start();
    }

    public void scheduleAlarm() {
        // Construct an intent that will execute the AlarmReceiver
        Intent intent = new Intent(getApplicationContext(), EnvoieReceiver.class);
        // Create a PendingIntent to be triggered when the alarm goes off
        final PendingIntent pIntent = PendingIntent.getBroadcast(this, EnvoieReceiver.REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Setup periodic alarm every 5 seconds
        long firstMillis = System.currentTimeMillis(); // first run of alarm is immediate
        int intervalMillis = 1000 * 60 * 10; // 10 minutes
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, intervalMillis, pIntent);

        // Construct an intent that will execute the AlarmReceiver
        Intent nintent = new Intent(getApplicationContext(), NotificationDemandeReceiver.class);
        // Create a PendingIntent to be triggered when the alarm goes off
        final PendingIntent npIntent = PendingIntent.getBroadcast(this, NotificationDemandeReceiver.REQUEST_CODE,
                nintent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Setup periodic alarm every 5 seconds
        long nfirstMillis = System.currentTimeMillis(); // first run of alarm is immediate
        int nintervalMillis = 1000 * 60 * 60 * 24; // 10 minutes
        AlarmManager nalarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        nalarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, nfirstMillis, nintervalMillis, npIntent);


        /*

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 13);
        calendar.set(Calendar.MINUTE, 00);
        Intent downloader = new Intent(getApplicationContext(), NotificationDemandeReceiver.class);
        final PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0,
                downloader, 0);
        AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);

        */

        /*
            Intent myIntent = new Intent(this , NotificationDemandeService.class);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 15);
            calendar.set(Calendar.MINUTE, 19);
            calendar.set(Calendar.SECOND, 00);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);
        */
    }

接收器:

public class NotificationDemandeReceiver extends BroadcastReceiver {
    public static final int REQUEST_CODE = 12345;
    public static final String ACTION = "fr.solutis.solutis.alarm";

    // Triggered by the Alarm periodically (starts the service to run task)
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, NotificationDemandeService.class);
        i.putExtra("foo", "bar");
        context.startService(i);
    }
}

服务:

public class NotificationDemandeService extends IntentService {


    DatabaseHandler db = new DatabaseHandler(this);

    public NotificationDemandeService() {
        super("EnvoieService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {


        List<Demande> demandes = db.getAllDemandesRenvoie();

        if (!(demandes.isEmpty())) {

            String message = "Votre demande n'a pas été envoyée, merci de vous connecter à internet.";
            int icon = R.drawable.notification_icon;

            int mNotificationId = 001;

            PendingIntent resultPendingIntent =
                    PendingIntent.getActivity(
                            this,
                            0,
                            intent,
                            PendingIntent.FLAG_CANCEL_CURRENT
                    );

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
            Notification notification = mBuilder.setSmallIcon(icon).setTicker("Solutis").setWhen(0)
                    .setAutoCancel(true)
                    .setContentTitle("Solutis")
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                    .setContentIntent(resultPendingIntent)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher_solutis))
                    .setContentText(message).build();

            NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(mNotificationId, notification);
        }
    }
}

Android Manifest:

...

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <!-- Optional permission for reliable local dispatching on non-Google Play devices -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
...
      <receiver android:name=".EnvoieReceiver" android:process=":remote" >
        </receiver>

        <receiver android:name=".NotificationDemandeReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service android:name=".EnvoieService" android:exported="false" />
        <service android:name=".NotificationDemandeService" android:exported="false" />

1 个答案:

答案 0 :(得分:-1)

您是否将此intent-filter添加到接收器?

<receiver android:name=".your.Receiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

还需要许可

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />