繁体   English   中英

Android库中的本地通知

[英]Local Notifications in an Android Library

我在这里写这篇文章是因为我面临着一个问题,即使经过许多研究和尝试,我也无法解决。

我目前正在开发一个仅包含Java类和片段的Android库。 问题是我需要向用户发送本地通知,单击通知应将用户发送回他所在的活动。 在这一点上,我的图书馆发送通知就好了。 但是单击通知没有任何动作。

在我的通知接收器类(扩展了BroadcastReceiver类)中,当出现通知时,我创建了一个Pending Intent,但是我不知道我可以作为参数将用户发送到活动中。 我尝试使用意图过滤器,但没有任何结果

那么如何让通知将用户发送回应用程序? 最好的办法是,如果我能够让通知将用户发送回创建通知的活动(但这是一个片段,那么...)

在一个普通的应用程序中,我打算将用户发送回活动类,但是我的库只需要有片段。

也许没有问题,而且解决方案很简单,因为我是通知新手

如果有人在这里有一个想法,谢谢您的帮助! :D

如果我的问题不清楚(例如我的英语不好),不要犹豫,问我添加信息^^

**从4月29日开始编辑:**我设法通过使用以下方法将我班级的规范名称提供给我的广播待定意图来实现:

mContext.getClass().getCanonicalName();

一旦进入广播接收器类,我只需从发送类的名称中获取该类:

Class<?> activityClass = null;
    try {
       activityClass = Class.forName(stringSourceClass);
    } catch (ClassNotFoundException e) {
       e.printStackTrace();
   }

看看下面的代码...

public BroadcastReceiver batteryReceiver = new BroadcastReceiver() {

        @Override
          public void onReceive(Context context, Intent intent) {
              try {
                  String title = context.getString(R.string.app_name);

                  Intent intent1 = new Intent(context, YourActivity.class);

                  PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),1,intent1,PendingIntent.FLAG_UPDATE_CURRENT);

                  NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                          .setSmallIcon(R.drawable.ic_launcher)
                          .setContentTitle(title)
                          .setContentText("Hello")
                          .setAutoCancel(false)
                          .setContentIntent(pendingIntent);

                  NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                  notificationManager.notify(1, notificationBuilder.build());
              } catch (Exception e) {
              }
          }
      };

检查建立通知页面:

 Intent resultIntent = new Intent(this, ResultActivity.class); ... // Because clicking the notification opens a new ("special") activity, there's // no need to create an artificial back stack. PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT ); 

只需将您的活动放入resultIntent

如何使通知将用户发送回应用程序?

那很简单:
1.在为未决的意图创建意图时,调用addAction(“ action_name”)方法;
2.在活动中,您想要调用(在清单文件中)intent-filter标记内,添加<action android:name="action_name>.现在,当您的通知尝试启动活动时,它将向系统发送意图消息,该消息将使用采取适当措施并启动它。
PS动作名称对于每个应用程序必须唯一

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM