0

I am working on an alarm notification function and want to keep the alarms after device reboot. It works fine before I reboot the device. After reboot, it pops up an error( I can't log the error for debug...so I don't know what the error actually is ). This error really brings me a headache......

EDITED: the reboot part is corrected, I remove NOW() in the sqlite query and then it works~~~but I still would like to know the answers of the questions as below. Thanks :)

Besides, I also have couple of questions like how can I remove the alarm when it expires and why the notification does not vibrate in my app??? Thanks.

here is my code:

RebootReceiver

public class RebootReceiver extends BroadcastReceiver{
    private String TAG = "RebootReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.d(TAG, "action: "+intent.getAction());
        SQLiteDatabase db = (new SupremeDB(context)).getReadableDatabase();

        String sql = "SELECT * "+
                    " FROM "+SupremeDB.ALARM_TABLE+
                    " WHERE 1";

        Cursor alarmCursor = db.rawQuery(sql, null);
        while (alarmCursor.moveToNext()){
            String eventType = "";
            switch(alarmCursor.getString(alarmCursor.getColumnIndex(SupremeDB.TABLE_NAME))){
            case SupremeDB.ONE_TO_ONE_TABLE:
                eventType = "One To One";
                break;
            case SupremeDB.DOOR_HOST_TABLE:
                eventType = "Door Host";
                break;
            case SupremeDB.TRAINING_TABLE:
                eventType = "Training";
                break;
            case SupremeDB.LONG_PRESENT_TABLE:
                eventType = "Long Present";
                break;
            }
            this.setAlarm(context, 
                    alarmCursor.getInt(alarmCursor.getColumnIndex(SupremeDB.ALARM_ID)), 
                    alarmCursor.getString(alarmCursor.getColumnIndex(SupremeDB.ALARM_DATE)), 
                    "You have a "+
                    eventType+
                    " on "+alarmCursor.getString(alarmCursor.getColumnIndex(SupremeDB.ALARM_DATE))
                    );
        }
    }

    public Calendar str2Calendar(String datetime){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(datetime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.toString());
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = format2.parse(datetime);
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                Log.e(TAG, e1.toString());
            }
        }

        Calendar dateCalendar = Calendar.getInstance();
        dateCalendar.setTime(date);

        return dateCalendar;
    }

    public void setAlarm(Context context, int alarmId, String datetime, String message){
        Intent intent = new Intent(context, NotificationReceiver.class);
        intent.putExtra("message", message);
        intent.putExtra("alarm_id", alarmId);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar dateCalendar = this.str2Calendar(datetime);
        dateCalendar.set(Calendar.HOUR_OF_DAY, dateCalendar.get(Calendar.HOUR_OF_DAY)-2);

        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC, dateCalendar.getTimeInMillis(), pendingIntent);
        Log.d(TAG, "alarm set: "+dateCalendar.getTimeZone().getDisplayName()+","+dateCalendar.getTimeInMillis()+", id:"+alarmId);
    }
}

and NotificationReceiver

public class NotificationReceiver extends BroadcastReceiver{
    private String TAG = this.getClass().getName();
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.d(TAG, "action:"+intent.getAction());
        String message = intent.getStringExtra("message");
        int alarmId = intent.getIntExtra("alarm_id", 0);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                .setVibrate(new long[]{500, 1000})
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(message);

        NotificationManager notifyMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notifyMgr.notify(context.getResources().getString(R.string.app_name), alarmId, mBuilder.build());
    }

}

the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <receiver android:name="NotificationReceiver">

    </receiver>
    <receiver android:name="RebootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
Simon
  • 471
  • 2
  • 8
  • 20

1 Answers1

1

Make a class that extends the BroadcastReceiver and put the AlarmManager code in its onReceive() then you can resgister the BroadcastReceiver in the Manifest file as below.

<receiver android:name=".MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </receiver> Also add the Permission to the Manifest File.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

You can also refer this example.

Edit: Delete alarm of your application.

You can write a code for vibration :

Vibrator vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500});
Community
  • 1
  • 1
Sagar Pilkhwal
  • 5,914
  • 2
  • 27
  • 78
  • the reboot problem is solved:)but I want to know what means here? – Simon Sep 05 '14 at 09:31
  • what was the problem in your code? For [category](http://stackoverflow.com/a/21257097/3326331) refer this post or this [post](http://stackoverflow.com/a/11078148/3326331). – Sagar Pilkhwal Sep 05 '14 at 09:33
  • 1
    for the reboot problem, I think the error occurs on the query error, which may mean NOW() is not an effective command for sqlite. When I edit it, it runs fine now:) – Simon Sep 05 '14 at 09:36
  • 1
    use `NOW` for SQLite and `NOW()` for MySQL, try executing this on SQLite console ` select datetime('NOW', 'localtime');` or `select datetime('NOW');` – Sagar Pilkhwal Sep 05 '14 at 09:39