简体   繁体   中英

Android Custom-Time Notification Service/Broadcast/AlarmManager

My goal is to implement a notification that appears on a user-chosen time of day. I already tried Service , this works but the problem is it needs a lot of background process (the code is below) and the other one was AlarmManager but this seems not to work properly, especially on API 19+ . I could not find an up-to-date well-coded tutorial or a useful answer on a similar question here on stackoverflow so I turn to you.

All of you know: If a friend text you an Whatsapp you get a notification even when your phone is off or in sleep(screen off). Im sure some of you already implemented something like this.

The task precisely: My app shall notify the user every day once about his scheduled events in his calendar.

For example: He has chosen 13:00 (I'm using always 24h format) to remind him about his events. He scheduled 2 events on next day: - Drive kids to school - Go to gym

Next day at 13:00 the app shows a notification: "You have two events for today!: 1)... 2)..."

Filling the notification with the informations is not the problem. This works fine and I tested it a lot. Im missing only the well-coded background-thread thats watching for the user-chosen time to show the notification.

Please note :

  • The TimerTask ticks-intervall is 1000ms (1second). Im sure this is not well-coded but it works. But Im searching for a better and more battery-friendly solution.

  • Moreover I added the "android.permission.RECEIVE_BOOT_COMPLETED" and "android.permission.WAKE_LOCK" permission.

  • The service is flagged as START_STICKY

Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <service android:name=".services.NotificationService" android:exported="false"/>

        <receiver android:name=".services.BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <activity
            android:name=".activities.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        //Other Activities

    </application>

</manifest>

BootReceiver:

public class BootReceiver extends WakefulBroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, NotificationService.class));
    }
}

NotificationService:

public class NotificationService extends Service{

    private Calendar currentCalendar, plannedCalendar;

    public static final String FILENAME_SETTINGS = "MySettings";
    private static final int MODE_PRIVATE = 0;
    SharedPreferences data;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    private Timer timer;
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            data = getSharedPreferences(FILENAME_SETTINGS, MODE_PRIVATE);

            int plannedHour = data.getInt("alarm_hour", 0);
            int plannedMinute = data.getInt("alarm_minute", 0);
            plannedCalendar = Calendar.getInstance(Locale.getDefault());
            plannedCalendar.set(Calendar.MINUTE, plannedMinute);
            plannedCalendar.set(Calendar.HOUR_OF_DAY, plannedHour);
            plannedCalendar.set(Calendar.SECOND, 0);
            plannedCalendar.set(Calendar.MILLISECOND, 0);

            //Kalender aktualisieren
            currentCalendar = Calendar.getInstance(Locale.getDefault());
            currentCalendar.setTimeInMillis(System.currentTimeMillis());
            //Check ob es 00:00:00 Uhr ist --> Notification wieder erwuenscht!!!
            currentCalendar.set(Calendar.SECOND, 0);
            currentCalendar.set(Calendar.MILLISECOND, 0);
            if(currentCalendar.get(Calendar.SECOND) == 0 && currentCalendar.get(Calendar.MINUTE) == 0 && currentCalendar.get(Calendar.HOUR_OF_DAY) == 0){
                SharedPreferences.Editor editor = data.edit();
                editor.putBoolean("notification", false);
                editor.apply();
            }
            //Nochmal aktualisieren weil durch den "Check" manipuliert wurde
            currentCalendar = Calendar.getInstance(Locale.getDefault());
            currentCalendar.setTimeInMillis(System.currentTimeMillis());


            if((currentCalendar.getTimeInMillis() >= plannedCalendar.getTimeInMillis()) & !data.getBoolean("notification", false)) {
                PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
                PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
                wakeLock.acquire();

                notification();
                SharedPreferences.Editor editor = data.edit();
                editor.putBoolean("notification", true);
                editor.apply();

                wakeLock.release();
            }
        }
    };

    @Override
    public void onCreate(){
        super.onCreate();
        timer = new Timer();
        timer.schedule(timerTask, 0, 1000);
    }

    @Override
    public void onDestroy() {
        try{
            timer.cancel();
            timerTask.cancel();
        }catch (Exception e){
            e.printStackTrace();
        }
        Intent intent = new Intent("Intent");
        intent.putExtra("VALUE", "blalal");
        sendBroadcast(intent);
    }

    public void notification(){
        Context context = getApplicationContext();
        Intent intent = new Intent(context, LiveSelectActivity.class);
        PendingIntent pen = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentTitle(getString(R.string.hineweisTrainingsGeplant))
                .setContentText("Content")
                .setContentIntent(pen)
                .setDefaults(Notification.DEFAULT_ALL)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_add_white_24dp);

        Notification notification = builder.build();
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

Use AlarmManager to schedule Intent s that your service will receive and process at a desired time. It does work if configured properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM