Checking alarm running do not work correctly - android

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!

Related

Access to BroadcastReceiver method onReceive() in activity

I have written some related code for AlarmManager App.
I want to do something like writting a Toast massage in the activity, for sure i can not do that in onReceive() method the question is that how can i do it in the activity?
public class MainActivity extends AppCompatActivity implements View.OnClickListener,BroadConnect.IsConnect {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vv();
setRecurringAlarm(MainActivity.this);
}
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
//updateTime.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
updateTime.setTimeZone(java.util.TimeZone.getTimeZone("GMT+5:00"));
updateTime.set(Calendar.HOUR_OF_DAY,10);
//updateTime.set(Calendar.MINUTE,31);
updateTime.set(Calendar.MINUTE,1);
updateTime.set(Calendar.SECOND,20);
Intent intent = new Intent(context, BroadConnect.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}
#Override
public void onReceiveTimer() {
Toast.makeText(MainActivity.this,"OK",Toast.LENGTH_LONG).show(); //This will not be displayed
}
}
public class BroadConnect extends BroadcastReceiver {
private IsConnect isConnect;
public interface IsConnect{
void onReceiveTimer();
}
public void setIsConnect(IsConnect isConnect) {
this.isConnect = isConnect;
}
#Override
public void onReceive(Context context, Intent intent) {
isConnect.onReceiveTimer(); //It runs this and makes a ERRORE
}
}

How to invoke an activity from background services when arrives a notification?

I want to check notifications from background receivers or services.
The notification is shown, but it should also invoke an activity.
MainActicityClass
Here I have created the alarm class which would call broadcast manager at specific interval
public class MainActivity extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent);
}
}
Alarm Receiver Class
This is the broadcast class to invoke from back ground
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, MyListenerServices.class);
context.startService(background);
}
}
MyListener
This is subclass of notificationlistener services
Its reads any incoming notification but unable to read the notification from inactive class
Integrate class read any kind of incoming notification from background
public class MyListenerServices extends NotificationListenerService{
public MyListenerServices() {
}
private boolean isRunning;
private Context context;
private Thread backgroundThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
// Do something here
Log.d("MSG", "ServiceRunning");
StatusBarNotification[] statusBarNotifications = getActiveNotifications();
Log.d("MSG", "New Object2 "+statusBarNotificationsArray);
if (statusBarNotifications.length > 0) {
Log.d("MSG", "New Object "+statusBarNotifications.length);
//
Intent i = new Intent(context, AutomaticCameraActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
// }
// }catch (Exception e){
// Log.d("MSG",e.getMessage());
}
stopSelf();
}
};
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification mNotification=sbn.getNotification();
Log.v("MSG"," Notification"+ mNotification);
}
#Override
public void onDestroy() {
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
Any help would be appreciated
Thanks in advance
Create a pending intent
Intent resultIntent = new Intent(this, ResultActivity.class);
//Change ResultActivity by your activity you want invoke
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
More information in Create Notification

pending itent doesn't trigger receiver "onReceive"

I have the following code which is executed when I debug it:
private void initPendingIntent() {
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(getActivity(), AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, alarmIntent, 0);
}
private PendingIntent pendingIntent;
private void initViews(LayoutInflater inflater, ViewGroup container) {
rootView = inflater.inflate(R.layout.fragment_settings, container, false);
rootView.findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
public void start() {
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
int interval = 2000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(getActivity(), "Alarm Set", Toast.LENGTH_SHORT).show();
}
and yet the execution doesn't stop at the breakpoint i place here:
public class AlarmReceiver extends RoboBroadcastReceiver {
#Override
public void handleReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
and my manifest:
<receiver android:name=".boradcasts.AlarmReceiver"
android:enabled="false">
</receiver>
<receiver android:name=".boradcasts.AlarmReceiver"
android:enabled="false">
</receiver>
change false to true =)

How to begin a receiver function programmatically in android?

I want to begin the receiver class by programmatically,I got some idea about how to start service programmatically and what is the difference between beginning service programmatically and receiver programmatically.Share your solutions and ideas.
If you add receiver in service and get data from your activity. I add Activity and Service class below.
This is your main activity when you get receive data from service.
public class YourActivity extends Activity {
private MyReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter(YourServices.ACTION);
manager.registerReceiver(receiver, filter);
if (!YourServices.isRunning) {
startService(new Intent(this, YourServices.class));
}
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals(YourServices.ACTION)) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 20 seconds after boot completed
cal.add(Calendar.SECOND, 20);
Log.v("background service", "STARTED////\\");
//
// Fetch every 1 hour
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
}
}
}
}
}
Here your service that send data when starting.
public class YourServices extends Service {
public static String ACTION = "your_action";
public static boolean isRunning = true;
private void broadcastData() {
Intent intent = new Intent(ACTION);
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
broadcastData();
return START_STICKY;
}
}

Notification on every 5 minutes

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>

Categories

Resources