Alarm Repeating automatically - android

I ring alarm at particular user entered time. The problem is that after some time, the alarm rings again even if no time is set. This repeated alarm does not ring after after a fixed time. Sometimes it rings after 2 minutes, sometimes after 7 minutes and so on..I don't want this, It is ruining my project. Below is my code, can you help me:
Intent myIntent = new Intent(ReminderService.this, MyReceiver.class);
int randomPIN = (int)(Math.random()*9000)+1000;
pendingIntent = PendingIntent.getBroadcast(ReminderService.this, randomPIN, myIntent,pendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() , pendingIntent);
MyReceiver.java:
package app.aguai.medieazy;
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);
}
}
And My AlarmService.java:
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);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min=c.get(Calendar.MINUTE);
int sec=c.get(Calendar.SECOND);
String currenttime= String.valueOf(hour)+" : "+String.valueOf(min)+" : "+String.valueOf(sec);
PrescribedDB db=new PrescribedDB(getApplicationContext());
Intent i=new Intent(MyAlarmService.this,ReminderPopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("name",db.getMed(currenttime));
i.putExtra("time",currenttime);
startActivity(i);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
I have to launch this project tomorrow and this is the only small bug in my big project. Please help. Thanx.

Related

unable to stop service using AlarmManger in android

public class myserveclass extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
.
public class MainActivity extends ActionBarActivity {
CheckinternetConnection internet;
TextView textview;
int tempint = 100;
private static final long REPEAT_TIME = 1000 * 5;
private PendingIntent pendingIntent;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
internet = new CheckinternetConnection();
schedueService();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(internet, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(internet);
}
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Utils.isNetworkAvailable(MainActivity.this)) {
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
}
}
}
public void schedueService() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
1000 * 10, pintent);
}
}
this is my code for start service and stop service am able to start service when app is connected with internet and stop when internet is off but after 10 second again service becomes start please check my issue where am doing wrong i have used alarm manger please check please suggest me where am doing wrong .
You need to CANCEL the alarm to stop the service
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pintent);
Hope it helps ツ

android alarm doesn't work if i press back button

I have implemented an Alarm manager and receiver in my application, all is working perfectly. The issue I am having is when I press the back button to close the application, the alarm doesn't run at the time specified. Below is the code I am using:
My Receiver Code
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("SERVICE RECIEVED");
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
My Alarm Service Code
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();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Intent _intent = new Intent(getBaseContext(), FirstCallActivity.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(_intent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
Start Alarm Code
public void startAlarm(Calendar cal) {
// Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, FirstCallActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 12345,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
Manifest Code (within application tags)
<service
android:name=".MyAlarmService"
android:enabled="true" />
<receiver android:name=".MyReceiver" />
Could anyone explain why this is happening? I know if the application is fully closed nothing is going to happen, but I it seems strange the back button causing this issue because the application is still running in the background.
Thanks
It turns out that the app was being closed on the back button. By stopping the app closing on the back button press with the code below, the function required for the set alarm run correctly.
#Override
public void onBackPressed() {
System.out.println("BACK PRESS");
moveTaskToBack(true);
}

Pending intent get service

I am having a problem getting my pendingIntent to fire. I have done some troubleshooting using the logcat etc. and in the end I am almost positive that my problem is actually in my pendingIntent method. The times I have set are correct, and the method is getting called, but nothing happens at the scheduled times.
Here is the method that I use to create the pendingIntent
public void scheduleAlarm(){
Log.d("Alarm scheduler","Alarm is being scheduled");
Intent changeVol = new Intent();
changeVol.setClass(this, VolumeService.class);
PendingIntent sender = PendingIntent.getService(this, 0, changeVol, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, sender);
//Toast.makeText(this, "Volume Adjusted!", Toast.LENGTH_LONG).show();
}
Here is the service class:
public class VolumeService extends Service{
#Override
public void onCreate() {
super.onCreate();
Log.d("Service", "Service has been called.");
Toast.makeText(getApplicationContext(), "Service Called!", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
The log in the scheduleAlarm() class is working as I planned but then nothing happens, so I assume it is my pendingIntent.
Thanks in advance!
Figured it out! The problem was in the Service class, I changed a few other things around too.
However, I believe the main problem was that in my service class in the onCreate method I was trying to run my code. But this needed to be done in the onStartCommand method
public class VolumeService extends Service{
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_LONG).show();
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
and a few changes were made in the class starting the service as seen here:
public void scheduleAlarm(){
Log.d("Alarm scheduler","Alarm is being scheduled");
Intent intent = new Intent(AlarmSettings.this, VolumeService.class);
PendingIntent pintent = PendingIntent.getService(AlarmSettings.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, time, pintent);
}

Android AlarmManager problems

I'm making and application in android using multiple alarms, and i want to do differents things for each alarm, my problem is that i don't know how to recover the id of the alarm or differentiate each alarm in alarm class.
This is my code:
//Activate the alarm
public void ActivateAlarm(int num) {
int seconds =Preferences.getTime(num);
myIntent[num] = new Intent(Settings.this,
Alarm.class);
pendingIntent[num] = PendingIntent.getService(Settings.this, num,
myIntent[num], 0);
alarmManager[num] = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager[num].setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
seconds * 1000, pendingIntent[num]);
Toast.makeText(Settings.this, "Alarm"(num+1)+"activated",Toast.LENGTH_LONG)
.show();
}
class Alarm
public class Alarm extends Service implements Runnable {
public int alarmID;
private static Thread thread;;
#Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(1);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Toast.makeText(Alarm.this, Alarm.thread.getName(), Toast.LENGTH_LONG).show();
//ReadFile.readFile(Integer.parseInt(thread.getName()));
displayNotification();
}
};
private void displayNotification() {
//different notification for each alarm
}
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
//super.onStart(intent, startId);
thread = new Thread(this);
thread.start();
}
public void setIDAlarm(int pos){
this.alarmID=pos;
}
}
Thank you.
SInce it worked for you i'll post as answer for others:
You can use
intent.setAction("MyAction1")
and then filter your alarms with
intent.getAction().equals("MyAction1") { do something ...}

Service Stopping in Android

I have Android Service that runs always in background, and another service which is triggered by the always running service which is alarmmanager service.
Howewer, I want to stop service with a button, my aim is to stop always running service so the alarm manager service will automatically be stopped. Is it correct perspective?
My sample code is as follows
package com.example.deneme;
public class AndroidNotifyService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartService = (Button)findViewById(R.id.startservice);
Button buttonStopService = (Button)findViewById(R.id.stopservice);
buttonStartService.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(AndroidNotifyService.this, com.example.deneme.AndroidScheduledService.class);
AndroidNotifyService.this.startService(intent);
}});
buttonStopService.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(AndroidScheduledService.ACTION);
intent.putExtra("RQS", AndroidScheduledService.RQS_STOP_SERVICE);
sendBroadcast(intent);
}});
}
}
My always running service
package com.example.deneme;
public class AndroidScheduledService extends Service {
final static String ACTION = "AndroidScheduledServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
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);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//this.unregisterReceiver(notifyServiceReceiver);
Intent intent = new Intent();
intent.setAction(NotifyService.ACTION);
intent.putExtra("RQS", NotifyService.RQS_STOP_SERVICE);
sendBroadcast(intent);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
My Alarmmanager service
public class NotifyService extends Service {
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
HttpClient httpclnt;
HttpPost httppst;
String message;
String response;
//NotifyServiceReceiver notifyServiceReceiver;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";
/*
#Override
public void onCreate() {
// TODO Auto-generated method stub
notifyServiceReceiver = new NotifyServiceReceiver();
super.onCreate();
}
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
/*
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(notifyServiceReceiver, intentFilter);
*/
// Send Notification
notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher,
"Notification!",
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Exercise of Notification!";
String notificationText = "http://www.google.com/";
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent
= PendingIntent.getActivity(getBaseContext(),
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//this.unregisterReceiver(notifyServiceReceiver);
super.onDestroy();
}
/*
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class NotifyServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int rqs = arg1.getIntExtra("RQS", 0);
if (rqs == RQS_STOP_SERVICE){
stopSelf();
}
}
}*/
}
My BroadCast Receiver Classes
For NotifyService Class
package com.example.deneme;
public class MyScheduledReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(context, com.example.deneme.NotifyService.class);
context.startService(intent2);
}
}
For AndroidScheduledService Class
package com.example.deneme;
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
Intent myIntent = new Intent(context, com.example.deneme.AndroidScheduledService.class);
context.startService(myIntent);
}
}
}
Stopping the service won't stop the Alarm manager service. You have to stop it manually.
Intent intent = new Intent(this, com.example.deneme.AndroidScheduledService.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
To stop a service:
Intent stopServiceIntent = new Intent(getBaseContext(), yourServiceToStop.class);
getBaseContext().stopService(stopServiceIntent );

Categories

Resources