繁体   English   中英

使用Alarm Manager Android安排本地通知

[英]Scheduling local notifications using Alarm Manager android

我正在使用本地通知开发android应用程序。 我使用服务实现了本地通知。 在服务中,本地通知有效,但是当我终止应用程序时,服务被破坏。 通知无效。 现在,我想使用警报管理器实现本地通知,该如何使用警报管理器来实现

这是服务等级。

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;
        }
    }







}

startForeground()的文档中:

使此服务在前台运行,并在此状态下向用户显示正在进行的通知。 默认情况下,服务是后台的,这意味着如果系统需要杀死它们以回收更多的内存(例如在Web浏览器中显示大页面),则可以杀死它们而不会造成太大的伤害。 如果取消服务会对用户造成破坏(例如服务正在执行背景音乐播放),则可以设置此标志,以便用户注意其音乐是否停止播放。

showNotification()方法中,您需要在Notification时在前台启动服务,

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

一旦您需要停止服务,只需致电:

stopForeground(**false / true**);

通过false ,如果你不希望一次服务被停止删除通知,还是true ,如果你想要的通知应被自动删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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