无法从Service类中的Activity发送中获取String

时间:2017-01-05 08:26:26

标签: android android-intent android-activity firebase firebase-cloud-messaging

我从Service类发送String,将FirebaseMessagingService扩展为MainActivity.java

但是无法将其添加到MainActivity.java中只获取null,我犯了错误,很多时候我在我的程序中使用了Intent但是这次没有获取数据。

MyFirebaseMessagingService.java:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FirebaseMessageService";
    Bitmap bitmap;
    String strMessage = "", strImageURI = "", strTrueOrFalse = "";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        strMessage = remoteMessage.getData().get("message");

        strImageURI = remoteMessage.getData().get("image");

        strTrueOrFalse = remoteMessage.getData().get("PushNotifyActivity");

        bitmap = getBitmapfromUrl(strImageURI);

        sendNotification(strMessage, bitmap, strTrueOrFalse);

    }


    private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {

        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        notificationIntent.putExtra("NotificationMessage", "Testing");
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setLargeIcon(image)/*Notification icon image*/
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(messageBody)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }

    public Bitmap getBitmapfromUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            return bitmap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;

        }
    }
}

注意:为了测试字符串传递与否,我已经给出了"测试"作为默认的String要获取,但不幸的是,即使我在MainActivity.java中也没有相同。

MainActivity.java:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    onNewIntent(getIntent());

    subscribeToPushService();

    }

private void subscribeToPushService() {

    FirebaseMessaging.getInstance().subscribeToTopic("news");

    String token = FirebaseInstanceId.getInstance().getToken();

}

@Override
public void onNewIntent(Intent intent) {
    dbManager = new DBManager(MainActivity.this);
    dbManager.open();

    String msg = intent.getStringExtra("NotificationMessage");
    Toast.makeText(MainActivity.this, "MSG: "+msg, Toast.LENGTH_LONG).show();

    dbManager.insert(msg, "");

}

问题:为什么我得到的是null而不是String"测试"在MainActivity.java中

2 个答案:

答案 0 :(得分:2)

刚刚从Android Source确认了Intent类。如果您使用Intent.PutExtra(String,String)直接放置数据或使用Intent.putExtras(bundle)之类的包,似乎没有区别,您也可以检索。

所以我认为唯一的问题是PendingIntent.FLAG_ONE_SHOT上的标志,根据它所说的文件,

  

表示此PendingIntent只能使用一次的标志。用于getActivity(Context,int,Intent,int),getBroadcast(Context,int,Intent,int)和getService(Context,int,Intent,int)。   如果设置,在调用send()之后,它将自动被取消,并且将来尝试发送它将失败。

所以我认为这是问题所在。

https://developer.android.com/reference/android/app/PendingIntent.html#FLAG_ONE_SHOT

答案 1 :(得分:0)

PendingIntent中传递更新当前标志,如下所示:

 PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

将其从意图中删除:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

并检查天气,您的信息是messageBody可变

你得到了Bundle而不是String.Change你的newIntent代码像这样:

 @Override
public void onNewIntent(Intent intent) {
    Toast.makeText(MainActivity.this, "Intent:CALLED", Toast.LENGTH_LONG).show();

    if (intent!= null) {
        Toast.makeText(MainActivity.this, "Extras found", Toast.LENGTH_LONG).show();

        String msg = intent.getStringExtra("NotificationMessage");
        Toast.makeText(MainActivity.this, "Open: "+msg, Toast.LENGTH_LONG).show();

    }
}