Android通知已编程

时间:2013-07-11 13:49:50

标签: java android notifications

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

我打电话的代码是:

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());

1 个答案:

答案 0 :(得分:4)

您可以AlarmManager捆绑使用BroadcastReceiver

首先,您必须创建待处理的意图并在某处注册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毫秒数的通知。