alarmManager.setInexactRepeating does not working exactly on time - android

I want to repeat some sort of code on a particular time only i.e at xx:02,xx:17,xx:32,xx:47
i tried using AlarmManager class that brodcast a pending intent.
My problem is that- the following code runs fine on HTC desire 816 and Samsung Galaxy Grand neo but not Gionee M2.
MainActivity.java
package com.example.alarmexample;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int newmin=0;
SimpleDateFormat f= new SimpleDateFormat("dd-MM-yy HH:mm");
long current= System.currentTimeMillis();
String d= f.format(current);
String time[]=d.split(":");
int min = Integer.parseInt(time[1]);
if(min>=0 && min<=2)
{
newmin=2-min;
}
else if(min<=17)
{
newmin=17-min;
}
else if( min<=32)
{
newmin=32-min;
}
else if(min<=47)
{
newmin=47-min;
}
else
{
newmin=62-min;
}
long newtime= current+(newmin * 60 * 1000);
Intent intent = new Intent(this,MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, newtime, 15*60*1000 , pendingIntent);
Toast.makeText(this, "Alarm set in " + newmin + " miniuts",
Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
Output on HTC desire 816 and Samsung Galaxy Grand Neo is-
Time | result
xx:02 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:17 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:32 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:47 | toast showing message "Time is up!!!!." with 2 Second vibration
But on Gionee M2 -
Time | result
xx:00 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:02 | nothing happens
xx:17 | nothing happens
xx:20 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:32 | nothing happens
xx:40 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:47 | nothing happens
Why the behavior is different when have a same peace of code..
Is am doing something wrong? or anything else..
please tell me, thanks in advance.

Use setExact(int, long, PendingIntent) if you want to have the alarm fired exactly at specified interval.
The cause of your trouble is that you are using a API call to the AlarmManager that is defined as inexact. If you look at the documentation for setInexactRepeating(int, long, long, PendingIntent) you will find this passage.
Your alarm's first trigger will not be before the requested time, but
it might not occur for almost a full interval after that time. In
addition, while the overall period of the repeating alarm will be as
requested, the time between any two successive firings of the alarm
may vary. If your application demands very low jitter, use one-shot
alarms with an appropriate window instead; see setWindow(int, long,
long, PendingIntent) and setExact(int, long, PendingIntent).

Related

Schedule an alarm on device reboot automatically in android

I am trying to build an application which checks for notification files on a server, every hour. I used the alarm manager class to implement this. But I am unable to implement the automatic start on reboot part. I want that the alarm should run periodically after reboot. Can some one please tell me how to go about doing it.
This is my MyAlarmReceiver Class.
package com.example.quickstart;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.example.quickstart.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, NotificationService.class);
// i.putExtra("username", username);
context.startService(i);
}
}
This is my NotificationBootReceiver Class.
package com.example.quickstart;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class NotificationBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Construct an intent that will execute the AlarmReceiver
Intent i = new Intent(context, MyAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every every half hour from this point onwards
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
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
2*60*60,pIntent);
// alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
// AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
}
}
AndroidManifest file looks like this(it's not the complete manifest file but the relevant parts)
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".NotificationBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
The notifications are working fine, but what I want is the start notifications automatically on reboot feature. When i reboot the notification feature does not work,i.e, the alarm does not go off. And also the android documentation says (this only works if the app has already been launched by the user at least once) , is there a way to set the alarm automatically on reboot without launching the app. Any help appreciated. Thanks in advance
Documentation link android devs link
(Go to: Start an alarm when the device restarts)
No it isn't possible to set the alarms without starting the app even once. Once the app has been started the alarms can be triggered.

How can I do something after Elapsed Time in Android?

I am new in programming.
I want to turn off wifi after 2h (I know how to turn it off) in the background
I googled and found out, that the Elapsed Real Timer is needed for that. I have also find this code and implemented it (this is the only code I have in my class) This class is called when the user selects something from a spinner dropdown:
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Toast;
/**
* Wird aufgerufen, wenn eine Zeit von der dropdown liste gewählt wurde
*/
public class ElapsedRealtimeAlarm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, ElapsedRealtimeAlarm.class), 0);
long firstTime = SystemClock.elapsedRealtime(); // elapsedRealTime --> Zeit seitdem booten.
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime, 1*1000*3600*2, mAlarmSender); // 1*1000 --> 1s * 3600 --> 1h * 2 --> 2h
Toast.makeText(getApplicationContext(), "Das ist ein Text", Toast.LENGTH_SHORT).show();
}
}
Is the code until yet fine? And how can I turn wifi off after the elapsed timer?
And does this the elapsed timer only one time or is this like an interval?
Sorry for my english
Thanks
EDIT:
I did the steps, mentioned in the answer of "Deb" and it is still nothing happening
Here the code
Step 1: "Make a BroadcatReceiver extending WakefulBroadcastReceiver"
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.widget.Toast;
public class BroadCastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
new BackgroundService(); // Step 4
}
}
Step 2: Make a service extending IntentService Class
Step 3: In your service inside onHandleIntent() write your code for switching the wifi off or on.
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.view.View;
import android.widget.Toast;
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
} else {
wifiManager.setWifiEnabled(true);
}
}
Step 4: Now go back to your BroadcastReceiver class and there inside onReceive() call your service that you made in step 2 (the code is already in step 1)
Manifest file (receiver, service and permissions for wifi)
<manifest ..... ..... ....>
<application>
.....
<receiver android:name=".BroadCastReceiver" ></receiver>
<service android:name=".BackgroundService" android:exported="false"></service>
</application>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
</manifest>
EDIT 2
The class where I am executing startActivity(new Intent(SpinnerTimeOnItemSelectedListener.this, ElapsedRealtimeAlarm.class));
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
public class SpinnerTimeOnItemSelectedListener extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).toString().equals("Zeit auswählen") || parent.getItemAtPosition(position).toString().equals("Select Time")){
//onNothingSelected(parent);
;
} else if (parent.getItemAtPosition(position).toString().equals("30min")){
startActivity(new Intent(SpinnerTimeOnItemSelectedListener.this, ElapsedRealtimeAlarm.class));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Wenn es einen ElapsedRealTimeAlarm gibt, soll er gecancelt werden
// Ansonsten nichts
;
}
}
ElapsedRealtimeAlarm's onCreate()
public class ElapsedRealtimeAlarm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Toast.makeText(getBaseContext(), "ElapsedRealTimeAlarm wurde aufgerufen", Toast.LENGTH_SHORT).show(); // just to check, that he called this class
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, BroadCastReceiver.class), 0);
long firstTime = SystemClock.elapsedRealtime(); // elapsedRealTime --> Zeit seitdem booten.
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime+2000, 10, mAlarmSender);
}
}
Make a BroadcatReceiver extending WakefulBroadcastReceiver .
Make a service extending IntentService Class.
In your service inside onHandleIntent() write your code for switching the wifi off or on.
Now go back to your BroadcastReceiver class and there inside onReceive() call your service that you made in step 2.
Your line of code
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime, 1*1000*3600*2, mAlarmSender);
This is responsible for running an alarmmanager repeatedly after every 2hrs.But if u want the alarm manager to run only once replace am.setRepeating() with am.set().
Your Code
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, ElapsedRealtimeAlarm.class), 0);
Replace PendingIntent.getService with the PendingIntent.getBroadcast and pass the reference of your BroadcastReceiver class you made in step 1
NOTE :Do not forget to write the receiver and service in your manifest otherwise it won't work
Update:
Inside your BroadcastReceiver's onReceive() call the service like this
Intent service=new Intent(context,BackgroundService.class);
startWakefulService(context, service);
this will call the onHandleIntent().
Update 2:
Replace getBaseContext() with this and change the PendingIntent.getService as
Intent i=new Intent(this, BroadCastReceiver.class);
PendingIntent alarmIntent=PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Do the following it will usefull to you
Create a service that turn wifi & other operations
Create a broadcast receiver inside that onReceive method call the service
Create a pending intent and alarm for a time which you want ,when alarm time period eleapses then trigger the broadcast receiver.

How to use Elapsed Real Time in Android?

I want to develop an app. The app has a spinner dropdown. The dropdown has 3 option (30min, 1h, 2h). When for example 30min is pressed I want to start an elapsed Real Time for 30min and after that I want to turn off wifi, that means after 30min the wifi should be turned off.
The logcat shows me a NullPointer Exception.
Here is my code
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
public class SpinnerTimeOnItemSelectedListener extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
if(parent.getItemAtPosition(position).toString().equals("Zeit auswählen") || parent.getItemAtPosition(position).toString().equals("Select Time")){
onNothingSelected(parent);
} else if (parent.getItemAtPosition(position).toString().equals("30min")){
Intent intent = new Intent(SpinnerTimeOnItemSelectedListener.this, ConnectionManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(SpinnerTimeOnItemSelectedListener.this, 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, 5000, pendingIntent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Wenn es einen ElapsedRealTimeAlarm gibt, soll er gecancelt werden
// Ansonsten nichts
;
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
And in this class the wifi should be managed (turned on/off)
public class ConnectionManager extends BroadcastReceiver {
/**
*
* #param context The Context in which the receiver is running.
* #param intent The Intent being received.
*/
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
Error of the logcat:
07-24 17:35:17.503 5430-5430/com.falkenherz.abusufean.batterycooler E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.falkenherz.abusufean.batterycooler, PID: 5430
java.lang.NullPointerException
at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:104)
at android.app.PendingIntent.getService(PendingIntent.java:522)
at com.example.ali.turnoffwifi.SpinnerTimeOnItemSelectedListener.onItemSelected(SpinnerTimeOnItemSelectedListener.java:42)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:956)
at android.widget.AdapterView.access$200(AdapterView.java:49)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:920)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
The error is on this line:
PendingIntent pendingIntent = PendingIntent.getBroadcast(SpinnerTimeOnItemSelectedListener.this, 0, intent, 0);
How can I fix this problem?
Thanks
Here is little bit concept problem:
elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
check : http://developer.android.com/reference/android/os/SystemClock.html
and here your task you can done with the Chronometer class. You can bind it to SystemClock.elapsedRealtime() using setBase(). Another way could be if you use Handler inside an Activity and using the sendEmptyMessageDelayed() method with value 1000*60*30(30 minutes) to update your timer.
Or if you Want to use pending intent Then you have to
1)getcurrenttime in Millis using calenderinstance
2)convert 30 minutes to millis and
3) Total millis =currenttimeinmillis+30minutes in millis
then set your Total millis to alarm manager object
also check :android service using SystemClock.elapsedRealTime() instead of SystemClock.uptimeMillis() works in emulator but not in samsung captivate?
Thats it....

launch activity from service when notification is clicked

I know, there are tons of these on here, but I've been trying solutions all day and haven't gotten anywhere.
Neither the example on google's docs, nor any of the 5 other ways I've found on here have worked for me at all.
As is the typical case, when I click the notification it closes the status bar and nothing new is shown onscreen.
I am creating the notification from a service and need the notification to trigger a new activity that has not yet been created.
I also will need a way to pass information to that activity via intent.
And yes... this is java for Android
What follows are the shattered remnants of my code.
package com.bobbb.hwk2;
import java.io.FileOutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.widget.Toast;
public class contactBackup extends Service
{
private NotificationManager nManager;
private static final int NOTIFY_ID = 1100;
#Override
public void onCreate()
{
super.onCreate();
String ns = Context.NOTIFICATION_SERVICE;
nManager = (NotificationManager)getSystemService(ns);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// inform user that service has started
Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show();
String data = lookUpContacts();
if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) )
{
Context context = getApplicationContext();
// create the statusbar notification
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
//nIntent.putExtra("data",data);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
}
}
#Override
public void onDestroy()
{
nManager.cancel(NOTIFY_ID);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
// function returns string containing information
// from contacts
public String lookUpContacts()
{
...
}
public boolean saveToSDCard(String fileName, String data)
{
...
}
}
I can only hope that whatever is causing my problem is something fixable and not more of the crazy glitches I've been getting with eclipse (which no one else seems to have ever seen >:U )
If you can help me solve this problem, please share.
If you can't help with this specific problem but feel obligated to say unrelated things about posting, styles, topics, or good practice, then DON'T
Thank you :D
Edit:
You're going to have to add a flag for FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is because you're launching from outside your app (from the system notification bar).
This is what happens when people overwork themselves. XD
The only reason none of the tutorials I tired worked is because I misspelled my activity name in the manifest.
Thanks for stopping by
Just add following in contactBackup(service class),
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
nIntent.putExtra("data",data);
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
then get value in contactViewer class,
as,
String s=getIntent().getStringExtra("data");

Start app at a specific time

I was wondering if it's possible (and if it is how) to start up my app at a specific time, something like an alarmclock which goes off at a specific time.
Let's say I want my app to start up at 8 in the morning, is that feasable ?
You can do it with AlarmManager, heres a short example. First you need to set the alarm:
AlarmManager am = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
Date futureDate = new Date(new Date().getTime() + 86400000);
futureDate.setHours(8);
futureDate.setMinutes(0);
futureDate.setSeconds(0);
Intent intent = new Intent(con, MyAppReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, futureDate.getTimeInMillis(), sender);
Next, You need to create a reciever with some code to execute your application: (ie- starting your app):
public class MyAppReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startActivity(new Intent(context, MyAppMainActivity.class));
}
}
You are probably looking for AlarmManager, which let's you start services / activities / send broadcasts at specific intervals or a given time, repeating or not. This is how you write memory friendly background services in android. AlarmManager is sort of like cron in unix. It allows your background service to start, do its work, and get out of memory.
You probably do not want to start an activity (if that's what you meant by "application"). If you want to alert the user that something has happened, add an alarm that starts a receiver at a given time, and have the receiver add a notification. The notification can open the application when clicked. That's less invasive than bringing some potentially unwanted activity to the foreground.
there is a very good tutorial: http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html
here is the c&p:
Android AlarmManager tutorial
by Rakesh Cusat on September 20th, 2012 | Filed in: Android Core
While writing an application, need arises to schedule execution of code in future. You may require AlarmManager to schedule your work at a specified time. AlarmManager accesses to system alarm and schedules the execution of code even when the application is not running.
Project Information: Meta-information about the project. Platform Version : Android API Level 10.
IDE : Eclipse Helios Service Release 2
Emulator: Android 4.1
Prerequisite: Preliminary knowledge of Android application framework, and Intent Broadcast receiver.
AlarmManager:
AlarmManager has access to the system alarm services. With the help of AlarmManager you can schedule execution of code in future. AlarmManager object can’t instantiate directly however it can be retrieved by calling Context.getSystemService(Context.ALARM_SERVICE). AlarmManager is always registered with intent. When an alarm goes off, the Intent which has been registered with AlarmManager, is broadcasted by the system automatically. This intent starts the target application if it is not running. It is recommended to use AlarmManager when you want your application code to be run at a specific time, even if your application is not currently running. For other timing operation handler should be used because it is easy to use. Handler is covered in other tutorial.
Method Description
set() Schedules an alarm for one time.
setInexactRepeating() Schedules an alarm with inexact repeating. Trigger time doesn’t follow any strict restriction.
setRepeating() Schedules an alarm with exact repeating time.
setTime() Sets the system’s wall clock time.
setTimeZone() Sets the system’s default time zone.
Check out the AlarmManager documention for more info.
In this tutorial let’s learn to create one-time timer and the repeating timer, and also to cancel the repeating timer. Here timer and alarm have been used interchangeably, but in this tutorial context both of them have the same meaning.
Example Code:
Let’s create three buttons start repeating timer, cancel repeating timer and one-time timer in the layout file. These buttons are attached with methods i.e startRepeatingTimer, cancelRepeatingTimer and onetimeTimer respecitively. These methods will be defined in the Activity class. The layout file is shown below(activity_alarm_manager.xml).
<linearlayout android:layout_height='match_parent'
android:layout_width='match_parent' android:orientation='vertical'
xmlns:android='http://schemas.android.com/apk/res/android'
xmlns:tools='http://schemas.android.com/tools'>
<button android:id='#+id/btStart' android:layout_height='wrap_content'
android:layout_width='match_parent' android:onclick='startRepeatingTimer'
android:padding='#dimen/padding_medium' android:text='#string/btStart'
tools:context='.WidgetAlarmManagerActivity'/>
<button android:id='#+id/btCancel' android:layout_height='wrap_content'
android:layout_width='match_parent' android:onclick='cancelRepeatingTimer'
android:padding='#dimen/padding_medium' android:text='#string/btCancel'
tools:context='.WidgetAlarmManagerActivity'/>
<button android:id='#+id/btOneTime' android:layout_height='wrap_content'
android:layout_width='match_parent' android:onclick='onetimeTimer'
android:padding='#dimen/padding_medium' android:text='#string/btOneTime'
tools:context='.WidgetAlarmManagerActivity'/>
</linearlayout>
We are going to define the BroadcastReciever which handles the intent registered with AlarmManager. In the given class onReceive() method has been defined. This method gets invoked as soon as intent is received. Once we receive the intent we try to get the extra parameter associated with this intent. This extra parameter is user-defined i.e ONE_TIME, basically indicates whether this intent was associated with one-time timer or the repeating one. Once the ONE_TIME parameter value has been extracted, Toast message is displayed accordingly. Helper methods have also been defined, which can be used from other places with the help of objects i.e setAlarm(), cancelAlarm() and onetimeTimer() methods. These methods can also be defined somewhere else to do operation on the timer i.e set, cancel, etc. To keep this tutorial simple, we have defined it in BroadcastReceiver.
setAlarm(): This method sets the repeating alarm by use of setRepeating() method. setRepeating() method needs four arguments:
type of alarm,
trigger time: set it to the current time
interval in milliseconds: in this example we are passing 5 seconds ( 1000 * 5 milliseconds)
pending intent: It will get registered with this alarm. When the alarm gets triggered the pendingIntent will be broadcasted.
cancelAlarm(): This method cancels the previously registered alarm by calling cancel() method. cancel() method takes pendingIntent as an argument. The pendingIntent should be matching one, only then the cancel() method can remove the alarm from the system.
onetimeTimer(): This method creates an one-time alarm. This can be achieved by calling set() method. set() method takes three arguments:
type of alarm
trigger time
pending intent
package com.rakesh.alarmmanagerexample;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = 'onetime';
#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, 'YOUR TAG');
//Acquire the lock
wl.acquire();
//You can do the processing here.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
//Make sure this intent has been sent by the one-time timer button.
msgStr.append('One time Timer : ');
}
Format formatter = new SimpleDateFormat('hh:mm:ss a');
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 5 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Given below is the manifest file. Here, WAKE_LOCK permission is required because the wake lock is being used while processing in onReceive() method present in AlarmManagerBroadcastReceiver class. AlarmManagerBroadcastReceiver has been registered as broadcast receiver.
<manifest android:versioncode='1' android:versionname='1.0'
package='com.rakesh.alarmmanagerexample'
xmlns:android='http://schemas.android.com/apk/res/android'>
<uses-sdk android:minsdkversion='10' android:targetsdkversion='15'/>
<uses-permission android:name='android.permission.WAKE_LOCK'/>
<application android:icon='#drawable/ic_launcher'
android:label='#string/app_name' android:theme='#style/AppTheme'>
<activity android:label='#string/title_activity_alarm_manager'
android:name='com.rakesh.alarmmanagerexample.AlarmManagerActivity'>
<intent-filter>
<action android:name='android.intent.action.MAIN'/>
<category android:name='android.intent.category.LAUNCHER' />
</intent-filter>
</activity>
<receiver android:name='com.rakesh.alarmmanagerexample.AlarmManagerBroadcastReceiver'>
</receiver>
</application>
</manifest>
Now let’s define the activity class which defines some methods. These methods are going to handle the button clicks. Here in this class we create an instance of AlarmManagerBroadcastReciever which will help us to access setAlarm(), cancelAlarm() and setOnetime(). Rest of the code is easy to understand.
package com.rakesh.alarmmanagerexample;
import com.rakesh.alarmmanagerexample.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class AlarmManagerActivity extends Activity {
private AlarmManagerBroadcastReceiver alarm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager);
alarm = new AlarmManagerBroadcastReceiver();
}
#Override
protected void onStart() {
super.onStart();
}
public void startRepeatingTimer(View view) {
Context context = this.getApplicationContext();
if(alarm != null){
alarm.SetAlarm(context);
}else{
Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
}
}
public void cancelRepeatingTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.CancelAlarm(context);
}else{
Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
}
}
public void onetimeTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.setOnetimeTimer(context);
}else{
Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_widget_alarm_manager, menu);
return true;
}
}
Once you are done with the coding, just execute the project and you will find the similar kind of application running in your emulator.
Please download https://github.com/rakeshcusat/Code4Reference/tree/master/AndroidProjects/AlarmManagerExamplecode, if you need reference code.
Reference: Tutorial on Android AlarmManager from our JCG partner Rakesh Cusat at the Code4Reference blog.
http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/

Categories

Resources