Bring Android app to foreground when device is sleeping - android

I successfully used the AlarmManager to set an alarm in the future and I was able to have a BroadcastReceiver getting called at alarm time. I read that you can use the PowerManager to turn device on in case it went to sleep and use the KeyguardManager to unlock the device.
But I also need to start my app or bring it into foreground. Will this be done automatically? I can not find a hint to this in the Internet.

You can do this by sending a startActivity in your broadcast receiver with your main activity as the intent.

Got it :)
//The Main Activity
public class FullscreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
Context context=this;
Alarm alarm = new Alarm();
public void onDummyButton(View view) {
alarm.SetAlarm(this);
}
}
//The Alarm Receiver
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.util.Calendar;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Log.d("Alarm", "onReceive");
// Put here YOUR code.
// Start the MainActivity
Intent i = new Intent(context, FullscreenActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
}
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);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() + 1000 * 15);
//calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
//calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+1);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
Toast.makeText(context, "Alarm scheduled for: " + calendar.get(Calendar.HOUR_OF_DAY)+':'+calendar.get(Calendar.MINUTE)+':'+calendar.get(Calendar.SECOND), Toast.LENGTH_LONG).show();
}
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);
}

Related

Unable to display Alarm messge when alarm is set

public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleAlarm(View V){
//Long time= new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
Long time= new GregorianCalendar().getTimeInMillis()+30*1000;
Intent intentAlarm= new Intent(this, AlarmReceiver.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 Scheduled for 30 repetd", Toast.LENGTH_LONG).show();
}
}
AlarmReceiverClass
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG);
}
}
This is my code i am trying to set alarm and display alarm message in each 30 second But i am unable to display Alarm messes in toast while i write code all the thing correct but i don't know where am doing mistake please look my code and please suggest me where am doing wrong .
First of all please add .show() in toast.
i.e. Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
EDIT
Please use the below code :
in manifest
<receiver android:name=".alarm.manager.Alarm" >
</receiver>
create a new class named AlarmService.java
public class AlarmService extends Service {
Alarm alarm = new Alarm();
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarm.SetAlarm(AlarmService.this);
return START_STICKY;
}
public void onStart(Context context, Intent intent, int startId) {
alarm.SetAlarm(context);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Another class alarm.java
package alarm.manager;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;
public class Alarm extends BroadcastReceiver {
public static final String ALARM_SERVICE = "alarm";
public Alarm() {
}
Context mContext;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressLint("NewApi")
#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();
mContext = context;
Log.d("App", "Alarm manager invoked");
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, pi);
}
/**
* Stop alarm
*
* #param context
* = context of activity
*/
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);
}
}
from your class call these lines
Alarm alarm = new Alarm();
alarm.SetAlarm(getApplicationContext());
You just missed to call .show() method for Toast. So it will be
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();

AlarmManager wont fire pending intent

I try to use AlarmManager with BroadcastReceiver.
My problem is that I dont get the intent fire from the AlarmManager.
Im not getting any call from Log.i("test", "test")
Here is my code:
public void activityCheck()
{
Intent intent = new Intent(this.getApplicationContext(), com.example.workoutlog.UsageCheckService.class);
intent.putExtra("nofitication", "nofitication");
PendingIntent service = PendingIntent.getService(this, 0, intent, 0);
AlarmManager m = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
Log.i("Yo", "Yo");
m.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), 1000*60, service);
}
My BroadcastReceiver class
public class UsageCheckService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("test", "test");
}
}
In my manifest
<receiver android:name="com.example.workoutlog.UsageCheckService" >
</receiver>
If the phone is in sleep state, you will have to wake it up.
Try this:
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);
}
}
}
If you device is in "sleep mode" (battery save), the Broadcast will not wake up it.
You must use WakefulBroadcastReceiver
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

Alarm Manager shows notification everytime

I have made an android application that displays a notification message at a particular time (say 6:15:00 pm) of the day. I have used the Calendar along with AlarmManager class for this purpose.
However, when I installed the app on my phone to test it, it showed me the message/notification at the specified time but continues to show the same at any time..I mean the notification keeps on coming throughout the day in my phone even though I have set the time for it in my app.
Here is my code
1) Activity class
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity
{
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 6);
calendar.set(Calendar.YEAR, 2013);
calendar.set(Calendar.DAY_OF_MONTH, 13);
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 48);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} //end onCreate
}
2) Receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
3) Service class
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
I have added both service and receiver in manifest.xml file. Please can anyone tell me what should I do to display the notification only once during the entire day?
I guess the reason was the onCreate method was called multiple times and so your alarmManager.set was called multiple times. For example, whenever the screen orientation is changed, that activity is destroyed and a new activity starts by onCreate() method. So every time you rotate the screen that activity will be destroyed and a new activity starts by onCreate() method and alarmManager.set was called again.
You may save a state member in onSaveInstanceState(Bundle bundle) method. Android calls this method whenever the screen is rotated, and that given bundle bundle would be passed to oncreate(Bundle bundle). In your onCreate, check the Bundle is null before try to call alarmManager.set.
I did not ever use BroadcastReceiver like
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
So I doubt whether the usage of BroadcastReceiver is wrong, usually we use BroadcastReceiver as below:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="mypackage.START_ALARM" ></action>
</intent-filter>
</receiver>
Intent i = new Intent("mypackage.START_ALARM");
try this its working fine for me :
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 54);
cal.set(Calendar.SECOND, 0);
ca.set(Calendar.MILLISECOND, 0);
Intent intent = new Intent(getBaseContext(), Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getBaseContext(), 1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);

Start Broadcast Receiver from within Activity

I have read most posts re this issue, but still can't get my implementation working, can you please help?
Basically I want to initiate a BroadcastReceiver from within an Activity, to do something every 10 seconds. So I set the Alarm, but the code never actually reaches "onReceive()"... I can't spot any difference in my code from other examples, could you please take a look?
Also just to mention that I haven't put a receiver in the manifest file, as I understand that it is not needed since I register it within the activity.
Thank you!
package alarm.in;
import alarm.in.activity.R;
import android.app.Activity;
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 android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class activityActivity extends Activity {
private Alarm alarm;
private static final String TAG = "AlarmInActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarm = new Alarm();
}
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(ALARM_SERVICE);
registerReceiver(alarm, filter);
}
public void onPause() {
super.onPause();
this.unregisterReceiver(alarm);
}
public void setAlarm(View view){
alarm.SetAlarm(getBaseContext(),1,10);
}
public void cancelAlarm(View view){
alarm.CancelAlarm(getBaseContext());
}
private 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();
Log.d(TAG, "Alarm Worked!");
wl.release();
}
public void SetAlarm(Context context, int minutes, int seconds)
{
AlarmManager am=(AlarmManager)context.getSystemService(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 * seconds * minutes, pi); // Millisec * Second * Minute
Log.d(TAG, "AlarmSet");
}
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(ALARM_SERVICE);
alarmManager.cancel(sender);
Log.d(TAG, "AlarmCancel");
}
}
}
You registered your receiver, but forgot to send the action to the receiver:
Intent intent = new Intent(ALARM_SERVICE);
sendBroadcast(intent);

Develop Alarm Application

I'd like develop an Alarm Application.
The application should work like this:
launch it
the activity show me the time
I can set the alarm
I can close the application
when the alarm time comes , it starts an activity (even if the device is locked)
I have tried to adapt this sample https://github.com/commonsguy/cwac-wakeful but I cannot launch an activity when the alarm time comes.
I use this code to setup the alarm (for test I have inserted this code on an onCreate method of activity):
Intent intent = new Intent(this, OnAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
this is the OnAlarmReceiver class:
public class OnAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(ClockActivity.LOG_TAG, "OnAlarmReceiver::onReceive");
WakefulIntentService.sendWakefulWork(context, AlarmService.class);
}
}
this is the service class:
public class AlarmService extends WakefulIntentService {
public AlarmService(String name) {
super(name);
}
#Override
protected void doWakefulWork(Intent intent) {
Log.i(ClockActivity.LOG_TAG, "AlarmService::doWakefulWork");
Intent newIntent = new Intent(getApplicationContext(), ClockActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.setAction(ClockActivity.ALARM_ACTION);
getApplicationContext().startActivity(newIntent);
}
}
this is the portion of Manifest where are setup the service and the receiver:
<receiver android:name=".OnAlarmReceiver"></receiver>
<service android:name=".AlarmService"></service>
the doWakefulWork method is never called!
I have made this application:
AlarmActivity.java
package com.foo;
import pack.breceiver.MyBroadcastReceiver;
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.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.os.Bundle;
public class AlarmActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startAlert(View view) {
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package pack.breceiver;
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, "Don't panik but your time is up!!!!",
Toast.LENGTH_LONG).show();
/*// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000); */
}
}
check this out : http://blog.nelsondev.net/?p=124
using"alarmmanager"
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
AlarmCal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingAlarmIntent);
I had a similar problem and I resolved removing the receiver from manifest and set in my code registering him with registerReceiver.
Do you get an instantiation exception maybe ?
You should have a public no arg constructor in your service :
public class AlarmService extends WakefulIntentService {
public AlarmService() {
super("AlarmService");
}
// etc
}

Categories

Resources