即使app未运行,也会在recyclerview中添加新项目时显示通知

时间:2017-08-25 12:13:10

标签: android android-recyclerview

我想在Recyclerview中插入新项目时显示通知,即使应用程序正在运行

我试过了:

RecyclerAdapter recyclerAdapter = new RecyclerAdapter(getActivity(), title, date, content);
recyclerView.setAdapter(recyclerAdapter);

int newCount = recyclerAdapter.getItemCount();
int previousItem = getFromSavePref(); 
if(previousItem < newCount)
{
     updateNotification();
     previousItem=newCount;
     savedInSharedPref(previousItem);
}

getFromSavePref()和savedInSharedPref(int value)方法在Session类中可用,用于管理共享的prefrences,recyclelerAdapter是recyclerView的适配器类。

public void updateNotification(){
        NotificationCompat.Builder notification = new NotificationCompat.Builder(getActivity());

            notification.setSmallIcon(R.drawable.ic_launcher);

        notification.setContentTitle(getString(R.string.update));
        notification.setContentText(getString(R.string.notificatiocontent));
        Intent intent = new Intent(getActivity(), Main.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(getActivity());
        stackBuilder.addParentStack(Main.class);
        stackBuilder.addNextIntent(intent);
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, newsNotification.build());
    }

通知即将在应用程序运行时发出,即使未运行也要显示

如果我在正确的位置调用updateNotification()或者在其他地方需要它,请告诉我。

0 个答案:

没有答案