如何在新活动中获取通知的标题和消息并在textview上显示

时间:2019-06-10 16:11:58

标签: android notifications

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

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

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

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;
    }
}
}

1 个答案:

答案 0 :(得分:0)

您可以像下面这样使用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是否为null并更新您的文本视图(可以放在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