簡體   English   中英

AlarmManager中有多個警報

[英]More than one alarms in alarmManager

這是一個短信計時器應用程序,因此我需要使用警報管理器設置多個警報,以便我可以向許多人發送消息。 我的代碼是:

Phone = phone.getText().toString();
        Message = message.getText().toString();
        phone.setText("");
        message.setText("");
        //Validating if any field empty
        if (Phone.length() >= 10 && Message.length() > 0) {
            Toast.makeText(this.getApplicationContext(), "Your sms will be sent soon", Toast.LENGTH_SHORT).show();
            //Getting Calender Reference
            Calendar cal = Calendar.getInstance();
            int currentApiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentApiVersion > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                cal.set(Calendar.MINUTE, time_picker.getMinute());
                cal.set(Calendar.HOUR_OF_DAY, time_picker.getHour());
            } else {
                //Setting the date and time from the time picker
                cal.set(Calendar.MINUTE, time_picker.getCurrentMinute());
                cal.set(Calendar.HOUR_OF_DAY, time_picker.getCurrentHour());
            }

            int a = (Calendar.getInstance().get(Calendar.SECOND) * 1000);

            myIntent = new Intent(this, MyReceiver.class);
            //Pending Intent for sending the intent afterwards
            pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent, 0);
            alarmManager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
            alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis() - a, pendingIntent);

所有代碼都包含在onclick函數中,因此,當用戶填充數據並單擊發送時,應設置一個警報。 我最多只需要5個警報。 我嘗試創建AlarmManager[]ArrayList<PendingIntent>但沒有成功,僅設置了最新的警報。

PendingIntent通常由它們的requestCode(像ID一樣起作用)來區分,這可能是導致您出現問題的原因,您可以這樣設置requestCode:

將其添加到onCreate之外:

static int i; 

並替換為:

pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent, 0);

有了這個:

pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), i++ /*this number is the PendingIntent's requestCode*/, myIntent, 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM