Android Display Toast When Alarm Timer Is Triggered - android

I am trying to figure out how alarm timers work so I can trigger an event when a user selects the predefined times in the app. To start off I just want to show a toast so I can clearly see the app is working. But when I run the app and set the time for 10 seconds the class handling my Intent never seems to get called.
I am using Log.d in the Main and I can see it being logged correctly when the button is clicked. But the event does not fire off at the selected time.
This is the function that fires off when the button is clicked and the Log.d is displayed in the console.
public void scheduleAlarm()
{
Long time = System.currentTimeMillis() + 10000;
Log.d("logs", "This is running in the main act");
Intent intentAlarm = new Intent(this, affirmationSchedule.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Has Been Scheduled", Toast.LENGTH_LONG).show();
}
And this is the class which handles the code to run when the alarm time comes
public class affirmationSchedule extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("logs", "This function is running");
Toast.makeText(context, "this is a toast working.", Toast.LENGTH_LONG).show();
}
}
Log.d never displays. the toast in this class never displays.
This leads me to believe I am not creating my object correctly.
This is how I am registering receiver in the manifest.
<receiver
android:name="com.wuno.wunoaffirmations"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.wuno.BroadcastReceiver" />
</intent-filter>
</receiver>
Any ideas?
This might be relevant,
After I click the button and the original toast goes away. This pops up in console.
05-16 23:10:11.989 14242-14268/com.wuno.wunoaffirmations E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4015c60
But not in ten seconds. More like 5.The alarmManager is set for 10 seconds.

This how i used alarm manager within a project of mine. Basically i followed some code from a google's app code. so here it is. I hope this will help you.
How to use it? Well just Create instance of AlramReciver and then set it.
private AlarmReceiver alarmReceiver = new AlarmReceiver();
alramReceiver.setAlram();
This is helper class which set the alram receiver.
public class AlarmReceiver extends WakefulBroadcastReceiver {
private static AlarmManager alarmManager;
private static PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
/*
* If your receiver intent includes extras that need to be passed along to the
* service, use setComponent() to indicate that the service should handle the
* receiver's intent. For example:
*
* ComponentName comp = new ComponentName(context.getPackageName(),
* MyService.class.getName());
*
* // This intent passed in this call will include the wake lock extra as well as
* // the receiver intent contents.
* startWakefulService(context, (intent.setComponent(comp)));
*
* In this example, we simply create a new intent to deliver to the service.
* This intent holds an extra identifying the wake lock.
*/
Intent service= new Intent(context, AlarmService.class);
startWakefulService(context,service);
}
/**
*set the alram
* #param context
*/
public void setAlarm(Context context){
alarmManager=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent =PendingIntent.getBroadcast(context,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 60, alarmIntent);
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
/**
* cancels the alram
* #param context
*/
public void cancelAlarm(Context context){
// If the alarm has been set, cancel it.
if (alarmManager!= null) {
alarmManager.cancel(alarmIntent);
}
// Disable {#code SampleBootReceiver} so that it doesn't automatically restart the
// alarm when the device is rebooted.
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
This is bootReceiver class used when your device goes off and switch on again
public class BootReceiver extends BroadcastReceiver {
AlarmReceiver alarmReceiver = new AlarmReceiver();
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
alarmReceiver.setAlarm(context);
}
}
}
This is intent service class here you have to write your logic for your app.
public class AlarmService extends IntentService {
public AlarmService() {
super("AlarmService");
}
#Override
protected void onHandleIntent(Intent intent) {
//Write the logice here
AlarmReceiver.completeWakefulIntent(intent); // this tell if the related work is complete then system tracks for another alram.
}
Last you have to make changes in your manifest.
<service android:name="AlarmService" />
<receiver android:name="AlarmReceiver" />
<receiver android:name="BootReceiver" />
I hope this will help you atleast. P.s you don't have to post same question twice.

public void scheduleAlarm()
{
Calendar cal = Calendar.getInstance();
Log.d("logs", "This is running in the main act");
Intent intentAlarm = new Intent(this, affirmationSchedule.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal + 10000, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Has Been Scheduled", Toast.LENGTH_LONG).show();
}
Broadcast Receiver
public class affirmationSchedule extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("logs", "This function is running");
Toast.makeText(context, "this is a toast so this is working.", Toast.LENGTH_LONG).show();
}
}
In manifest
<receiver
android:name="com.wuno.affirmationSchedule"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.wuno.BroadcastReceiver" />
</intent-filter>
</receiver>

Related

AlarmManager getting killed with the app

I created an app to send message using alarm manager but if i put an alarm for a long duration the app is killed by android automatically, so i need to prevent the app from getting killed.Please tell me how can I do it.
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());
}
//System clock time
Calendar c = Calendar.getInstance();
Long a ;//=(long) (Calendar.getInstance().get(Calendar.SECOND) * 1000);
if(cal.get(Calendar.HOUR_OF_DAY) < c.get(Calendar.HOUR_OF_DAY))
h = (cal.get(Calendar.HOUR_OF_DAY) + 24 - c.get(Calendar.HOUR_OF_DAY)) * 60;
else
h = (cal.get(Calendar.HOUR_OF_DAY) - c.get(Calendar.HOUR_OF_DAY * 60;
m = (cal.get(Calendar.MINUTE) - c.get(Calendar.MINUTE));
a = (m + h) * 60;
myIntent = new Intent(this, MyReceiver.class);
myIntent.putExtra("pos", array.select);
//Pending Intent for sending the intent afterwards
pendingIntent[array.select] = PendingIntent.getBroadcast(this.getApplicationContext(), array.select, myIntent, 0);
alarmManager[array.select] = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
alarmManager[array.select].set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + a * 1000, pendingIntent[array.select]);
pendingarray.add(pendingIntent[array.select]);
sms_list.Phone[array.select] = Phone;
Intent back = new Intent(this, sms_list.class);
back.putExtra("PHONE", Phone);
back.putExtra("Flag",2);
back.putExtra("MSG", Message);
back.putExtra("HOUR", (int) cal.get(Calendar.HOUR_OF_DAY));
back.putExtra("MIN", (int) cal.get(Calendar.MINUTE));
back.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(back);
If the answer is wake lock can you please tell me where to use it.
You can use a service to do it, this will also work after the device is rebooted. You also have to make the service foreground to prevent the system from killing it. It can be done by adding an ongoing notification. See the service code below.
In your Manifest add the following
<receiver
android:name=".Autostart"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name=".StarterService"
android:enabled="true"
android:exported="true" />
Then create a new class as follows:
public class Autostart extends BroadcastReceiver {
/**
* Listens for Android's BOOT_COMPLETED broadcast and then executes
* the onReceive() method.
*/
#Override
public void onReceive(Context context, Intent arg1) {
Log.d("Autostart", "BOOT_COMPLETED broadcast received. Executing starter service.");
Intent intent = new Intent(context, StarterService.class);
context.startService(intent);
}
}
And finally your service as follows:
public class StarterService extends Service {
private static final String TAG = "MyService";
/**
* starts the AlarmManager.
*/
#Override
public void onCreate() {
super.onCreate();
//TODO: Start ongoing notification here to make service foreground
}
#Override
public void onStart(Intent intent, int startid) {
//TODO: Put your AlarmManager code here
//TODO: you also need to add some logic to check if some previous work is pending in case of a device reboot
Log.d(TAG, "onStart");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
//TODO: cancel the notification
Log.d(TAG, "onDestroy");
}
}
Now all you need to do is call the service whenever you need to send the message.
PS: I know an answer is accepted but hope this helps you or someone else.
An alarm should be triggered in a Broadcast Receiver.
If it performs long-lived operations, you should then use threads or Services. Both of them can be launched from a receiver.
EDIT
As a short example, I use this method in a button's onClickListener in the activity :
scheduleAlarm(name);
Method :
public void scheduleAlarm(String client)
{
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String delay = sharedPref.getString(SettingsActivity.PREF_DELIVERY_DELAY, "48");
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+ Integer.parseInt(delay) * 1000; //todo change seconds to hours
// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers and
//we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
intentAlarm.putExtra("CLIENT", client);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
//todo string res
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled in " + delay + " hours", Toast.LENGTH_LONG).show();
}
And finally, the AlarmReceiver.java
package com.patrickmiller.test2;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm received", Toast.LENGTH_SHORT).show();
String client = intent.getStringExtra("CLIENT");
Notify(context, client);
}
public void Notify(Context context, String client) {
//todo expanded layout with options Fiche de contact | Rapport and cover image
//todo send name, address, phone, email and id through Intent to ContactClientActivity
//todo delete notification when generated
try {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//todo set notification icon, content title and content text as string resources
.setSmallIcon(R.drawable.warning)
.setContentTitle(client)
.setContentText("N'oubliez pas de générer le rapport du client");
Intent resultIntent = new Intent(context, ContactClientActivity.class);
//todo may need to expend instead of calling activity. Buttons will do.
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
catch(Exception e) {
Toast.makeText(context, String.valueOf(e), Toast.LENGTH_LONG).show();
}
}
}
You don't have to care about the client's thing. Just the way I scheduled the alarm..
My operation is a short-lived one, which is sending a notification. If you plan a long-lived operation, you should start a service or a thread from the receiver (onReceive callback method).
ok, your app is finished because is running in the main thread, so you need to make this process in other thread that is not killed when the app is closed. check this documentation from the official page. if you decide start using asyncTask class check this reference

AlarmManager gets killed on app destroy

I have the following problem: I register my alarm manager in onCreate, It gets executed each minute now. However if i kill the app via the Android taskmanager (so the app state is destoyed) the AlarmReceiver stops excecuting. Why?
My Code:
AlarmReceiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
private AlarmManager mAlarm;
private PendingIntent mAlarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, PortalPullService.class);
startWakefulService(context, service);
}
public void setAlarm(Context context) {
mAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
mAlarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
int interval = context.getResources().getInteger(R.integer.update_interval_in_mins) * 60 * 1000;
mAlarm.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + interval,
interval,
mAlarmIntent);
ComponentName reciever = new ComponentName(context, AlarmBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(reciever,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public void cancelAlarm(Context context) {
if(mAlarm != null) {
mAlarm.cancel(mAlarmIntent);
}
ComponentName reciever = new ComponentName(context, AlarmBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(reciever,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
PullService
public class PortalPullService extends IntentService {
private static final String LOG_TAG = "PortalPullService";
public PortalPullService() {
super(LOG_TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
//TODO make request to ** check if new Infos are available, then send notification
Helper.sendNotification(this, "Test", "Testnotification"); //My test if this works
AlarmReceiver.completeWakefulIntent(intent);
}
}
AndroidManifest.xml
<receiver android:name=".PortalUpdate.AlarmReceiver" />
<service
android:name=".PortalUpdate.PortalPullService"
android:exported="false" />
The receiver gets registered via new AlarmReceiver().setAlarm(this);
I searched on sveral SO questions, but i can't find an answer... I don't know where is my fault...
Thanks in advance ;)
Okay it's a problem to install a debug version of your app on Huawei.
Because you can disable Background Services in Huawei, and Huawei doesn't recognize a debug version of your app as a proper app, it destroys all services maybe cause of security reasons ...
Installing it properly over Play Store helps!
Because the PendingIntent scheduled is a token associated with your app, and if the app is forcefully killed, stopped or hibernated, it will be removed by the system. You can set it up again in onResume or onCreate when the user starts your app again.

Upload Image from IntentService when the app is closed

I'm developing an app that synchronize your local date with the cloud. So I need to check automatically, each 10 minutes, my local data to get the new camera files to upload to the cloud.
So I have used an IntentService that works only when the app is running in foreground. If I close it, my service doesn't upload anything.And I WANT MY INTENTSERVICE WORKS IN BACKGROUND with the AlarmManager.
My IntentService is declared in Manifest.xml:
<!-- Uploader and Deleter Files Service -->
<service android:name=".receiver.UploadDeleteService" android:exported="false" />
<receiver
android:name=".receiver.AlarmReceiver"
android:process=":remote" >
</receiver>
My AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.codepath.example.servicesdemo.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, UploadDeleteService.class);
context.startService(i);
}
}
My ServiceInteractor where I instance my AlarmReceiver inside AlarmManager:
public class ServiceInteractorImpl implements ServiceInteractor {
private Context context;
public ServiceInteractorImpl(Context context){
this.context = context;
}
#Override
public void launchService() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(context, AlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, AlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 10);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.getTimeInMillis(), pIntent);
}
}
My UploadDeleteService where I call to the retrofit implementation module:
public class UploadDeleteService extends IntentService implements ApiConnector.GetObjectListener {
private RemoteInteractor remoteInteractor;
public UploadDeleteService(String name) {
super(name);
}
public UploadDeleteService() {
super("UpdateDeleteService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i("SERVICE", "Service running");
remoteInteractor = new RemoteInteractorImpl(getApplicationContext());
remoteInteractor.checkNews(this);
}
#Override
public void onImageUploaded(String type, JSONObject response) {
Log.d("SERVICE", " onImageUploaded ");
//REST OF THE STUFF....
}
}
Please I need a helping hand to solve that problem. I need it works each 10 minutes although the app is closed. Thanks!
For stopped Service:
change "cal.getTimeInMillis()" to "10*60*1000"
cal.add(Calendar.MINUTE, 10); //this will add 10 minute to current time
For Stopped open app when service start:
normally it will not open your app, you need to check what happened in RemoteInteractorImpl.class
you create new instance at onHandleIntent
remoteInteractor = new RemoteInteractorImpl(getApplicationContext());
remoteInteractor.checkNews(this);

Using Alarm Manager to execute a task once

I am trying to execute an action once at a later time using AlarmManager. I followed the code and the question here and came up with this.
public class EmailAccountUpdater extends BroadcastReceiver
{
// Constructors
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION))
{
Log.v("Test", " Step 1 - Creating the alarm " );
// Place holder
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent newIntent = new Intent("com.test.EMAIL_ACCOUNTS_CHANGED");
PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, newIntent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.set( AlarmManager.RTC_WAKEUP, 35000, pendingIntent);
}
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver
{
// constructors
#Override
public void onReceive(Context context, Intent intent)
{
Log.v("Test","Step 2 - Alarm received");
if (intent.getAction().equals("com.test.EMAIL_ACCOUNTS_CHANGED"))
{
onAccountsUpdated();
}
}
public void onAccountsUpdated()
{
// do something
}
}
In the manifestManifest.xml
<receiver android:name="full.path.AlarmReceiver">
<intent-filter>
<action android:name="com.test.EMAIL_ACCOUNTS_CHANGED"/>
</intent-filter>
</receiver>
Basically what I wanted to do was to put the following in Placeholder (just below the first log statement).
Thread.sleep(35000);
onAccountsUpdated();
But according to this, it is not suggestible to use postDelayed and Thread.sleep in BroadcastReceiver. So I came up with this. What happens is I always get the Step 1 but never reach the step 2. What I am I doing wrong? Any help would be welcome.
The solution is (as per the thread you linked):
you want something to happen some time after the broadcast you can start a service, and that service wait the amount of time, or if the amount of time you want to wait is longer than a few seconds, you should just put the launch of this service in the AlarmManager and let the AlarmManager launch the service for you.
Your plan doesn't work because the context is destroyed after EmailAccountUpdater.onReceive returns.

How to Autostart an AlarmManager to start a Scheduled Activity?

This tutorial come from android-er,
The main activity(AndroidScheduledActivity.java) start a AlarmManager to trigger BroadcastReceiver(MyScheduledReceiver.java) repeatly. In the onReceive() method of MyScheduledReceiver, it start another activity(MyScheduledActivity.java) indirectly. Such that the activity(MyScheduledActivity.java) will be start in scheduled interval.
Now I would use AutoStart to start automatically, but I was not able to write the AutoStartNotifyReceiver .
please can you give me an idea how to manage it ?
Thanks a LOT !
main activity, AndroidScheduledActivity.java :
public class AndroidScheduledActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.start);
buttonStart.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(getBaseContext(),
MyScheduledReceiver.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(getBaseContext(),
0, myIntent, 0);
AlarmManager alarmManager
= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
finish();
}});
}
}
Then BroadcastReceiver, MyScheduledReceiver.java
public class MyScheduledReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
and my problem AutoStartNotifyReceiver :
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
????????????????????
}
}
}
Your AutoStartNotifyReceiver extends BroadcastReceiver class is there because the alarms get cleared when the device resets. So, in the onReceive of this class (where you have the question marks) you need to set the alarm all over again with the same code (without, of course the finish())that you used to do it the first time in the onClick method of AndroidScheduledActivity.
Then, you need to put the following entry in your Manifest to let the system know to launch your AutoStartNotifyReceiver when the system boots up:
<receiver android:name=".AutoStartNotifyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
As well as a permission in the Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Now, this is all assuming you only have one alarm and only set it one way every time. If that is not the case than this gets a bit more complicated. But based on the little info you provided, my solution should do what you want.
Also, since you are a newcomer here just a kindly reminder: when someone provides an adequate answer to a question, the person asking the question (you) accepts the answer by clicking the checkbox next to the answer. This is so the person answering gets credit. Welcome to SO!
thanks, it works. just need to improve my java a little more. I have to add "context" don t know exactly why.
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
Intent myIntent = new Intent(context, MyScheduledReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pendingIntent);
}
}
}

Categories

Resources