简体   繁体   中英

Scheduling local notifications using Alarm Manager android

I'm developing android application using local notifications. I was implemented local notifications using Services. In services local notifications work but when I kill the app the service destroyed. Notifications not working. Now I want to implement local notifications using alarm manager how can I do this with alarm manager

Here is Service Class.

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.deemsysinc.cyberhealthapp.R;
import com.deemsysinc.cyberhealthapp.weightgoal.WeightGoalActivity;
import com.google.gson.Gson;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

public class NotificationService extends Service{
    private IBinder iBinder=new MyBinder();
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Handler handler;
    // timer handling
    NotificationManager manager;
    Notification myNotication;
    static TimerTask timerTask;

    Date date1;
    Date date2;
    ArrayList<NotificationList> notificationLists;

    int temp=0;


    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return true;
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        handler=new Handler();
        prefs = getSharedPreferences(configuration.AppPrefernce, MODE_PRIVATE);
        editor = prefs.edit();
        notificationLists=new ArrayList<NotificationList>();


    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        timerStart();
        //Remove();
        return Service.START_STICKY;
    }

    public void showNotifications()
    {

        Calendar cal = Calendar.getInstance();
        Date currentLocalTime = cal.getTime();
        DateFormat date = new SimpleDateFormat("hh:mm a");
        String localTime = date.format(currentLocalTime);
        String converted = localTime.replace("am", "AM").replace("pm", "PM");
        Toast.makeText(getApplicationContext(),"Timer Running",Toast.LENGTH_LONG).show();
        Log.d("Locals",""+local);
        //Toast.makeText(getApplicationContext(),"Service Checked",Toast.LENGTH_SHORT).show();
        if(!prefs.getString("weight_hr","").equals("")) {
            if (prefs.getString("weight_hr", "").equals(converted)) {
                temp++;
                Bundle bundle=new Bundle();
                //SimpleDateFormat writeformat = new SimpleDateFormat("dd/MM/yyyy");
                //String formattedDate = writeformat.format(calendar.getTime());
                if(temp==1) {
                    notificationLists.add(new NotificationList("Weight", "It's time to log your weight today. Click to update weight!", ""));
                    Gson gson = new Gson();
                    String json = gson.toJson(notificationLists);
                    editor.putString("notificationlist", json);
                    editor.commit();
                    bundle.putString("fromNotificationCenter","1");
                }
                else
                {
                    bundle.putString("fromNotificationCenter","0");
                }
                manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Intent notificationIntent = new Intent(getApplicationContext(), WeightGoalActivity.class);
                notificationIntent.putExtras(bundle);
                PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 6, notificationIntent, 0);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
                builder.setAutoCancel(true);
                builder.setContentTitle("Cyberhealths");
                builder.setContentText("It's time to log your weight today. Click to update weight!");
                builder.setSmallIcon(R.drawable.my_icon);
                builder.setContentIntent(pendingIntent);
                builder.setOngoing(false);
                manager.notify(6, builder.build());

            }
        }











    }





    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(6);
        Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show();

    }
    private void timerStart() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            showNotifications();
                        } catch (Exception e) {

                        }

                    }
                });
            }
        };
        timer.scheduleAtFixedRate(timerTask, 0, 65000);

    }


   @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);

    }

    private void runOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }
    public class MyBinder extends Binder {
        public NotificationService getService() {
            return NotificationService.this;
        }
    }







}

From the documentation of startForeground() :

Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.

In your showNotification() method you need to start service on foreground upon Notification,

int FOREGROUND_ID = 6;
....
builder.setOngoing(false);
Notification notification = builder.build();
manager.notify(FOREGROUND_ID, notification);
startForeground(FOREGROUND_ID, notification);

Once you need to stop the service, simply call:

stopForeground(**false / true**);

Pass false if you don't want Notification to be removed once service stops, or true if you want that Notification should be removed automatically.

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