如何在以后显示状态栏通知?

Posted

技术标签:

【中文标题】如何在以后显示状态栏通知?【英文标题】:How to show status bar notification at a later time? 【发布时间】:2016-05-18 11:51:42 【问题描述】:

我已成功创建状态栏通知,但我希望它在用户退出应用 6 小时后弹出。

我有以下代码:

public class myClass extends superClass implements myinterface 

    final int NOTIF_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) .........

    /* more methods etc */ ......

    @Override
    protected void onDestroy() 
        View iop = (View) findViewById(R.id.app);
        sendNotification(iop);

        super.onDestroy();
    

    public void sendNotification(View view) 

        // Use NotificationCompat.Builder to set up our notification.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        //icon appears in device notification bar and right hand corner of notification
        builder.setSmallIcon(R.drawable.ic_launcher);

        // This intent is fired when notification is clicked
        Intent intent = new Intent(view.getContext(), androidLauncher.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Set the intent that will fire when the user taps the notification.
        builder.setContentIntent(pendingIntent);

        // Large icon appears on the left of the notification
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));

        // Content title, which appears in large type at the top of the notification
        builder.setContentTitle("Notifications Title");

        // Content text, which appears in smaller text below the title
        builder.setContentText("Your notification content here.");

        // The subtext, which appears under the text on newer devices.
        // This will show-up in the devices with Android 4.2 and above only
        builder.setSubText("Tap to view documentation about notifications.");

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // Will display the notification in the notification bar
        notificationManager.notify(NOTIF_ID, builder.build());

退出应用程序时会弹出状态栏通知,但我希望它在用户退出应用程序后 6 小时后弹出。我该怎么办?

提前致谢!

【问题讨论】:

使用报警管理器弹出通知 【参考方案1】:

您可以使用AlarmManager 安排包含您的通知的广播。

private void scheduleNotification() 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("Scheduled Notification");
    builder.setContentText(content);
    builder.setSmallIcon(R.drawable.ic_launcher);]
    Notification notification = builder.build();

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(6);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);

然后使用 BroadcastReceiver 接收意图并显示通知。

public class NotificationPublisher extends BroadcastReceiver 

    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";

    public void onReceive(Context context, Intent intent) 

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);

    

不要忘记在您的 AndroidManifest.xml 文件中注册接收器。

(来源:https://gist.github.com/BrandonSmith/6679223)

【讨论】:

嗨,我更倾向于您的解决方案,但我需要使用 NotificationCompat 而不是 Notification 来支持旧设备。我尝试更改,但出现了一些红线错误,要求我改为更改通知。如果可能,您可以编辑代码以支持 NotificationCompat 吗?非常感谢! 使用NotificationCompat.Builder 代替Notification.Builder 应该可以。 实施没有错误,但没有显示通知。还添加了接收器。 你等了 6 个小时?您是否在 AndroidManifest 中添加了接收器? 我将 TimeUnit.HOURS.toMillis(6) 更改为 TimeUnit.SECONDS.toMillis(30) 以不必等待 6 小时。是的,我在 AndroidManifest 中添加了接收器,但没有任何反应。【参考方案2】:

创建一个新类,该类将使用挂起的意图和警报管理器执行警报。

long time= 6*60*60*1000; //6 hours
new Alarm_task(this, time).run();

public class Alarm_task implements Runnable

    // The android system alarm manager
    private final AlarmManager am;
    // Your context to retrieve the alarm manager from
    private final Context context;
    long alarm_time;

    public Alarm_task(Context context, long time) 
        this.context = context;
        this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        this.alarm_time = time;
    

    @Override
    public void run() 
        // Request to start are service when the alarm date is upon us
        //pop up a notification into the system bar not a full activity
        Intent i = new Intent("intent name");
        // can create a dialog in that intent or just call the sendNotification() function
        /** Creating a Pending Intent */
        PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);

        /** Setting an alarm, which invokes the operation at alart_time */
       alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + alarm_time, operation);
    

在清单文件中定义意图:

<activity
        android:name=".Activity name"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="Intent name" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

现在在该活动中,您可以在 onCreate() 期间调用 Sendnotification() 函数.. 或根据您的应用程序显示一些 UI

【讨论】:

在哪里添加通知代码?在 run 方法里面? 创建一个与意图 i 关联的新活动,该活动将在 6 小时后触发..【参考方案3】:

onDestroy调用这个方法

public void Remind (String title, String message)
    



AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

                        Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
                        notificationIntent .PutExtra ("message", message);
        notificationIntent .PutExtra ("title", title);
                    notificationIntent.addCategory("android.intent.category.DEFAULT");

                    PendingIntent broadcast = PendingIntent.getBroadcast(context, 0 , notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                    Calendar cal = Calendar.getInstance();

                    if (android.os.Build.VERSION.SDK_INT>16)
                    
                        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+ 6*60*60*1000, broadcast);
                    else
                    
                        alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 6*60*60*1000, broadcast);
                    


新建一个JAVA文件

    public class Broadcast extends BroadcastReceiver 
    @Override
    public void onReceive(Context context, Intent intent1) 
        String message = intent1.getStringExtra ("message");
        String title = intent1.getStringExtra ("title");

// This intent is fired when notification is clicked
Intent notificationIntent = new Intent(context, AndroidLauncher.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(AndroidLauncher.class);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


// Use NotificationCompat.Builder to set up our notification.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        //icon appears in device notification bar and right hand corner of notification
        builder.setSmallIcon(R.mipmap.ic_launcher);




        // Set the intent that will fire when the user taps the notification.
        builder.setContentIntent(pendingIntent);



        // Content title, which appears in large type at the top of the notification
        builder.setContentTitle("Notifications Title");

        // Content text, which appears in smaller text below the title
        builder.setContentText("Your notification content here.");

        // The subtext, which appears under the text on newer devices.
        // This will show-up in the devices with Android 4.2 and above only
        builder.setSubText("Tap to view documentation about notifications.");

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // Will display the notification in the notification bar
        notificationManager.notify(0, builder.build());



    

在清单中注册此接收器

<receiver android:name=".Broadcast">
            <intent-filter>
                <action android:name="android.media.action.DISPLAY_NOTIFICATION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

【讨论】:

无法解析方法“GetStringExtra”;无法解析符号“视图”;无法解析方法“getResources()”;无法解析方法“getSystemService()”;无法解析符号“NOTIFICATION_SERVICE”;无法解析符号“NOTIF_ID”; 仍有一些错误。无法解析方法“getIntent()”; PendingIntent.getActivity(this, 0, tent, 0) 第一个参数类型错误。找到:“com.package.app.Broadcast”,需要:“android.content.Context”;无法解析方法“getSystemService()”;无法解析符号“NOTIFICATION_SERVICE”;无法解析符号“NOTIF_ID”; 现在只有一个问题:getSystemService(NOTIFICATION_SERVICE);无法解析方法“getSystemService()”;无法解析符号“NOTIFICATION_SERVICE”; @TrondroMulligan 试试我编辑的答案。如果存在问题,请告诉我。【参考方案4】:

您可以使用警报管理器服务和通知管理器来做到这一点。

【讨论】:

您不应该对此发表评论吗?我的意思是有这么好的声誉..仍然把一个班轮作为答案..!!!

以上是关于如何在以后显示状态栏通知?的主要内容,如果未能解决你的问题,请参考以下文章

如何在状态栏中显示图标而不在通知抽屉中显示通知?

停止 OneSignal 通知以显示在状态栏中

如何使用 Cordova 显示状态栏通知 - Android 和 IOS

如何在黑莓的状态栏右侧创建通知图标?

如何在右侧创建通知\状态栏图标?

Blackberry - 如何在状态栏中使用通知图标