【问题标题】:How to get title and message of notification and display on textview in new activity如何在新活动中获取通知的标题和消息并在文本视图上显示
【发布时间】:2019-06-10 16:11:58
【问题描述】:

我是 Android 新手。我已经尝试了 Stack Overflow 链接和其他网站的所有可能方法,但无法做到。

我能够从 Cloud Messaging Firebase 生成通知。但现在我想获取通知的标题和消息,并在文本视图或列表视图中的“我的购物车活动”中显示。我尝试过静态、意图和接口方法。但我无法实现它。

这是最后一年的项目演示。下面是我的代码

MyFirebaseInstanceIDService 类

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";

@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
    storeToken(refreshedToken);
}

private void storeToken(String token) {
    //saving the token on shared preferences
    SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
}
}

MyFirebaseMessagingService 类

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            sendPushNotification(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

//this method will display the notification
//We are passing the JSONObject that is received from
//firebase cloud messaging
private void sendPushNotification(JSONObject json) {
    //optionally we can display the json into log
    Log.e(TAG, "Notification JSON " + json.toString());
    try {
        //getting the json data
        JSONObject data = json.getJSONObject("data");

        //parsing json data
        String title = data.getString("title");
        String message = data.getString("message");
        String imageUrl = data.getString("image");

        //creating MyNotificationManager object
        MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());

        //creating an intent for the notification
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);

        //if there is no image
        if(imageUrl.equals("null")){
            //displaying small notification
            mNotificationManager.showSmallNotification(title, message, intent);
        }else{
            //if there is an image
            //displaying a big notification
            mNotificationManager.showBigNotification(title, message, imageUrl, intent);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

}

下面的 MyNotificationManager 类

public class MyNotificationManager {

public static final int ID_BIG_NOTIFICATION = 234;
public static final int ID_SMALL_NOTIFICATION = 235;

private Context mCtx;

public MyNotificationManager(Context mCtx) {
    this.mCtx = mCtx;
}

//the method will show a big notification with an image
//parameters are title for message title, message for message text, url of the big image and an intent that will open
//when you will tap on the notification
public void showBigNotification(String title, String message, String url, Intent intent) {
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mCtx,
                    ID_BIG_NOTIFICATION,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
    bigPictureStyle.setBigContentTitle(title);
    bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
    bigPictureStyle.bigPicture(getBitmapFromURL(url));
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx);
    Notification notification;
    notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent)
            .setContentTitle(title)
            .setStyle(bigPictureStyle)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher))
            .setContentText(message)
            .build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(ID_BIG_NOTIFICATION, notification);
}

//the method wi
//
//
// +-ll show a small notification
//parameters are title for message title, message for message text and an intent that will open
//when you will tap on the notification
public void showSmallNotification(String title, String message, Intent intent) {
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mCtx,
                    ID_SMALL_NOTIFICATION,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );


    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx);
    Notification notification;
    notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent)
            .setContentTitle(title)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher))
            .setContentText(message)
            .build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(ID_SMALL_NOTIFICATION, notification);
}

//The method will return Bitmap from an image URL
private Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
}

【问题讨论】:

    标签: android notifications


    【解决方案1】:

    您可以像这样使用 pendingIntent 将值从通知传递到活动:

    在您的通知类中:

            Intent intent = new Intent(this, YourActivity.class);
        intent.putExtra("title",title)
                .putExtra("message",message);
    
        //Create a Pending Intent like so:
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT );
    
       //add this line to your mBuilder to set the pending intent
      .setContentIntent(pendingIntent); 
    
    }
    

    在您的活动中检查 Extra 是否不为空并更新您的文本视图(可以放在 onCreate() 上):

        bundle = getIntent().getExtras();
    
        if(bundle!=null){
           for(String key : bundle.keySet()){
               if(key.equals("title"))
                   textView.setText(bundle.getString(key));
    
               else if (key.equals("message"))
                   textView2.setText(bundle.getString(key));
           }
        }
    

    更多信息可以找到here

    【讨论】:

    • 你能告诉我,我的通知管理器类中的第一个代码放在哪里吗?
    • 试试 showBigNotification(),你已经创建了一个待处理的 Intent 并将其设置为内容,你只需添加 putExtra()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多