简体   繁体   中英

start an alarm using sms keyword for android

sir, i don't really know how to get my code to work. it just can't start the alarm. it just starts the assigned activity and skip the alarm part. what am i doing wrong. thanks for help in advance

public class EAlarmReceiver extends BroadcastReceiver {

public static String sender;
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Bundle bundle = intent.getExtras(); 
    Object[] pdusObj = (Object[]) bundle.get("pdus"); 
    SmsMessage[] messages = new SmsMessage[pdusObj.length]; 
    for (int i = 0; i<pdusObj.length; i++) 
    { 
            messages[i] = SmsMessage.createFromPdu ((byte[]) 
            pdusObj[i]); 
            sender = messages[i].getOriginatingAddress();
    } 

    for (SmsMessage msg : messages) {
        if (msg.getMessageBody().contains("firealert")) {

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 0);

            Intent i = new Intent(context, ReceiverInterface.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context,
                12345, i, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager am = 
                (AlarmManager)context.getSystemService(Activity.ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                    pendingIntent);
        }//end if
    }//end for

}// end onreceive

The activity starting should give you a clue of what is happening. There is no point in the code that starts the activity unless the alarm is being trigger. The alarm is in fact being triggered, but as you have specified the current time (cal.add(Calendar.SECOND, 0)), it triggers immediately, launching the corresponding PendingIntent. Add the desired time to the calendar in order to get the alarm to trigger in a later time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM