在通知android

时间:2017-04-09 06:23:58

标签: android notifications alarmmanager

我已经完成了几个stackoverflow的答案,还有一些教程可以在android中的通知中添加动作按钮。我正在使用NotificationCompat来创建通知,并且通知有两个操作按钮。因为,操作按钮中的第三个参数是一个挂起的意图,我很好奇是否有办法将click事件方法直接附加到操作按钮。请查找BroadcastReceiver的代码以及我创建通知的位置。

AlarmManager:

 notifyMed.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(mContext, "Notify clicked", Toast.LENGTH_LONG).show();
                Long alertTime = new GregorianCalendar().getTimeInMillis()+5*1000;

                Intent alertIntent = new Intent(mContext, AlertReceiver.class);

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

                alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime ,
                        PendingIntent.getBroadcast(mContext , 1 , alertIntent , PendingIntent.FLAG_UPDATE_CURRENT));

                return false;
            }
        });

以下是BroadCastReceiver的代码:

广播接收器:

public class AlertReceiver extends BroadcastReceiver {

int notificationId = 6324;

@Override
public void onReceive(Context context, Intent intent) {


    createNotification(context, "Medication Notification" , "It is time to take your medication", "Message From PHMS");
}

public void createNotification(Context context, String msgTitle, String msgContentText, String msgTicker){

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MedicationNotification.class) , 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.cardiogram)
            .setContentTitle(msgTitle)
            .setTicker(msgTicker)
            .setContentText(msgContentText);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    mBuilder.setSound(uri);

    long[] vibrate = {500,1000};
    mBuilder.setVibrate(vibrate);


    mBuilder.addAction(R.drawable.ic_snooze_black_24dp,"Snooze", pendingIntent);
    mBuilder.addAction(R.drawable.ic_check_circle_black_24dp,"Take Medication", pendingIntent);

    mBuilder.setContentIntent(pendingIntent);

    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);

    mBuilder.setAutoCancel(true);

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

    mNotificationManager.notify(notificationId, mBuilder.build());
}

}

这是androidManifest.xml的代码

<receiver android:name=".activities.AlertReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

    <activity android:name=".activities.MedicationNotification"></activity>
</application>

我只想处理通知操作按钮上的点击事件。通知正确生成。请帮助!

0 个答案:

没有答案