2

我已经构建了一个简单的应用程序,当我单击按钮时会显示通知。如何显示编程通知?

我调用的代码是:

Notification.Builder builder = new Notification.Builder(this)
    .setTicker("Notifica")
    .setSmallIcon(android.R.drawable.stat_notify_chat)
    .setContentTitle("Notifica")
    .setContentText("Hai una notifica!")
    .setAutoCancel(true)
    .setContentIntent(PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0));
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.notify("interstitial_tag", 1, builder.build());
4

1 回答 1

4

您可以将AlarmManagerBroadcastReceiver捆绑使用。

首先,您必须创建待处理的意图并将其注册到某个地方的AlarmManager.set。然后创建您的广播接收器并接收该意图。

更新:这是我承诺的代码。

首先,您需要创建广播接收器。

public class NotifyHandlerReceiver extends BroadcastReceiver {

    public static final String ACTION = "me.pepyakin.defferednotify.action.NOTIFY";

    public void onReceive(Context context, Intent intent) {
        if (ACTION.equals(intent.getAction())) {
             Notification.Builder builder = new Notification.Builder(context)
                .setTicker("Notifica")
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentTitle("Notifica")
                .setContentText("Hai una notifica!")
                .setAutoCancel(true)
                .setContentIntent(PendingIntent.getActivity(context, 0,
                        new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0));

            NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            nm.notify("interstitial_tag", 1, builder.build());
       }
    }
}

这是您可以处理通知请求的广播接收器。为了它可以工作,你必须在你的AndroidManifest.xml. 如果您不这样做,Android 将无法处理您的通知请求。

只需将<receiver/>声明添加到您的<application/>标签中。

    <receiver android:name=".NotifyHandlerReceiver">
        <intent-filter>
            <action android:name="me.pepyakin.defferednotify.action.NOTIFY" />
        </intent-filter>
    </receiver>

请注意,该动作名称与中定义的完全相同NotifyHandlerReceiver.ACTION

然后你可以使用这个代码

public static final int REQUEST_CODE_NOTIFY = 1;

public void scheduleNotification(long delayTimeMs) {
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    long currentTimeMs = SystemClock.elapsedRealtime();

    PendingIntent pendingNotifyIntent = PendingIntent.getBroadcast(
            this,
            REQUEST_CODE_NOTIFY,
            new Intent(NotifyHandlerReceiver.ACTION),
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, currentTimeMs + delayTimeMs, pendingNotifyIntent);
}

从您的活动开始延迟delayTimeMs几毫秒的通知。

于 2013-07-11T13:53:27.997 回答