Reputation: 495
I followed the teaching tried to register the alarm, it should display "TEST" After five seconds,but it did not show any edit- Although you want to do it for five seconds after the alarm, but actually they want to be executed in a fixed time every day -
I should have done all settings, is where it went wrong?
--- AndroidManifest.xml
<receiver android:name=".AlarmClass" android:process=".abc">//What is the role of .abc?
</receiver>
---MainActivity.java
public void AddAlarm(View view){
AlarmManager alm;
PendingIntent pen;
Calendar cal;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy;MM;dd;HH;mm;ss");
Date curDate = new Date(System.currentTimeMillis()) ;
String str = formatter.format(curDate);
String[] aArray = str.split(";");//Split time string
cal = Calendar.getInstance();
cal.set(Integer.parseInt(aArray[0]), Integer.parseInt(aArray[1]), Integer.parseInt(aArray[2]), Integer.parseInt(aArray[3]), Integer.parseInt(aArray[4]), Integer.parseInt(aArray[5]) + 3);
Intent intent = new Intent(this,AlarmClass.class);
alm = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
pen = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_ONE_SHOT);//If I want to set multiple alarms should change the second argument?
alm.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pen);
}
---AlarmCless.java
public class AlarmClass extends BroadcastReceiver {
@Override
public void onReceive (Context context,Intent intent){
Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
}
}
And if I want to set multiple alarms, for example, five seconds and ten seconds later, passing different parameters For example
Toast.makeText(context, teststring, Toast.LENGTH_LONG).show();
But 'teststring' appear differently, how do?
Upvotes: 0
Views: 59
Reputation: 7214
Specify the action tag for the receiver in Manifest.xml
<receiver android:name=".AlarmClass" android:process=".abc">
<action android:name="your_action" />
</receiver>
Here android:process=".abc"
specifies the name of the process in which the broadcast receiver should run.
Declare an intent for sending the broadcast.
Intent intent = new Intent("your_action");
alm = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Declare PendingIntent with its own notification id, bacause no two notification should has the same id, it they has the same id they get overrided.
pen = PendingIntent.getBroadcast(this,notification_id,intent,PendingIntent.FLAG_ONE_SHOT);//If I want to set multiple alarms should change the second argument?
Since you need to send the broadcast after 5sec form now use System.currentTimeMillis()+5000
alm.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,pen);
If you want to send another broadcast after 10sec then follow same above procedure but with different notification_id and use System.currentTimeMillis()+10000 instead of System.currentTimeMillis()+5000
Upvotes: 1