I have two issues of Alarm manager. One is i want to repeat alarm every 10 seconds and other is my Broadcast Receiver is invoking after 10 second.
When i use Activity instead of Broadcast Receiver it is working But Broadcast Receiver is not working. And time is not proper some time it works in 1 min and some times it works i 50 Seconds. But i need every 10 Second.
My code is:
buttonStart.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
long tenMin = 1000/5 ;//here is 30 seconds
Intent intent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,
0, intent, 0);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tenMin, pendingIntent);
}});
BoradcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
}
}
Manifest file:
<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>
<service android:name=".MyAlarmService" />
<receiver
android:name=".MyBroadcastReceiver"
android:process=":remote"></receiver>
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
Use:
Activity:
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,0, intent, 0);
10sec repeating interval,
repeatingInterval = 10 *1000; //interval in milli seconds for 10sec
AlarmManager alarmManager =(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
alarmManager .setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), repeatingInterval , pendingIntent);
It should work.
Related
I'm having a requirement where i need to open an activity at specific time and perform specific task even when the app is killed. That is even when the app is removed from multi-task window pane.
As of now i'm using the alarm manager to achieve this task as shown below.
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();
The onReceive method is as below:
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
The problem is, it opens up the activity when the app is in background. Not when in closed or not in the back stack(mutli-task pane).
Please lighten me up. I'm struggling.
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidScheduledActivity"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidScheduledActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MyScheduledActivity" />
<receiver android:process=":remote"
android:name="MyScheduledReceiver" />
</application>
</manifest>
start a service and your alarm code in that.Once the alarm is done start your application through notification or as per your logic.
You should use Service, Open your activity through service. Service
I am almost done, but when clicking the set Alarm button to fire the notification after 5 seconds for example, nothing happens.
this is the OnClick method for SetAlarm
public void setAlarm(View view) {
long alertTime = new GregorianCalendar().getTimeInMillis()+5*1000;
Intent alertIntent = new Intent(this, AlertReceiver.class);
//schedule to happen at later date
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
and this is my receiver:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "Times up", "5 seconds has passed", "Alert");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert) {
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.not)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
//intent to fire when notification clicked on
mBuilder.setContentIntent(notificIntent);
//how the person will be notified
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
//cancel notification when clicked in the taskbar
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager= (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1,mBuilder.build());
}
and this is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yahyazeid.testnotification" >
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service android:name=".AlertReceiver">
<intent-filter> <action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</service>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<activity android:name=".MoreInfoNotification"
android:label="More on notification"
android:parentActivityName=".MainActivity">
</activity>
</application>
</manifest>
Any suggestions?
The corrected manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yahyazeid.testnotification" >
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<activity android:name=".MoreInfoNotification"
android:label="More on notification"
android:parentActivityName=".MainActivity">
</activity>
<service android:name=".AlertReceiver">
</service>
</application>
</manifest>
Try this code. It looks like you did not set the notification in your receiver.
public void scheduleAlarm(View V)
{
// 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()+5*1000;
// 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
Intent intentAlarm = new Intent(this, AlarmReciever.class);
//Get the Alarm Service
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Set for 5 seconds", Toast.LENGTH_LONG).show();
Then for the Receiver
public class Receiver extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.depressiontest)
.setContentTitle("Time has Expired")
.setContentText("5 Seconds has passed.")
.setVibrate(pattern)
.setAutoCancel(true);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
And then in your manifest
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service android:name=".Receiver">
<intent-filter> <action android:name="NOTIFICATION_SERVICE" />
</intent- filter>
</service>
For setting a specific date using the get Calendar instance
Calendar cal = Calendar.getInstance();
//Setting date for 11/29/2016
cal.set(Calendar.DATE,29); //1-31 days of week
cal.set(Calendar.MONTH,10); //January starts at 0 (zero), December = 11
cal.set(Calendar.YEAR,2016);//year...
//Setting the specific hour/min/sec
cal.set(Calendar.HOUR_OF_DAY, 16); //HOUR
cal.set(Calendar.MINUTE, 39); //MIN
cal.set(Calendar.SECOND, 10); //SEC
// Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getService(MainActivity.this, 0,intent, 0);
//or if you start an Activity
//PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
I'm writing an Android app that has a list of deadlines and I want to notify to user, when the time has come, that one of them is expired at the exact deadline's date, even if the app is not running.
I use an AlarmManager, a custom BroadcastReceiver and a custom Services class, but even if I give the exact time to the alarm it always fire notification only when I run the app.
This is where I set the alarm:
public static void setAlarm( String string){
AlarmManager alarms =(AlarmManager)Utility.getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ALARM_INTENT_FILTER);
intent.putExtra("content",string);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Utility.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE,00);
calendar.set(Calendar.SECOND,00);
calendar.set(Calendar.MILLISECOND,00);
calendar.set(Calendar.AM_PM,Calendar.PM);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
This is the BroadcastReceiver:
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, NotificationServices.class);
service1.putExtra("content",intent.getStringExtra("content"));
context.startService(service1);
}
}
This is the services class:
public class NotificationServices extends Service
{
#Override
public IBinder onBind(Intent arg0) {return null;}
#Override
public void onCreate() {super.onCreate();}
#SuppressWarnings("static-access")
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
JSONObject jsonObject = Utility.jsonObjectFromString(intent.getStringExtra("content"));
DeadLinesList deadlinesList = new DeadLinesList(jsonObject);
Date currentdate = Utility.removeTime(new Date());
String message = "";
for (DeadLine deadline : deadlineList.getDeadline()){
if (deadline.getDateDeadline()!= null && Utility.removeTime(deadline.getDateDeadline()).compareTo(currentdate) == 0){
message += deadline.getDeadlineName()+"\n";
}
}
if (message.length()>0){
NotificationCompat.Builder b = new NotificationCompat.Builder(Utility.getContext());
Intent newIntent = new Intent(Utility.getContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(Utility.getContext(),0, newIntent, 0);
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Message")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND).build();
NotificationManager notificationManager = (NotificationManager) Utility.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {super.onDestroy();}
}
This is the manifest where I register the services and the receiver:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.alarm.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:largeHeap="true">
<receiver android:name=".Notifications.NotificationReceiver">
<intent-filter>
<action android:name="ALARM_ACTION"/>
</intent-filter>
</receiver>
<service android:name=".Notifications.NotificationServices"
android:enabled="true">
</service>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustPan"
android:configChanges="keyboardHidden|orientation|screenSize">
<meta-data
android:name="android.app.default_searchable"
android:value=".MainActivity" />
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Where is the error? Why notification are fired only when I open app, and not at the precise time of the day, or when app is not running?
From the API of AlarmManager
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
I have used broadcast receiver with alarm manager to hit webservices for every 60 seconds,seems its working fine when i have used my broadcast receiver in different class but its not calling when i declare a receiver with in my activity
my code is below
public static void startAlarm(Context context) {
Intent locationAlarm = new Intent(context, GetLocation.class);
AlarmManager alarms = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Calendar updateTime = Calendar.getInstance();
PendingIntent recurringAlarm = PendingIntent.getBroadcast(context, 0,
locationAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,
updateTime.getTimeInMillis() + 500, UPDATE_INTERVAL,
recurringAlarm);
}
Broadcast receiver :
public class GetLocation extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
LogUtil.d("Started Service");
}
}
My Manifest file :
<receiver android:name="com.sample.sample.listeners$GetLocation" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
kindly correct my mistake. my Started service method never called
You have a typo in your manifest file. You have put $GetLocation instead of .GetLocation
<receiver android:name="com.sample.sample.listeners.GetLocation" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
In my project, I'm using alarm code. There is no error, but anything within the BroadcastReceiver class is not being executed. I don't understand where the fault is.
Im doing it in Windows using Eclipse. I also have specified the <receiver> class in AndroidManifest.xml.
I want the code whithin the BroadcastReceiver class to be executed. In this case, I want the text given whithin the receiver class to be displayed at the specified time.
This is my receiver class:
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.registerReceiver(null, null);
Toast.makeText(context, "Time is
up!!!!.",Toast.LENGTH_LONG).show();
}}
Can anyone suggest a way to get rid of this problem?
Thanks!!!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project.rappel"
android:versionCode="1"
android:versionName="1.0">
<application
android:icon="#drawable/icon"
android:label="#string/app_name">
<provider
android:name="ScheduleProvider"
android:authorities="com.project.rappel" />
<activity
android:name=".Rappel"
android:label="#string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SetSchedule"></activity>
<activity
android:name=".DaysAndTimes"></activity>
<activity
android:name=".Tts"></activity>
<receiver
android:name="MyBroadcastReceiver"
android:process=":remote" />
</application>
<uses-sdk
android:minSdkVersion="8" />
</manifest>
Above is my androidmanifest.xml.This is the code I used for trigerring the Receiver.
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();
}
Looking only at this piece code it is not easy to answer.
However, it is likely that you have not specified the intent filter for the receiver in the manifest.
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="xyz.abc.YOUR_ACTION" />
</intent-filter>
</receiver>
The activity or service that is using the alarm, when "the time is up" has to send an Intent matching the action specified in the android manifest. You have to do something like this:
Intent MyIntent = new Intent("xyz.abc.YOUR_ACTION");
Context cont = this.getBaseContext();
cont.sendBroadcast(SMSIntent);
Hope this helps.
Cheers
I think the problem is in manifest file.
Try to remove this parameter "android:process=":remote"" from your reciever.
EDIT:
Please, see my code bellow it work's perfectly. Hope, it will help.
// registration
Intent intent = new Intent(context, AlarmReceiver.class).putExtra(AlarmReceiver.ALARM_ID, alarm.getId());
intent.setData(Uri.parse("date:" + alarm.getId()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // try to change last parameter like mine
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTime().getTime(), pendingIntent);
// in manifest in application tag
<receiver android:name=".ui.more.AlarmReceiver"/>
// receiver class
public class AlarmReceiver extends BroadcastReceiver {
public static final String ALARM_ID = "alarmId";
public void onReceive(Context context, Intent intent) {
context.startActivity(new Intent(context, StartAlarmActivity.class)
.putExtra(StartAlarmActivity.ALARM_ID, intent.getExtras().getInt(ALARM_ID))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
First try adding a period in your manifest file in front of MyBroadcastReceiver. It should look like: android:name=".MyBroadcastReceiver".
If that doesn't work (though hopefully it does) try adding 'Context.' before ALARM_SERVICE on this line:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
so it would look like:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Otherwise, I am not seeing anything immediately obvious.
This code works fine:
public void setupAlarm() {
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
// Set Alarm for next 10 seconds
time.add(Calendar.SECOND, 10);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
}
and in the androidmanifest.xml I used this code:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name=".MyAlarmReceiver" />
<activity
android:name=".AlarmSampleActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Thanks all for helping!!!