I want to give the notification to user on every 5 minutes I am using following code.
it shows me notification first time but not give next time.
public void startAlarm() {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
long whenFirst = System.currentTimeMillis(); // notification time
Intent intent = new Intent(this, NotifyUser.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, whenFirst, 60*5000, pendingIntent);
}
public class NotifyUser extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
loadNotification();
}
private void loadNotification() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification(R.drawable.ic_launcher/*android.R.drawable.stat_notify_more*/, "Hanumanji waiting for you", System.currentTimeMillis());
Context context = NotifyUser.this;
CharSequence title = "Hanumanji is waiting for you";
CharSequence details = "Do Hanuman Chalisa Parayan with ShlokApp.";
Intent intent = new Intent(context, NotifyUser.class);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
notify.setLatestEventInfo(context, title, details, pending);
notify.sound = Uri.parse("android.resource://pro.shlokapp.hanumanchalisa/"+ R.raw.game_sound_pause);
nm.notify(0, notify);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {}
}
it shows me notification first time but not give next time. : The reason is you use nm.notify(0, notify);
Do not use 0 as it will show latest notification.
Below code works like a charm :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 5000, 1500);
}
class MyTimerTask extends TimerTask {
public void run() {
generateNotification(getApplicationContext(), "Hello");
}
}
private void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, 0);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify((int) when, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify((int) when, notification);
}
}
}
Use Timer class. Change the timer interval as per your needs.
Hope this helps.
in this post How exactly to use Notification.Builder there is an example. I used it to make the notification in my app. It also use the NotificationBuilder from the support library.
I think in your code above, you are just updating the notification, that is already there. Try to check it by displaying a number that is increased by one every time you set/update a new notification.
Hope this will help you =).
MainActivity.java // It contains on a textview tvTime
public class MainActivity extends Activity {
private SampleAlarmReceiver alarm;
private ListView listView;
private ArrayList<String> times;
private ArrayAdapter mAdapter;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
displayTime();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
alarm = new SampleAlarmReceiver();
alarm.setAlarm(this);
times = new ArrayList<>();
Calendar c = Calendar.getInstance();
String time = c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
times.add(time);
mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, times);
listView.setAdapter(mAdapter);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("display_time"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks START ALARM, set the alarm.
case R.id.start_action:
alarm.setAlarm(this);
return true;
// When the user clicks CANCEL ALARM, cancel the alarm.
case R.id.cancel_action:
alarm.cancelAlarm(this);
return true;
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
#SuppressLint("SetTextI18n")
public void displayTime() {
Calendar c = Calendar.getInstance();
String time = c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
times.add(time);
mAdapter.notifyDataSetChanged();
}
}
SampleAlarmReceiver.java
public class SampleAlarmReceiver extends WakefulBroadcastReceiver {
// The app's AlarmManager, which provides access to the system alarm services.
private AlarmManager alarmMgr;
// The pending intent that is triggered when the alarm fires.
private PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent("display_time");
// You can also include some extra data.
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
}
// BEGIN_INCLUDE(set_alarm)
/**
* Sets a repeating alarm that runs once a day at approximately 8:30 a.m. When the
* alarm fires, the app broadcasts an Intent to this WakefulBroadcastReceiver.
*
* #param context given context
*/
public void setAlarm(Context context) {
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, SampleAlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
5 * 60 * 1000, // After five minute
5 * 60 * 1000, // Every five minute
alarmIntent);
// Enable {#code SampleBootReceiver} to automatically restart the alarm when the
// device is rebooted.
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
/**
* Cancels the alarm.
*
* #param context given context
*/
public void cancelAlarm(Context context) {
// If the alarm has been set, cancel it.
if (alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
// Disable {#code SampleBootReceiver} so that it doesn't automatically restart the
// alarm when the device is rebooted.
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
SampleBootReceiver.java
public class SampleBootReceiver extends BroadcastReceiver {
SampleAlarmReceiver alarm;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
alarm = new SampleAlarmReceiver();
alarm.setAlarm(context);
}
}
}
main.xml // its a menu used in MainActivity
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/start_action"
android:title="Start Alarm"
app:showAsAction="ifRoom|withText" />
<item
android:id="#+id/cancel_action"
android:title="Stop Alarm"
app:showAsAction="ifRoom|withText" />
</menu>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmmanager">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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>
<receiver android:name=".SampleAlarmReceiver" />
<receiver
android:name=".SampleBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Related
I've been stuck on this for days now.
I want my alarm manager to fire off every 15 minutes even when the app is closed but it does not work when app is closed. It works while app is open though.
In my manifest file I have:
<!-- Used to consume the alarm manager alerts when app clsoed -->
<receiver
android:name="biz.customName.pkg.AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="biz.customName.pkg.msg"/>
</intent-filter>
</receiver>
My BroadcastReceiver class (AlarmReceiver)
public class AlarmReceiver extends BroadcastReceiver
{
// Alarm manager used to run install when app is closed
AlarmManager alarmManager;
// Called when alarm received
#Override
public void onReceive(Context context, Intent intent)
{
// Enable alarm
setupAlarm(context);
// Perform background task
}
// Setup alarm
public void setupAlarm(Context context)
{
// Setup reciever for alarm
// context.registerReceiver(this, new IntentFilter("biz.customName.pkg.msg"));
// Setup pending intent
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Loader.filterName), PendingIntent.FLAG_UPDATE_CURRENT);
// Setup alarm
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final long triggerTime = System.currentTimeMillis() + 900 * 1000;
// Newest OS
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 23)
{
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}
}
}
In main I call setup alarm to get the alarm going initially then each time the onReceive inside my Broadcast receiver is called I reset the alarm.
What am I doing wrong that it doesn't work when the app is closed?
Add this in your AndroidManifest.xml
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".MyAlarmReceiver"
android:enabled="true"
android:exported="true" />
MyAlarmReceiver.java
public class MyAlarmReceiver extends BroadcastReceiver {
Context context;
public MyAlarmReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
intent = new Intent(context, MyService.class);
context.startService(intent);
}
}
MyService.java
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
YourTask();
return Service.START_STICKY;
}
private void YourTask(){
// call api in background
// send push notification
//etc...
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
PendingIntent pendingIntent;
AlarmManager alarmManager;
Intent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoUpdateDataInBackground();
}
private void AutoUpdateDataInBackground() {
// Retrieve a PendingIntent that will perform a broadcast
alarmIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
long interval = 15 * 60 * 1000;
// Repeating on every 15 minutes interval
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),interval, pendingIntent);
}
}
BTW : AlarmManager will not be called with locked screen and enabled energy saving mode
My Scenario is to show Greeting notification to my users even they are not using the app. Below code is working fine if the open is opened or minimized. But, I want to show the notification in morning even though the user did not open the application.
Main Activity:
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.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
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
}
My Receiver Class:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
/*Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);*/
try{
Utils.generateNotification(context);
}catch(Exception e){
e.printStackTrace();
}
}
}
Utils Class:
public class Utils {
public static NotificationManager mManager;
#SuppressWarnings("static-access")
public static void generateNotification(Context context){
mManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent intent1 = new Intent(context,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(context,0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
}
My Alarm Service:
public class MyAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Next Activity:
public class NextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
A few things you need to do here. If the user force closes the app, you need to ensure that you start your service with START_STICKY so that the service restarts when the app is force closed.
In order to get the Service to start when the user has rebooted their phone, you will need your BroadcastReceiver to receive BOOT_COMPLETED which will then start the service.
Your service will then set the Alarm as per normal. You will need to store the time of the alarm you want to set somewhere. I use SharedPrefs (PreferenceManager.getDefaultSharedPreferences(getApplicationContext());) but I'm sure there are better methods.
i have a probleme with BroadcastReceiver & Service in my application
.......
i have an
* activity ( MainActivity )
* service ( NotifyService )
* Receiver ( NotifyBroadcast )
service start from activity and then the receiver start from service
everything is good when my app was open , but when i clear it (destroyed) ,receiver stop doing its job ( just a toast message )
here is my code :
MainActivity ..
if( !NotifyService.ServiceIsRun){
NotifyService.ServiceIsRun=true;
startService(new Intent(this, NotifyService.class));
}
NotifyService ..
public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
if(ServiceIsRun){
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.e("broadService", "hello from Service"+i +"new :"+lastnew +"article :"+lastarticle);
i++;
Intent intent = new Intent( "com.latestBabiaNews" );
sendBroadcast(intent);
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
20000);
}
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
NotifyBroadcast ..
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
}
And in my Manifest ..
<service android:name=".NotifyService"></service>
<receiver android:name=".NotifyBroadcast">
<intent-filter>
<action android:name="com.latestBabiaNews"></action>
</intent-filter>
</receiver>
..........
finally i can show the Toast message when app was app was opened , but when i clear it i can't show anything !
To prevent service kill use it as foreground service. To perform it as foreground use this (inside Service class):
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
fg();
}
private void fg() {
Intent intent = launchIntent(this);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(getResources().getString(R.string.app_alias))
.setContentText(getResources().getString(R.string.app_alias))
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(someicon);
} else {
mBuilder.setSmallIcon(someicon);
mBuilder.setColor(somecolo);
}
noti = mBuilder.build();
noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
startForeground(_.ID, noti);
}
to stop, this:
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopForeground(true);
}
EDIT
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class MyBroadCast extends WakefulBroadcastReceiver {
public static final String INTENT_FILTER = "ru.ps.vm.BRTattva";
#Override
public void onReceive(Context ctx, Intent intent) {
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
To start use this:
public static void startbyalarm(Context ctx, long nexttime, boolean autoStart, SharedPreferences settings) {
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
Intent intent = new Intent(MyBroadcastReceiver.INTENT_FILTER);
if (autoStart)
intent.putExtra(_.AUTOLOADSERVICE,true);
PendingIntent pi = PendingIntent.getBroadcast(ctx, _.intentalarmindex, intent, PendingIntent.FLAG_CANCEL_CURRENT);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
am.setExactAndAllowWhileIdle(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
}
}
//or use repeating:
//am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
I want to implement a Service which permit to show a notification (daily, or after XX minutes) even if I close the application. (Actually, when I press back button, I finish the MainActivity...)
I need a runnable notification even if I didn't start the application (after rebooting the device for example, of course when the trigger is declanched)...
I tried some clear examples and tutorials but I doesn't find what I need.
Please HELP!
Thanks in advance,
Mohamed
You can do it with alarm manger:
public class AlarmHelper {
private Context context;
private AlarmManager alarmManager;
private static final String TAG = "AlarmHelper";
public final static String ALARM_ALERT_ACTION = "com.android.alarmclock.ALARM_ALERT";
public AlarmHelper(Context context) {
this.context = context;
alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
}
public void setNotifyAlarm(Long milliSecond) {
PendingIntent pendingIntent = getNotifyPendingIntent();
alarmManager.cancel(pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, milliSecond, pendingIntent);
// alarmManager.set(AlarmManager.RTC_WAKEUP, milliSecond, sender);
}
public void cancelNotifyAlarm() {
PendingIntent pendingIntent = getNotifyPendingIntent();
alarmManager.cancel(pendingIntent);
}
private PendingIntent getNotifyPendingIntent() {
Intent intent = new Intent(context, AlarmExpireService.class);
return PendingIntent.getService(context, 0, intent, 0);
}
public void setExpireAlarm(int minute) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, minute - 1);
PendingIntent pendingIntent = getExpirePendingIntent();
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
}
public void cancelExpireAlarm() {
PendingIntent pendingIntent = getExpirePendingIntent();
alarmManager.cancel(pendingIntent);
}
private PendingIntent getExpirePendingIntent() {
return PendingIntent.getService(context, 0, new Intent(context,
AlarmExpireService.class), 0);
}
}
Now in the AlarmExpireService.java:
public class AlarmExpireService extends Service {
// private static final String TAG = "AlarmExpireService";
private static final String TAG = "AlarmExpireService";
#Override
public void onCreate() {
super.onCreate();
//your logic for start activity or generate notification.
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AppLog.Log(TAG, "On start command");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Now Register service in the manifest file:
<service android:name="your_package.AlarmExpireService" />
For just call a method from AlarmHelper's setNotifyAlarm method and your work is done pass the time in millisecond (it will start after that time and notification will be pop up).
For more information take a reference of this links:
1. AlarmManager
2. Service
3.Pending Intent
I have my alarms that calls onReceive() in my broadcast receiver.
public class MainActivity extends ActionBarActivity {
private Button bLoggOut, bStartTracking, bStop;
final private static String myAction = "com.brucemax.MY_ALARM_OCCURED";
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
Log.d("myTag", "Alarm set "+String.valueOf(isAlarmSet()));
bStartTracking = (Button) findViewById(R.id.bStartTracking);
bStartTracking.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(myAction);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ContextHolder.getAppContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0/*updateTime.getTimeInMillis()*/, 5 * 1000, pendingIntent);
}
});
bStop = (Button) findViewById(R.id.bStop);
bStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
canselSetWakeUpMode();
}
});
}
public void canselSetWakeUpMode() {
Log.d("myTag", "MainActivity canselSetWakeUpMode()");
Intent myAlarm = new Intent(myAction);
// myAlarm.putExtra("project_id",project_id); //put the SAME extras
PendingIntent recurringAlarm = PendingIntent.getBroadcast(ctx, 1, myAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
alarms.cancel(recurringAlarm);
}
public boolean isAlarmSet() {
Intent myAlarm = new Intent(myAction);
return (PendingIntent.getBroadcast(ctx,1, myAlarm, PendingIntent.FLAG_NO_CREATE) != null) ;
}
}
MyReciever in manifest:
<receiver android:name=".Service.StartServiseWakefulReceiver">
<intent-filter>
<action android:name="com.brucemax.MY_ALARM_OCCURED"/>
</intent-filter>
</receiver>
Receiver:
public class StartServiseWakefulReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, HandleLocationService.class);
Log.d("myTag", "StartServiseWakefulReceiver onReceive()");
// Start the service, keeping the device awake while it is launching.
//Log.i("SimpleWakefulReceiver", "Starting service # " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
It is work. When i run app at first isAlarmSet() is false. I start alarming, it is work, then I stop alarming (and it is realy stops), close app. But when I start app again the isAlarmSet() is true!!! But alarming not run. Why???
Regards!