Wednesday, September 11, 2013

[android-developers] Android Alarm Manager problems after a period of time

Hi,
I have a problem using Alarm Manager. I developed a simple reminder application. It is composed by a set of normal Activity, an IntentService and a BroadcastReceiver. The first activity show a grid of reminder, and with a button I can create a new reminder (managed by another activity). The new reminder is stored into the database and when the storing operation terminate another activity starts an IntentService: the IntentService take the data from the database and create the reminders. Finally a broadcast receiver manage these reminders and shows a notification. 
But a problem persist: the first reminders within the first about 30/40 minutes are correctly notified, while the others after this period of time don't work.
This is my code: 



IntentService class:

package com.example.papp;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;

public class AlarmIntentService extends IntentService {
private IntentFilter matcher;
protected static int HELLO_ID =555;
private int counter;
private DbAlarmReminderAdapter dbAlarmReminderAdapter;
private Cursor alarmCursor;
private DbAdapter dbHelper; 
    private Cursor cursor;
private long ldata, lorario;
private String timeString;
long currentTimeStamp = System.currentTimeMillis();
int reminderID = 0;
String imageURIString;

public AlarmIntentService() {
super("AlarmIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
System.out.println("AVVIATO IL ALARMINTENTSERVICE");
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Toast.makeText(this, "Intent process in background", Toast.LENGTH_LONG).show();
syncronizeFromDb();   // avvio la sincronizzazione
}
// METODO PER LA CREAZIONE DELLE NOTIFICHE
private void createNotification(int year, int month, int day_of_month, int hour_of_day, int minute, int second, int reminderID){
counter++;
Calendar cal = Calendar.getInstance();       //for using this you need to import java.util.Calendar;
// add minutes to the calendar object
cal.set(Calendar.MONTH,month);  // the month starts with JAN == 0
cal.set(Calendar.YEAR,year);
cal.set(Calendar.DAY_OF_MONTH,day_of_month);
cal.set(Calendar.HOUR_OF_DAY,hour_of_day);
cal.set(Calendar.MINUTE,minute);
cal.set(Calendar.SECOND,second);
Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmintent.putExtra("title","E' l'ora della medicina");
alarmintent.putExtra("note","PillsApp");
alarmintent.putExtra("reminderID", reminderID);
alarmintent.putExtra("imageURIString", imageURIString);
StringBuilder sb = new StringBuilder();
sb.append(pad(hour_of_day)).append(":").append(pad(minute));
timeString = sb.toString();
alarmintent.putExtra("timeString", timeString);
//cambiato getBroadcast con getService
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID+counter, alarmintent, PendingIntent.FLAG_UPDATE_CURRENT);
//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to 
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

}
//GET IMAGE STRING URI FROM DATABASE
public String getImageStringUrifromDB(long reminderID){
String imageURIString = null;
       dbHelper = new DbAdapter(this);
       dbHelper.open();
       cursor = dbHelper.fetchReminderById(reminderID);
       if(cursor !=null){
    cursor.moveToFirst();
    imageURIString = cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_IMG_SRC));
       }
       cursor.close();
       dbHelper.close();
return imageURIString;
}
public void syncronizeFromDb(){
dbAlarmReminderAdapter = new DbAlarmReminderAdapter(this);
       dbAlarmReminderAdapter.open();
       alarmCursor = dbAlarmReminderAdapter.fetchAllReminders();
       
       
       //calcolo della data, anno, ora ecc corrente
       Calendar cal = Calendar.getInstance();
       int cyear = cal.get(Calendar.YEAR);
       int cmonth = cal.get(Calendar.MONTH);
       int cday = cal.get(Calendar.DAY_OF_MONTH);
       int chour = cal.get(Calendar.HOUR_OF_DAY);
       int cminute = cal.get(Calendar.MINUTE);
       

       //SINCRONIZZAZIONE DI TUTTI I REMINDER
       while(alarmCursor.moveToNext()){
        ldata = alarmCursor.getLong(alarmCursor.getColumnIndex("a_reminder_data"));
        lorario = alarmCursor.getLong(alarmCursor.getColumnIndex("a_reminder_orario"));
       
        int year = CalendarCalculations.getYearNumber(ldata);
        int month = CalendarCalculations.getMonthNumber(ldata);
        int day_of_month  = CalendarCalculations.getDayNumber(ldata);
        int hour_of_day = (int)CalendarCalculations.getHourNumber(lorario);
        int minute = (int)CalendarCalculations.getMinuteNumber(lorario);
        int second = 00;
        reminderID = alarmCursor.getInt(alarmCursor.getColumnIndex("a_reminderID"));
       
        long reminderDateMs = ldata;
        int reminderYear = CalendarCalculations.getYearNumber(reminderDateMs);
        int reminderMonth = CalendarCalculations.getMonthNumber(reminderDateMs);
        int reminderDayMonth = CalendarCalculations.getDayNumber(reminderDateMs);
        int reminderHour = (int) CalendarCalculations.getHourNumber(lorario);
           int reminderMinutes = (int) CalendarCalculations.getMinuteNumber(lorario);
       
           
        long currentDateMs = CalendarCalculations.getCurrentDataInMs();
           int currentHour = CalendarCalculations.getCurrentHourInt();
           int currentMinutes = CalendarCalculations.getCurrentMinuteInt();
           int currentYear = CalendarCalculations.getCurrentYearInt();
           int currentMonth = CalendarCalculations.getCurrentMonthInt();
           int currentDayMonth = CalendarCalculations.getCurrentDayMonthInt();
                        
           
           if(reminderYear == currentYear && reminderMonth == currentMonth && reminderDayMonth == currentDayMonth ){ 
            //System.out.println("STESSO GIORNO");
               if(reminderHour == currentHour){  // stessa ora
                //System.out.println("STESSa ORA");
                if(reminderMinutes > currentMinutes){
                //System.out.println("STESSO GIORNO CREATO");
                imageURIString = getImageStringUrifromDB(reminderID);
                   createNotification(year, month, day_of_month, hour_of_day, minute, second, reminderID);
                }
               
               }
           }
           else if(reminderDateMs > currentDateMs){  // altro giorno superiore alla data corrente
            //System.out.println("ALTRO GIORNO CREATO");
            imageURIString = getImageStringUrifromDB(reminderID);
               createNotification(year, month, day_of_month, hour_of_day, minute, second, reminderID);
           }
           
           //System.out.println("========================================");
           //System.out.println("========================================");
        }// CHIUSURA WHILE
   
       
       
       alarmCursor.close();
       dbAlarmReminderAdapter.close();
}
// METODO CHE AGGIUNGE LO 0 QUANDO SERVE
/** Add padding to numbers less than ten */
private static String pad(int c) {
   if (c >= 10)
       return String.valueOf(c);
   else
       return "0" + String.valueOf(c);
}




}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


The ReceiverClass:

package com.example.papp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;


import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;

import com.example.papp.R;
import com.example.papp.DisplayReminder;
 
public class AlarmReceiver extends BroadcastReceiver {
 
private static int NOTIFICATION_ID = 555;
Bitmap bitmap;
String msg ="msg";
private Context mcontext;
 
@Override
public void onReceive(Context context, Intent intent) {
mcontext = context;
WakeLocker.acquire(context);
Bundle extras=intent.getExtras();
String title=extras.getString("title");
// String id = extras.getString("id");
int reminderID = extras.getInt("reminderID");
// int idInt = Integer.parseInt(id);
String note=extras.getString("note");
String imageURIString = extras.getString("imageURIString");
String timeString = extras.getString("timeString");
note = note+" | "+timeString;
 
 
try {
System.out.println(Uri.parse(imageURIString));
bitmap = MediaStore.Images.Media.getBitmap(mcontext.getContentResolver(), Uri.parse(imageURIString));
bitmap = getResizedBitmap(bitmap,  60, 60);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
 
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
               context)
.setSmallIcon(R.drawable.android100)
               .setContentTitle(note)
               .setLargeIcon(bitmap)
               .setContentText(title)
               .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
 
   Intent notifyIntent =  new Intent(mcontext, DisplayReminder.class);
   notifyIntent.putExtra("reminderID", ""+reminderID);
 
   
   //cambiare getActivity con getService
   PendingIntent contentIntent = PendingIntent.getActivity(mcontext, reminderID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
       mBuilder.setContentIntent(contentIntent);
       NotificationManager mNotificationManager = (NotificationManager) mcontext.getSystemService(Context.NOTIFICATION_SERVICE);
       mNotificationManager.notify(NOTIFICATION_ID++, mBuilder.build());
 
       WakeLocker.release();
 


 
}

public Bitmap getResizedBitmap(Bitmap image, int bitmapWidth, int bitmapHeight) {
    return Bitmap.createScaledBitmap(image, bitmapWidth, bitmapHeight,
                true);
}
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


And this is part of my manifest file:

 <receiver android:name="com.example.papp.AlarmReceiver"></receiver>
        
        <service android:name="com.example.papp.AlarmService"></service>
        
        <service android:name="com.example.papp.AlarmIntentService"></service>
        
        <activity
            android:label="@string/app_name"
            android:name="com.example.papp.GalleryListMainActivity">
             <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Finally, the IntentService is launched from another activity in this way:

Intent msgIntent = new Intent(getApplicationContext(), AlarmIntentService.class);
        startService(msgIntent);
        

Thanks in advance


--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
---
You received this message because you are subscribed to the Google Groups "Android Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to android-developers+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate