显示多个推送通知

时间:2015-11-01 21:13:49

标签: android notifications push-notification broadcastreceiver android-notifications

我想一次发出多个通知,但它们总是覆盖其他通知,因此始终只有一个通知。

这里的BackgroundService.class:

import saveload.*;



public class BackgroundChecks extends Service {

public static boolean started = false;
private boolean interrupted = false;
private Intent goToAmtsblatt = null;
private Intent goToAmtstafel = null;

private long sleepPeriod = 3*60*60*1000;
ScheduledFuture sf = null;

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

@Override
public int onStartCommand(Intent intent, int a, int b) {
    int ret = super.onStartCommand(intent, a, b);
    try {
        if (intent.hasExtra("notificationActivityAmtsblatt")) {
            goToAmtsblatt = new Intent(this, Class.forName(intent.getStringExtra("notificationActivityAmtsblatt")));
        }
    } catch(Exception cce) {
        //do nothing
    }
    try {
        if (intent.hasExtra("notificationActivityAmtstafel")) {
            goToAmtstafel = new Intent(this, Class.forName(intent.getStringExtra("notificationActivityAmtstafel")));
        }
    } catch(Exception cce) {
        //do nothing
    }
    return ret;
}

@Override
public void onCreate() {
    super.onCreate();

    started = true;
    //do the tasks in Background


    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            //gets Preference Set
            final SharedPreferences sharedPref = BackgroundChecks.this.getSharedPreferences("gemeindeMuckendorf", Context.MODE_PRIVATE);

            try {
                getAktuelles(sharedPref);
            } catch(Exception ex) {
                //do nothing, just retry
            }
            try {
                getServiceNews(sharedPref);
            } catch(Exception ex) {
                //do nothing, just retry
            }
            try {
                getAmtsblatt(sharedPref);
            } catch(Exception ex) {
                //do nothing, just retry
            }
            try {
                getAmtstafel(sharedPref);
            } catch(Exception ex) {
                //do nothing, just retry
            }
        }
    };
    sf = ses.scheduleAtFixedRate(run, 0, sleepPeriod, TimeUnit.HOURS);
}


@Override
public void onDestroy() {
    super.onDestroy();
    if(sf!=null)
        sf.cancel(true);
    sf = null;
    started = false;
}

public void getAmtsblatt(SharedPreferences sharedPref) throws Exception {
    List<String> lastList = new ArrayList<String>();
    List<String> newList;
    //gets Preferences - last successfully checked List
    Thread.sleep(1000);
    lastList = Utils.stringToList(sharedPref.getString("retrievedPDFString", ""));
    newList = Utils.getUrlsFromHTML(Utils.getHTML("http://www.muckendorf-wipfing.at/5-0-Gemeindeblatt+Online.html"));
    //count new URLs
    int newCount = 0;
    for (String url : newList) {
        if (!lastList.contains(url)) { //new URL -> count
            newCount++;
        }
        Thread.sleep(10);
    }
    if (newCount > 0) { //one or more new URLs -> notification
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(BackgroundChecks.this)
                        .setSmallIcon(R.drawable.nclogo)
                        .setContentTitle("Es gibt " + newCount + " neue" + (newCount > 1 ? " Gemeindeblätter" : "s Gemeindeblatt"))
                        .setContentText((goToAmtsblatt == null ? "" : "Hier klicken, um " + (newCount > 1 ? "sie" : "es") + " anzusehen."))
                        .setAutoCancel(true);
        //if goTo is set, built the redirct
        if (goToAmtsblatt != null) {
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(BackgroundChecks.this);
            stackBuilder.addParentStack(Class.forName(goToAmtsblatt.getComponent().getClassName()));
            stackBuilder.addNextIntent(goToAmtsblatt);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
            mBuilder.setContentIntent(resultPendingIntent);
        }

        //re-set the retrieved Pdf List
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("retrievedPDFString", Utils.listToString(newList));
        editor.commit();

        //show the notification
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }
}

public void getAmtstafel(SharedPreferences sharedPref) throws Exception {
    List<String> lastList = new ArrayList<String>();
    List<String> newList;
    Thread.sleep(1000);
    lastList = Utils.stringToList(sharedPref.getString("retrievedAmtstafelString", ""));
    newList = Utils.getUrlsFromHTML(Utils.getHTML("http://www.muckendorf-wipfing.at/6-0-Amtstafel.html"));
    //count new URLs
    int newCount = 0;
    for (String url : newList) {
        if (!lastList.contains(url)) { //new URL -> count
            newCount++;
        }
        Thread.sleep(10);
    }
    if (newCount > 0) { //one or more new URLs -> notification
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(BackgroundChecks.this)
                        .setSmallIcon(R.drawable.nclogo)
                        .setContentTitle("Es gibt " + newCount + " neue" + (newCount > 1 ? " Amtstafel PDFs" : "s Amtstafel PDF"))
                        .setContentText((goToAmtstafel == null ? "" : "Hier klicken, um " + (newCount > 1 ? "sie" : "es") + " anzusehen."))
                        .setAutoCancel(true);
        //if goTo is set, built the redirct
        if (goToAmtstafel != null) {
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(BackgroundChecks.this);
            stackBuilder.addParentStack(Class.forName(goToAmtstafel.getComponent().getClassName()));
            stackBuilder.addNextIntent(goToAmtstafel);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(1, PendingIntent.FLAG_ONE_SHOT);
            mBuilder.setContentIntent(resultPendingIntent);
        }

        //re-set the retrieved Pdf List
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("retrievedAmtstafelString", Utils.listToString(newList));
        editor.commit();

        //show the notification
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }
}

public void getAktuelles(SharedPreferences sharedPref) throws Exception {
    List<News> news = Utils.getNewsFromHTML(Utils.getHTML("http://www.muckendorf-wipfing.at/22-0-Aktuelle+Meldungen.html"));
    String newNewsString = new ObjectSaver().saveString(news);
    String oldNewsString = sharedPref.getString("aktuellesList", "");
    if(!oldNewsString.equals(newNewsString)) {
        SharedPreferences.Editor edit = sharedPref.edit();
        edit.putString("aktuellesList", newNewsString);
        edit.commit();
    }
}

public void getServiceNews(SharedPreferences sharedPref) throws Exception {
    //retrieve List
    List<News> serviceList = new ArrayList();
    serviceList.add(new News("Müllabfuhr Kalender", Utils.extractContentFromHTML(Utils.getHTML("http://www.muckendorf-wipfing.at/34-0-Muellabfuhr+Kalender.html"))));
    serviceList.add(new News("SMS-Erinnerung an Müllabfuhr-Termine", "<html><head><meta http-equiv=\"refresh\" content=\"0; URL=http://195.58.166.60/noeav/umweltverbaende/default.asp?portal=verband&vb=tu&kat=5032&op=5002\"></head><body></body></html>"));
    serviceList.add(new News("Gemeinde- und andere Gebühren", Utils.extractContentFromHTML(Utils.getHTML("http://www.muckendorf-wipfing.at/35-0-Gemeindegebuehren.html"))));
    serviceList.add(new News("Infos zum Wirtschaftshof, Öffnungszeiten & Preisliste", Utils.extractContentFromHTML(Utils.getHTML("http://www.muckendorf-wipfing.at/36-0-Wirtschaftshof.html"))));
    //save List to sharedPrefs
    SharedPreferences.Editor edit = sharedPref.edit();
    edit.putString("serviceList", new ObjectSaver().saveString(serviceList));
    edit.commit();
}

}

这是MyBroadcastReceiver.class:

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Intent startServiceIntent = new Intent(context, BackgroundChecks.class);
    startServiceIntent.putExtra("notificationActivityAmtsblatt", AmtsblattActivity.class.getName());
    startServiceIntent.putExtra("notificationActivityAmtstafel", AmtsblattActivity.class.getName());
    context.startService(startServiceIntent);
}
}

所以我的问题是: 任何人都可以帮我解决此代码的工作原理,可以显示多个通知吗?谢谢!

1 个答案:

答案 0 :(得分:3)

  mNotificationManager.notify(0, mBuilder.build());

生成ID为0的通知。每次使用id调用notify时,都会用该id覆盖当前通知。

解决方案:为新通知使用唯一ID

  mNotificationManager.notify(getUniqueID(), mBuilder.build());
相关问题