Hello guys, Today I am going to share the knowledge about Alarm coding in java. There is class in Android API that manage the Alarm that is AlarmManager .And need to registered the broadcast Register, that one time it automatically trigger.
Main.xml
AlarmActivity.java
package app.test;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast;
public class AlarmActivity extends Activity implements View.OnClickListener {
private PendingIntent mAlarmIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
Intent launchIntent = new Intent(this, AlarmReceiver.class);
mAlarmIntent = PendingIntent.getBroadcast(this, 0, launchIntent, 0);
}
@Override
public void onClick(View v) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
long interval = 5*1000; //5 seconds
switch(v.getId()) {
case R.id.start:
Toast.makeText(this, "Scheduled", Toast.LENGTH_SHORT).show();
manager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime()+interval,
interval,
mAlarmIntent);
break;
case R.id.stop:
Toast.makeText(this, "Canceled", Toast.LENGTH_SHORT).show();
manager.cancel(mAlarmIntent);
break;
default:
break;
}
}
private long nextStartTime() {
long oneDay = 24*3600*1000; //24 hours
//Set the time to 09:00:00
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 9);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.SECOND, 0);
Calendar now = Calendar.getInstance();
if(now.before(startTime)) {
return startTime.getTimeInMillis();
} else {
startTime.add(Calendar.DATE, 1);
return startTime.getTimeInMillis();
}
}
}
AlarmReceiver.java
package app.test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Calendar now = Calendar.getInstance();
DateFormat formatter = SimpleDateFormat.getTimeInstance();
Toast.makeText(context, formatter.format(now.getTime()), Toast.LENGTH_SHORT).show();
}
}
Update Contact :
No Wa/Telepon (puat) : 085267792168
No Wa/Telepon (fajar) : 085369237896
Email : Fajarudinsidik@gmail.com
No Wa/Telepon (puat) : 085267792168
No Wa/Telepon (fajar) : 085369237896
Email: Fajarudinsidik@gmail.com
atau Kirimkan Private messanger melalui email dengan klik tombol order dibawah ini :