How to keep track of dates/times in Android/java [duplicate] - java

I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples.
Can anyone help me with a basic alarm manager program?

This is working code. It wakes CPU every 10 minutes until the phone turns off.
Add to Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...
Code in your class:
package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Set Alarm from Service:
package yourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this);
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
If you want to set alarm repeating at phone boot time:
Add permission and the service to Manifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
<service
android:name=".YourService"
android:enabled="true"
android:process=":your_service" >
</service>
And create a new class:
package yourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
alarm.setAlarm(context);
}
}
}

I tried the solution from XXX and while it did initially work, at some point it stopped working. The onReceive never got called again. I spent hours trying to figure out what it could be. What I came to realize is that the Intent for whatever mysterious reason was no longer being called. To get around this, I discovered that you really do need to specify an action for the receiver in the manifest. Example:
<receiver android:name=".Alarm" android:exported="true">
<intent-filter>
<action android:name="mypackage.START_ALARM" >
</action>
</intent-filter>
</receiver>
Note that the name is ".Alarm" with the period. In XXX's setAlarm method, create the Intent as follows:
Intent i = new Intent("mypackage.START_ALARM");
The START_ALARM message can be whatever you want it to be. I just gave it that name for demonstration purposes.
I have not seen receivers defined in the manifest without an intent filter that specifies the action. Creating them the way XXX has specified it seems kind of bogus. By specifying the action name, Android will be forced to create an instance of the BroadcastReceiver using the class that corresponds to the action. If you rely upon context, be aware that Android has several different objects that are ALL called context and may not result in getting your BroadcastReceiver created. Forcing Android to create an instance of your class using only the action message is far better than relying upon some iffy context that may never work.

Here's a fairly self-contained example. It turns a button red after 5sec.
public void SetAlarm()
{
final Button button = buttons[2]; // replace with a button from your own UI
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive( Context context, Intent _ )
{
button.setBackgroundColor( Color.RED );
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
}
Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.
I don't know what kind of behavior you would get if your app isn't in memory at all, so be careful with what kind of state you try to preserve.

MainActivity.java
package com.example.alarmexample;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAlert();
} public void startAlert() {
int timeInSec = 2;
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);
Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
#Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmexample" >
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.alarmexample.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>

• AlarmManager in combination with IntentService
I think the best pattern for using AlarmManager is its collaboration with an IntentService. The IntentService is triggered by the AlarmManager and it handles the required actions through the receiving intent. This structure has not performance impact like using BroadcastReceiver. I have developed a sample code for this idea in kotlin which is available here:
MyAlarmManager.kt
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
object MyAlarmManager {
private var pendingIntent: PendingIntent? = null
fun setAlarm(context: Context, alarmTime: Long, message: String) {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, MyIntentService::class.java)
intent.action = MyIntentService.ACTION_SEND_TEST_MESSAGE
intent.putExtra(MyIntentService.EXTRA_MESSAGE, message)
pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
}
fun cancelAlarm(context: Context) {
pendingIntent?.let {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(it)
}
}
}
MyIntentService.kt
import android.app.IntentService
import android.content.Intent
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
intent?.apply {
when (intent.action) {
ACTION_SEND_TEST_MESSAGE -> {
val message = getStringExtra(EXTRA_MESSAGE)
println(message)
}
}
}
}
companion object {
const val ACTION_SEND_TEST_MESSAGE = "ACTION_SEND_TEST_MESSAGE"
const val EXTRA_MESSAGE = "EXTRA_MESSAGE"
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aminography.alarm">
<application
... >
<service
android:name="path.to.MyIntentService"
android:enabled="true"
android:stopWithTask="false" />
</application>
</manifest>
Usage:
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, 10)
MyAlarmManager.setAlarm(applicationContext, calendar.timeInMillis, "Test Message!")
If you want to to cancel the scheduled alarm, try this:
MyAlarmManager.cancelAlarm(applicationContext)

This code will help you to make a repeating alarm. The repeating time can set by you.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:paddingTop="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="#+id/ethr"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Hr"
android:singleLine="true" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etmin"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Min"
android:singleLine="true" />
<EditText
android:id="#+id/etsec"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Sec"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp">
<Button
android:id="#+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
int hr = 0;
int min = 0;
int sec = 0;
int result = 1;
AlarmManager alarmManager;
PendingIntent pendingIntent;
BroadcastReceiver mReceiver;
EditText ethr;
EditText etmin;
EditText etsec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ethr = (EditText) findViewById(R.id.ethr);
etmin = (EditText) findViewById(R.id.etmin);
etsec = (EditText) findViewById(R.id.etsec);
RegisterAlarmBroadcast();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void onClickSetAlarm(View v) {
String shr = ethr.getText().toString();
String smin = etmin.getText().toString();
String ssec = etsec.getText().toString();
if(shr.equals(""))
hr = 0;
else {
hr = Integer.parseInt(ethr.getText().toString());
hr=hr*60*60*1000;
}
if(smin.equals(""))
min = 0;
else {
min = Integer.parseInt(etmin.getText().toString());
min = min*60*1000;
}
if(ssec.equals(""))
sec = 0;
else {
sec = Integer.parseInt(etsec.getText().toString());
sec = sec * 1000;
}
result = hr+min+sec;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
}
private void RegisterAlarmBroadcast() {
mReceiver = new BroadcastReceiver() {
// private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
registerReceiver(mReceiver, new IntentFilter("sample"));
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
}
private void UnregisterAlarmBroadcast() {
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
}
If you need alarm only for a single time then replace
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
with
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );

Alarm Manager:
Add To XML Layout (*init these view on create in main activity)
<TimePicker
android:id="#+id/timepicker"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"></TimePicker>
<Button
android:id="#+id/btn_start"
android:text="start Alarm"
android:onClick="start_alarm_event"
android:layout_width="match_parent"
android:layout_height="52dp" />
Add To Manifest (Inside application tag && outside activity)
<receiver android:name=".AlarmBroadcastManager"
android:enabled="true"
android:exported="true"/>
Create AlarmBroadcastManager Class(inherit it from BroadcastReceiver)
public class AlarmBroadcastManager extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
In Main Activity (Add these Functions):
#RequiresApi(api = Build.VERSION_CODES.M)
public void start_alarm_event(View view){
Calendar calendar=Calendar.getInstance();
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(),
timePicker.getMinute(),
0
);
setAlarm(calendar.getTimeInMillis());
}
public void setAlarm(long timeInMillis){
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(this,AlarmBroadcastManager.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent);
Toast.makeText(getApplicationContext(),"Alarm is Set",Toast.LENGTH_SHORT).show();
}

I have made my own implementation to do this on the simplest way as possible.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public void stop() {
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener);
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
backgroundTaskListener.perform(context, intent);
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
The only next step, implement it.
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import ...AbstractSystemServiceTask;
import java.util.concurrent.TimeUnit;
/**
* Created by Daniel on 28/08/2016.
*/
public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask {
private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE";
private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10);
private final static AlarmType ALARM_TYPE = AlarmType.REPEAT;
public UpdateInfoSystemServiceTask(Context context) {
super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() {
#Override
public void perform(Context context, Intent intent) {
Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask");
//DO HERE WHATEVER YOU WANT...
}
});
Log.i("MyAppLog", "UpdateInfoSystemServiceTask started.");
}
}
I like to work with this implementation, but another possible good way, it's don't make the AbstractSystemServiceTask class abstract, and build it through a Builder.
I hope it help you.
UPDATED
Improved to allow several BackgroundTaskListener on the same BroadCastReceiver.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
private final Set<BackgroundTaskListener> backgroundTaskListenerSet;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.backgroundTaskListenerSet = new HashSet<>();
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.add(backgroundTaskListener);
}
public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.remove(backgroundTaskListener);
}
public void stop() {
this.backgroundTaskListenerSet.clear();
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver() {
return new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) {
backgroundTaskListener.perform(context, intent);
}
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}

Here's an example with Alarm Manager using Kotlin:
class MainActivity : AppCompatActivity() {
val editText: EditText by bindView(R.id.edit_text)
val timePicker: TimePicker by bindView(R.id.time_picker)
val buttonSet: Button by bindView(R.id.button_set)
val buttonCancel: Button by bindView(R.id.button_cancel)
val relativeLayout: RelativeLayout by bindView(R.id.activity_main)
var notificationId = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
timePicker.setIs24HourView(true)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
buttonSet.setOnClickListener {
if (editText.text.isBlank()) {
Toast.makeText(applicationContext, "Title is Required!!", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
alarmManager.set(
AlarmManager.RTC_WAKEUP,
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, timePicker.hour)
set(Calendar.MINUTE, timePicker.minute)
set(Calendar.SECOND, 0)
}.timeInMillis,
PendingIntent.getBroadcast(
applicationContext,
0,
Intent(applicationContext, AlarmBroadcastReceiver::class.java).apply {
putExtra("notificationId", ++notificationId)
putExtra("reminder", editText.text)
},
PendingIntent.FLAG_CANCEL_CURRENT
)
)
Toast.makeText(applicationContext, "SET!! ${editText.text}", Toast.LENGTH_SHORT).show()
reset()
}
buttonCancel.setOnClickListener {
alarmManager.cancel(
PendingIntent.getBroadcast(
applicationContext, 0, Intent(applicationContext, AlarmBroadcastReceiver::class.java), 0))
Toast.makeText(applicationContext, "CANCEL!!", Toast.LENGTH_SHORT).show()
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(relativeLayout.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
relativeLayout.requestFocus()
return super.onTouchEvent(event)
}
override fun onResume() {
super.onResume()
reset()
}
private fun reset() {
timePicker.apply {
val now = Calendar.getInstance()
hour = now.get(Calendar.HOUR_OF_DAY)
minute = now.get(Calendar.MINUTE)
}
editText.setText("")
}
}

I was having a problem with alarms in Android too. The problem was about the doze mode (https://developer.android.com/training/monitoring-device-state/doze-standby). For example, the alarm worked fine when I set it to one hour further, but it didn't work if it was set to 4am. I just discovered it is very simple, I just should use AlarmManager.setAlarmClock() instead of AlarmManager.set().
So I decided to create an example application on github.
https://github.com/carlosabreu/androidalarm

Related

I am not able to set Notification in android app when app is closed

In my app(java) I am getting values from two different crypto Exchange. Then doing some calculation and getting output values. Values are refreshing every second. Now I want to set alert/notification whenever output values is greater than specific value. I want this whenever app is closed or running. How to do that because I am not able to do that when app is closed? Thanks.
You have to use Foreground Service to enable notification even when app is closed .
According to AndroidDevelopers,
Foreground services perform operations that are noticeable to the
user. Each foreground service must show a status bar notification that
has a priority of PRIORITY_LOW or higher. That way, users are actively
aware that your app is performing a task in the foreground and is
consuming system resources.
https://developer.android.com/guide/components/foreground-services
Example of code from Programmer'sWorld, to create foreground services and notification in your Android App
package com.example.myserviceclass;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
private Integer alarmHour;
private Integer alarmMinute;
private Ringtone ringtone;
private Timer t = new Timer();
private static final String CHANNEL_ID = “MyNotificationChannelID”;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarmHour = intent.getIntExtra(“alarmHour”, 0);
alarmMinute = intent.getIntExtra(“alarmMinute”, 0);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
try {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID )
.setContentTitle(“My Alarm clock”)
.setContentText(“Alarm time – ” + alarmHour.toString() + ” : ” + alarmMinute.toString())
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, “My Alarm clock Service”, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
catch (Exception e){
e.printStackTrace();
}
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (Calendar.getInstance().getTime().getHours() == alarmHour &&
Calendar.getInstance().getTime().getMinutes() == alarmMinute){
ringtone.play();
}
else {
ringtone.stop();
}
}
}, 0, 2000);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
ringtone.stop();
t.cancel();
super.onDestroy();
}
}
package com.example.myserviceclass;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TimePicker;
public class MainActivity extends AppCompatActivity {
private TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.FOREGROUND_SERVICE}, PackageManager.PERMISSION_GRANTED);
timePicker = findViewById(R.id.timPicker);
final Intent intent = new Intent(this, MyService.class);
ServiceCaller(intent);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker timePicker, int i, int i1) {
ServiceCaller(intent);
}
});
}
private void ServiceCaller(Intent intent){
stopService(intent);
Integer alarmHour = timePicker.getCurrentHour();
Integer alarmMinute = timePicker.getCurrentMinute();
intent.putExtra(“alarmHour”, alarmHour);
intent.putExtra(“alarmMinute”, alarmMinute);
startService(intent);
}
}
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.myserviceclass”>
<uses-permission android:name=”android.permission.FOREGROUND_SERVICE”/>
<application
android:allowBackup=”true”
android:icon=”#mipmap/ic_launcher”
android:label=”#string/app_name”
android:roundIcon=”#mipmap/ic_launcher_round”
android:supportsRtl=”true”
android:theme=”#style/AppTheme”>
<service android:name=”.MyService”/>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>
You can do with Notification setting.
first go in setting,
then in notification setting ,
on notification for your app.
Thank you
For this purpose, you can create a foreground service running. This way, you'll be able to notify the user even after he has exited out from the App.
Reference : https://developer.android.com/guide/components/foreground-services?authuser=1

Android: Alarm not being triggered through AlarmManager

I am writing a simple Android program that triggers an alarm 15 seconds after the application initialization (plays the default ringtone and pushes a notification) through AlarmManager. Below is my code:
MainActivity.java:
package com.example.basicalarmsetter;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
public class MainActivity extends AppCompatActivity {
private int uniqueId = 0;
// Schedules a notification in the future given the delay
#RequiresApi(api = Build.VERSION_CODES.O)
private void scheduleNotification(int matchId, long delay) {
// Construct the PendingIntent which will trigger our alarm to go off
Intent notificationIntent = new Intent();
notificationIntent.setAction("com.example.basicalarmsetter.MatchNotification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), matchId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) ;
long futureInMillis = SystemClock.elapsedRealtime() + delay;
// Set off our PendingIntent
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, futureInMillis, pendingIntent);
assert alarmManager != null;
alarmManager.setExact(AlarmManager. ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
// Sets an Alarm at a future specified date
#RequiresApi(api = Build.VERSION_CODES.O)
private void setAlarm(long notificationDelay) {
try {
System.out.println("Setting alarm at " + notificationDelay + " seconds");
// Sets off a notification after 5 seconds
scheduleNotification(uniqueId, notificationDelay);
uniqueId++;
} catch (Exception ex) {
System.out.println("Cannot print alarm!");
System.out.println("Exception: " + ex.toString());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm(15000);
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.basicalarmsetter">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.example.basicalarmsetter.MatchNotification"
android:enabled="true"
android:exported="true">
<intent-filter>
...
<action android:name="com.example.notificationtest.MatchNotification" />
</intent-filter>
</receiver>
</application>
</manifest>
MatchNotification.kt:
package com.example.basicalarmsetter
import android.app.Notification
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.net.Uri
import androidx.core.app.NotificationCompat
class MatchNotification : BroadcastReceiver() {
var NOTIFICATION_ID = "notification-id"
var NOTIFICATION_CHANNEL_ID = "10001";
private lateinit var player: MediaPlayer;
private lateinit var context: Context;
// Construct the notification to push to the user given the teams in the match
private fun getNotification(
content: String
): Notification? {
val builder = NotificationCompat.Builder(
context,
"default"
)
builder.setContentTitle("NBA Alarm")
builder.setStyle(NotificationCompat.BigTextStyle().bigText(content))
builder.setContentText(content)
builder.setSmallIcon(R.drawable.ic_launcher_foreground)
builder.setAutoCancel(true)
builder.setChannelId(NOTIFICATION_CHANNEL_ID)
return builder.build()
}
override fun onReceive(context: Context, intent: Intent) {
System.out.println("Match Notification Activated.");
this.context = context
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val id = intent.getIntExtra(NOTIFICATION_ID, 0)
notificationManager.notify(id, getNotification("Trigger Notification!"))
// Retrieve the URI of the alarm the user has set
var ringtoneUri:Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
player = MediaPlayer.create(context, ringtoneUri)
player.start()
}
}
This seems strange, consdering that I have specified my MatchNotification class as a receiver in my AndroidManifest.xml file.
Devices Tested On:
Motorola Moto E6 (Android 9)
Emulator for Pixel 2 (API 26)
Note: The solution should have the MainActivity code in Java
This part of your code seems wrong:
notificationIntent.setAction("com.example.basicalarmsetter.MatchNotification");
You're using the class name here. You need to use the action of the broadcast receiver, the one you put in your intent filter, a.k.a:
notificationIntent.setAction("com.example.notificationtest.MatchNotification");
Another issue: You're creating two alarms, which is unnecessary, at here:
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, futureInMillis, pendingIntent);
assert alarmManager != null;
alarmManager.setExact(AlarmManager. ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
At this section, following lines are unnecessary:
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, futureInMillis, pendingIntent);
assert alarmManager != null;
The value RTC_WAKEUP is supposed to be used with System.currentTimeMillis(), not SystemClock.elapsedRealtime().
The final of your MainActivity.java would look like this:
package com.example.basicalarmsetter;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
public class MainActivity extends AppCompatActivity {
private int uniqueId = 0;
// Schedules a notification in the future given the delay
#RequiresApi(api = Build.VERSION_CODES.O)
private void scheduleNotification(int matchId, long delay) {
// Construct the PendingIntent which will trigger our alarm to go off
Intent notificationIntent = new Intent();
notificationIntent.setAction("com.example.notificationtest.MatchNotification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), matchId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) ;
long futureInMillis = SystemClock.elapsedRealtime() + delay;
// Set off our PendingIntent
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager. ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
// Sets an Alarm at a future specified date
#RequiresApi(api = Build.VERSION_CODES.O)
private void setAlarm(long notificationDelay) {
try {
System.out.println("Setting alarm at " + notificationDelay + " seconds");
// Sets off a notification after 5 seconds
scheduleNotification(uniqueId, notificationDelay);
uniqueId++;
} catch (Exception ex) {
System.out.println("Cannot print alarm!");
System.out.println("Exception: " + ex.toString());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm(15000);
}
}
i have a solution that worked for me. Set alert as follow:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long delayInMillis = 5000;//your delay in millisecond
Intent myIntent = new Intent(this, AlertReceiver.class);
//any data you want to pass to your receiver class
myIntent.putExtra(AlertReceiver.TITLE, "Scheduled Alert");
myIntent.putExtra(AlertReceiver.CONTENT, "You have scheduled alert. Tap here to view continue...");
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, delayInMillis, pendingIntent);
}
}
add reveiver in your manifest
<receiver android:name=".utils.AlertReceiver" />//path to your receiver
your alert receiver class can be something like this
public class AlertReceiver extends BroadcastReceiver {
private static final String TAG = "AlertReceiver";
public static final String TITLE = "title";
public static final String CONTENT = "content";
#Override
public void onReceive(Context context, Intent receivedIntent) {
String title = receivedIntent.getStringExtra(TITLE);
String message = receivedIntent.getStringExtra(CONTENT);
Log.e(TAG, "onReceive: " + title + ":" + message);
//you can show your notification or anything you want to do once you receive your alert here...
}
}
hope this helps. Happy codding!!
Hi it seems to be like you haven't checked that is alarm running in the background or not and there must be some old code
Try the below code just paste it and nothing to do extra with AndroidManifest file and run.
class MyActivity : AppCompatActivity() {
private var alarmManager: AlarmManager? = null
private var broadcastReceiver: BroadcastReceiver? = null
private var pendingIntent: PendingIntent? = null
private val REQUEST_CODE = 45645
private var id: String? = "myname"
private var timeInMilliSeconds: Long = 15000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
initAlarm()
}
private fun initAlarm() {
//creating intent
val intent = Intent(id)
val alarmRunning = PendingIntent.getBroadcast(
this,
REQUEST_CODE,
intent,
PendingIntent.FLAG_NO_CREATE
) != null
//setting broadcast
broadcastReceiver = getBroadcastReceiver()
registerReceiver(
broadcastReceiver,
IntentFilter(id)
)
//setting alarm
val ensurePositiveTime = Math.max(timeInMilliSeconds, 0L)
pendingIntent = PendingIntent.getBroadcast(
this,
REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
//Check if alarm is already running
if (!alarmRunning) {
alarmManager?.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent)
} else {
updateAlarm()
Log.e("Alarm", "Alarm already running.!")
}
}
private fun updateAlarm() {
//calculating alarm time and creating pending intent
val intent = Intent(id)
val ensurePositiveTime = Math.max(timeInMilliSeconds, 0L)
pendingIntent = PendingIntent.getBroadcast(
this,
REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
//removing previously running alarm
alarmManager?.cancel(pendingIntent)
unregisterReceiver(broadcastReceiver)
//setting broadcast
broadcastReceiver = getBroadcastReceiver()
registerReceiver(
broadcastReceiver,
IntentFilter(id)
)
//Check if alarm is already running
alarmManager?.set(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + ensurePositiveTime,
pendingIntent
)
Log.e("Alarm", "Alarm updated..!")
}
/**
* This will receive broadcast after completed seconds
*/
private fun getBroadcastReceiver(): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
createNotification()
}
}
}
/***
* It creates notification
*/
private fun createNotification() {
val channelId = "fcm_default_channel"
val channelName = "notification"
val defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this#MyActivity, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("I am alarm from my activity")
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
val mNotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel =
NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH
)
notificationBuilder.setChannelId(channelId)
mNotificationManager.createNotificationChannel(channel)
}
val notification = notificationBuilder.build()
mNotificationManager.notify(0, notification)
}
/**
* Use this to cancel alarm
*/
private fun cancelAlarm() {
if (pendingIntent != null) {
alarmManager?.cancel(pendingIntent)
}
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver)
broadcastReceiver = null
}
Log.e("Alarm", "Alarm has been canceled..!")
}
}
Below is java code
public class AlarmActivity extends AppCompatActivity {
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
private int REQUEST_CODE = 45645;
private String id = "myname";
private long timeInMilliSeconds = 5000;
static String APP_TAG = "classname";
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
initAlarm();
}
private void initAlarm() {
//creating intent
Intent intent = new Intent(id);
boolean alarmRunning = PendingIntent.getBroadcast(
this,
REQUEST_CODE,
intent,
PendingIntent.FLAG_NO_CREATE
) != null;
//setting broadcast
broadcastReceiver = new MyReceiver();
registerReceiver(
broadcastReceiver,
new IntentFilter(id)
);
//setting alarm
long ensurePositiveTime = Math.max(timeInMilliSeconds, 0L);
pendingIntent = PendingIntent.getBroadcast(
this,
REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
//Check if alarm is already running
if (!alarmRunning) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + ensurePositiveTime,
pendingIntent
);
} else {
updateAlarm();
Log.e("Alarm", "Alarm already running.!");
}
}
private void updateAlarm() {
//calculating alarm time and creating pending intent
Intent intent = new Intent(id);
long ensurePositiveTime = Math.max(timeInMilliSeconds, 0L);
pendingIntent = PendingIntent.getBroadcast(
this,
REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
//removing previously running alarm
alarmManager.cancel(pendingIntent);
unregisterReceiver(broadcastReceiver);
//setting broadcast
broadcastReceiver = new MyReceiver();
registerReceiver(
broadcastReceiver,
new IntentFilter(id)
);
//Check if alarm is already running
alarmManager.set(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + ensurePositiveTime,
pendingIntent
);
Log.e("Alarm", "Alarm updated..!");
}
/**
* Use this to cancel alarm
*/
private void cancelAlarm() {
if (pendingIntent != null) {
alarmManager.cancel(pendingIntent);
}
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
Log.e("Alarm", "Alarm has been canceled..!");
}
}
BroadCastReceiver class
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WakeLocker.acquire(context);
createNotification(context);
WakeLocker.release();
}
/***
* It creates notification
* #param context
*/
private void createNotification(Context context) {
String channelId = "fcm_default_channel";
String channelName = "notification";
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("I am alarm from my activity")
.setContentTitle(context.getString(R.string.app_name))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel =
new NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH
);
notificationBuilder.setChannelId(channelId);
mNotificationManager.createNotificationChannel(channel);
}
Notification notification = notificationBuilder.build();
mNotificationManager.notify(0, notification);
}
}
Wake Locker class to keep running in background also, but for this you have to enable background services from app setting and disable the power saving mode
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context c) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) c.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, AlarmActivity.APP_TAG);
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null){
wakeLock.release();
}
wakeLock = null;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Alarmdemo">
<activity android:name=".AlarmActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.alarmdemo.MyReceiver" />
</application>

What are the ways to check 24 hours are completed?

In my application I have to check whether the 24 hours are completed.
How do I check such things using Thread, TimerTask and Alaram Manager.
Let me know how do I achieve this thing using TIMERTASK and THREAD ?
Use Alarm Manager:
A small example:
This is working code. It wakes CPU every 10 minutes until the phone turns off.
Add to Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name="Alarm"></receiver>
...
Code:
package YourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Set Alarm from Service:
package YourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
public void onStart(Context context,Intent intent, int startId)
{
alarm.SetAlarm(context);
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
If you want set alarm repeating at phone boot time:
Add permission to Manifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
And create new class:
package YourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
alarm.SetAlarm(context);
}
}
}
Alarms work in a different manner on and after API 19, make sure you are using API 18 and below if you want this to work. Otherwise you can include methods for API 19 from the official Docs.
If you want to know whether 24 hours has passed since last time, from inside app, I use sharedpreference by storing last time this check passed,
long hourSince1970 = System.currentTimeMillis()/3600000;
long lastUpdatedHour = MySharedPreference.getTimeLastUpdated(); // defaults to 0
if(lastUpdatedHour == 0 || hourSince1970-lastUpdatedHour >= 24){
MySharedPreference.setTimeLastUpdated(hourSince1970);
// 24 hours passed
// do your thing
}

Using a widget with buttons to set device volume on Android, easy question...?

I am simply trying to make a widget with a + button, a - Button, and a progress bar. The bar should show the current volume and the plus and minus buttons should control the phone volume. Right now I am just trying to get the plus button to do its function (the progress bar already shows the right volume when the widget is initiated) but whenever I click the button I get a force close. I've done apps before but never widgets, and I haven't worked with intents much. Here is the code to the only class my Widget has:
package com.habosa.volumeslider;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
public class VolumeWidgetProvider extends AppWidgetProvider {
private AudioManager volume;
private int whichStream = AudioManager.STREAM_RING;
public void goRinger() {
whichStream = AudioManager.STREAM_RING;
}
public void goMedia() {
whichStream = AudioManager.STREAM_MUSIC;
}
public void goAlarm() {
whichStream = AudioManager.STREAM_ALARM;
}
public void goNotification() {
whichStream = AudioManager.STREAM_NOTIFICATION;
}
public void volumeUp() {
volume.adjustStreamVolume(whichStream, AudioManager.ADJUST_RAISE, 0);
}
public void volumeDown() {
volume.adjustStreamVolume(whichStream, AudioManager.ADJUST_LOWER, 0);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
volume = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int maxVol = volume.getStreamMaxVolume(whichStream);
int currentVol = volume.getStreamVolume(whichStream);
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.main);
remoteView.setProgressBar(R.id.ProgressBar01, maxVol, currentVol, false);
Intent plus = new Intent(context, VolumeWidgetProvider.class);
plus.putExtra("msg", "plus");
plus.setAction("BUTTONPRESS");
PendingIntent plusPendingIntent = PendingIntent.getBroadcast(context, 0, plus, 0);
remoteView.setOnClickPendingIntent(R.id.PlusButton, plusPendingIntent);
for (int appWidgetId : appWidgetIds) {
appWidgetManager.updateAppWidget(appWidgetId, remoteView);
}
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("BUTTONPRESS")) {
String msg = "null";
try {
msg = intent.getStringExtra("msg");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
if (msg.equals("plus")) {volumeUp();}
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
} else {
// do nothing
}
super.onReceive(context, intent);
}
}
and here is my manifest if that is relevant:
<?xml version="1.0" encoding="utf-8"?>
<receiver android:name="VolumeWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="com.habosa.volumeslider.VolumeWidgetProvider.BUTTONPRESS"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/volumewidgetproviderinfo" />
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
What am I doing wrong?
Take a look at https://github.com/commonsguy/cw-andtutorials/tree/master/34-AdvAppWidget for a decent example to follow.
Note that the solution probably won't be to invoke the app widget provider class from the Intent, as you're apparently trying to do currently.

Alarm Manager Example

I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples.
Can anyone help me with a basic alarm manager program?
This is working code. It wakes CPU every 10 minutes until the phone turns off.
Add to Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...
Code in your class:
package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Set Alarm from Service:
package yourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this);
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
If you want to set alarm repeating at phone boot time:
Add permission and the service to Manifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
<service
android:name=".YourService"
android:enabled="true"
android:process=":your_service" >
</service>
And create a new class:
package yourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
alarm.setAlarm(context);
}
}
}
I tried the solution from XXX and while it did initially work, at some point it stopped working. The onReceive never got called again. I spent hours trying to figure out what it could be. What I came to realize is that the Intent for whatever mysterious reason was no longer being called. To get around this, I discovered that you really do need to specify an action for the receiver in the manifest. Example:
<receiver android:name=".Alarm" android:exported="true">
<intent-filter>
<action android:name="mypackage.START_ALARM" >
</action>
</intent-filter>
</receiver>
Note that the name is ".Alarm" with the period. In XXX's setAlarm method, create the Intent as follows:
Intent i = new Intent("mypackage.START_ALARM");
The START_ALARM message can be whatever you want it to be. I just gave it that name for demonstration purposes.
I have not seen receivers defined in the manifest without an intent filter that specifies the action. Creating them the way XXX has specified it seems kind of bogus. By specifying the action name, Android will be forced to create an instance of the BroadcastReceiver using the class that corresponds to the action. If you rely upon context, be aware that Android has several different objects that are ALL called context and may not result in getting your BroadcastReceiver created. Forcing Android to create an instance of your class using only the action message is far better than relying upon some iffy context that may never work.
Here's a fairly self-contained example. It turns a button red after 5sec.
public void SetAlarm()
{
final Button button = buttons[2]; // replace with a button from your own UI
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive( Context context, Intent _ )
{
button.setBackgroundColor( Color.RED );
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
}
Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.
I don't know what kind of behavior you would get if your app isn't in memory at all, so be careful with what kind of state you try to preserve.
MainActivity.java
package com.example.alarmexample;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAlert();
} public void startAlert() {
int timeInSec = 2;
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);
Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
#Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmexample" >
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.alarmexample.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
• AlarmManager in combination with IntentService
I think the best pattern for using AlarmManager is its collaboration with an IntentService. The IntentService is triggered by the AlarmManager and it handles the required actions through the receiving intent. This structure has not performance impact like using BroadcastReceiver. I have developed a sample code for this idea in kotlin which is available here:
MyAlarmManager.kt
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
object MyAlarmManager {
private var pendingIntent: PendingIntent? = null
fun setAlarm(context: Context, alarmTime: Long, message: String) {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, MyIntentService::class.java)
intent.action = MyIntentService.ACTION_SEND_TEST_MESSAGE
intent.putExtra(MyIntentService.EXTRA_MESSAGE, message)
pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
}
fun cancelAlarm(context: Context) {
pendingIntent?.let {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(it)
}
}
}
MyIntentService.kt
import android.app.IntentService
import android.content.Intent
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
intent?.apply {
when (intent.action) {
ACTION_SEND_TEST_MESSAGE -> {
val message = getStringExtra(EXTRA_MESSAGE)
println(message)
}
}
}
}
companion object {
const val ACTION_SEND_TEST_MESSAGE = "ACTION_SEND_TEST_MESSAGE"
const val EXTRA_MESSAGE = "EXTRA_MESSAGE"
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aminography.alarm">
<application
... >
<service
android:name="path.to.MyIntentService"
android:enabled="true"
android:stopWithTask="false" />
</application>
</manifest>
Usage:
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, 10)
MyAlarmManager.setAlarm(applicationContext, calendar.timeInMillis, "Test Message!")
If you want to to cancel the scheduled alarm, try this:
MyAlarmManager.cancelAlarm(applicationContext)
This code will help you to make a repeating alarm. The repeating time can set by you.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:paddingTop="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="#+id/ethr"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Hr"
android:singleLine="true" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etmin"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Min"
android:singleLine="true" />
<EditText
android:id="#+id/etsec"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Sec"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp">
<Button
android:id="#+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
int hr = 0;
int min = 0;
int sec = 0;
int result = 1;
AlarmManager alarmManager;
PendingIntent pendingIntent;
BroadcastReceiver mReceiver;
EditText ethr;
EditText etmin;
EditText etsec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ethr = (EditText) findViewById(R.id.ethr);
etmin = (EditText) findViewById(R.id.etmin);
etsec = (EditText) findViewById(R.id.etsec);
RegisterAlarmBroadcast();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void onClickSetAlarm(View v) {
String shr = ethr.getText().toString();
String smin = etmin.getText().toString();
String ssec = etsec.getText().toString();
if(shr.equals(""))
hr = 0;
else {
hr = Integer.parseInt(ethr.getText().toString());
hr=hr*60*60*1000;
}
if(smin.equals(""))
min = 0;
else {
min = Integer.parseInt(etmin.getText().toString());
min = min*60*1000;
}
if(ssec.equals(""))
sec = 0;
else {
sec = Integer.parseInt(etsec.getText().toString());
sec = sec * 1000;
}
result = hr+min+sec;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
}
private void RegisterAlarmBroadcast() {
mReceiver = new BroadcastReceiver() {
// private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
registerReceiver(mReceiver, new IntentFilter("sample"));
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
}
private void UnregisterAlarmBroadcast() {
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
}
If you need alarm only for a single time then replace
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
with
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );
Alarm Manager:
Add To XML Layout (*init these view on create in main activity)
<TimePicker
android:id="#+id/timepicker"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"></TimePicker>
<Button
android:id="#+id/btn_start"
android:text="start Alarm"
android:onClick="start_alarm_event"
android:layout_width="match_parent"
android:layout_height="52dp" />
Add To Manifest (Inside application tag && outside activity)
<receiver android:name=".AlarmBroadcastManager"
android:enabled="true"
android:exported="true"/>
Create AlarmBroadcastManager Class(inherit it from BroadcastReceiver)
public class AlarmBroadcastManager extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
In Main Activity (Add these Functions):
#RequiresApi(api = Build.VERSION_CODES.M)
public void start_alarm_event(View view){
Calendar calendar=Calendar.getInstance();
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(),
timePicker.getMinute(),
0
);
setAlarm(calendar.getTimeInMillis());
}
public void setAlarm(long timeInMillis){
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(this,AlarmBroadcastManager.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent);
Toast.makeText(getApplicationContext(),"Alarm is Set",Toast.LENGTH_SHORT).show();
}
I have made my own implementation to do this on the simplest way as possible.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public void stop() {
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener);
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
backgroundTaskListener.perform(context, intent);
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
The only next step, implement it.
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import ...AbstractSystemServiceTask;
import java.util.concurrent.TimeUnit;
/**
* Created by Daniel on 28/08/2016.
*/
public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask {
private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE";
private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10);
private final static AlarmType ALARM_TYPE = AlarmType.REPEAT;
public UpdateInfoSystemServiceTask(Context context) {
super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() {
#Override
public void perform(Context context, Intent intent) {
Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask");
//DO HERE WHATEVER YOU WANT...
}
});
Log.i("MyAppLog", "UpdateInfoSystemServiceTask started.");
}
}
I like to work with this implementation, but another possible good way, it's don't make the AbstractSystemServiceTask class abstract, and build it through a Builder.
I hope it help you.
UPDATED
Improved to allow several BackgroundTaskListener on the same BroadCastReceiver.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
private final Set<BackgroundTaskListener> backgroundTaskListenerSet;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.backgroundTaskListenerSet = new HashSet<>();
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.add(backgroundTaskListener);
}
public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.remove(backgroundTaskListener);
}
public void stop() {
this.backgroundTaskListenerSet.clear();
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver() {
return new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) {
backgroundTaskListener.perform(context, intent);
}
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
Here's an example with Alarm Manager using Kotlin:
class MainActivity : AppCompatActivity() {
val editText: EditText by bindView(R.id.edit_text)
val timePicker: TimePicker by bindView(R.id.time_picker)
val buttonSet: Button by bindView(R.id.button_set)
val buttonCancel: Button by bindView(R.id.button_cancel)
val relativeLayout: RelativeLayout by bindView(R.id.activity_main)
var notificationId = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
timePicker.setIs24HourView(true)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
buttonSet.setOnClickListener {
if (editText.text.isBlank()) {
Toast.makeText(applicationContext, "Title is Required!!", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
alarmManager.set(
AlarmManager.RTC_WAKEUP,
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, timePicker.hour)
set(Calendar.MINUTE, timePicker.minute)
set(Calendar.SECOND, 0)
}.timeInMillis,
PendingIntent.getBroadcast(
applicationContext,
0,
Intent(applicationContext, AlarmBroadcastReceiver::class.java).apply {
putExtra("notificationId", ++notificationId)
putExtra("reminder", editText.text)
},
PendingIntent.FLAG_CANCEL_CURRENT
)
)
Toast.makeText(applicationContext, "SET!! ${editText.text}", Toast.LENGTH_SHORT).show()
reset()
}
buttonCancel.setOnClickListener {
alarmManager.cancel(
PendingIntent.getBroadcast(
applicationContext, 0, Intent(applicationContext, AlarmBroadcastReceiver::class.java), 0))
Toast.makeText(applicationContext, "CANCEL!!", Toast.LENGTH_SHORT).show()
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(relativeLayout.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
relativeLayout.requestFocus()
return super.onTouchEvent(event)
}
override fun onResume() {
super.onResume()
reset()
}
private fun reset() {
timePicker.apply {
val now = Calendar.getInstance()
hour = now.get(Calendar.HOUR_OF_DAY)
minute = now.get(Calendar.MINUTE)
}
editText.setText("")
}
}
I was having a problem with alarms in Android too. The problem was about the doze mode (https://developer.android.com/training/monitoring-device-state/doze-standby). For example, the alarm worked fine when I set it to one hour further, but it didn't work if it was set to 4am. I just discovered it is very simple, I just should use AlarmManager.setAlarmClock() instead of AlarmManager.set().
So I decided to create an example application on github.
https://github.com/carlosabreu/androidalarm

Categories

Resources