【问题标题】:How to Pass data from a service to Main activity in Java如何将数据从服务传递到 Java 中的主要活动
【发布时间】:2021-07-10 22:57:31
【问题描述】:

目的是让通知显示为通知,并且通知的内容也显示在使用 firebase 的主要活动上。我尝试过使用意图,但它不起作用。任何帮助将不胜感激。

这里是发件人代码 (MyfirebaseMessagingService)

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Bundle;
import android.widget.TextView ;
 import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
     


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

        String dodo = "Kwifo";
        String message = "Wan Ma bu";
         /*  String title = remoteMessage.getData().get("message").toString() ;
           String message = remoteMessage.getData().get("data").toString() ;*/
        //   String title1 = remoteMessage.getData().get("title").toString();

        Intent intent = new Intent(this, MyFirebaseMessagingService.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("data",dodo);   //i will love to send data to the MainActivity
        intent.putExtra("message",message);
        startActivity(intent);




    }
      if (remoteMessage.getNotification() != null) {

    Log.d(TAG, "Message Body: " + remoteMessage.getNotification().getBody());
          String msg = remoteMessage.getNotification().getBody();
         Toast.makeText(MyFirebaseMessagingService.this, msg, Toast.LENGTH_SHORT).show();



    }
    Notification notification = new NotificationCompat.Builder(this)

            .setContentTitle(remoteMessage.getNotification().getTitle())
            .setContentText(remoteMessage.getNotification().getBody())
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();




 NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
    manager.notify(123, notification);

}


}

这里是接收器代码(MainActivity)

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.TextView ;
import android.app.PendingIntent ;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.gson.Gson;

import retrofit2.Call;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";
public static final String TOPIC = "/topics/deals";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    




    if (getIntent().getExtras() != null) {
                 for (String data : getIntent().getExtras().keySet()) {
 String title = getIntent().getExtras().getString("data"); //from MyFirebaseMessagingService
         // String content = getIntent().getExtras().getString("message","Default message");
                                    //Log.d(TAG, "Key: " + Message + " Value: " + title);

                                 //   String  title =getIntent().getStringExtra("data");
                                    String  content =getIntent().getStringExtra("message");

                                    TextView tvNotify = findViewById(R.id.tradeidea) ;
                                    tvNotify.setText(title) ;
                     // tvNotify.setText( "Key: " + title + " Value: " + content) ;
              Toast.makeText(MainActivity.this,   content,Toast.LENGTH_SHORT).show();


                                }
                            } 



    FirebaseMessaging.getInstance().subscribeToTopic(TOPIC)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    String msg = ("Ready to recieve Trading Data");
                    if (!task.isSuccessful()) {
                        msg = getString(R.string.msg_subscribe_failed);
                    }
                    Log.d(TAG, msg);
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
            });





         }





 }

【问题讨论】:

  • 尝试使用类似here的BroadcastReceiver
  • 为什么Intent intent = new Intent(this, MyFirebaseMessagingService.class);,不应该去你想要的活动吗?

标签: java android android-intent


【解决方案1】:

MainActivity.java -- 活动

PhoneStateReceiver.java -- 后台服务

MainActivity.java

public class MainActivity extends Activity {

Context context;
BroadcastReceiver updateUIReciver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;

    IntentFilter filter = new IntentFilter();
    filter.addAction("service.to.activity.transfer");
    updateUIReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //UI update here
            if (intent != null)
                Toast.makeText(context, intent.getStringExtra("number").toString(), Toast.LENGTH_LONG).show();
        }
    };
    registerReceiver(updateUIReciver, filter);
}}

PhoneStateReceiver.java

public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    try {
        System.out.println("Receiver start");
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            Intent local = new Intent();
            local.setAction("service.to.activity.transfer");
            local.putExtra("number", incomingNumber);
            context.sendBroadcast(local);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}}

希望这篇文章对你有用

【讨论】:

  • Zafar Iqbal,请你帮我把你的代码放到上下文中,我觉得很难理解。
【解决方案2】:

尝试使用捆绑包。

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    ...
    Intent intent = new Intent(this, MyFirebaseMessagingService.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Important.
    Bundle bundle = new Bundle();
    bundle.putString("data", doto);
    bundle.putString("message", message);
    //intent.putExtras(bundle);
    intent.putExtra(getPackageName() + ".MyBundle", bundle);
    startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Bundle bundle = getIntent().getExtras();
    Bundle bundle = getIntent().getBundleExtra(getPackageName() + ".MyBundle");
    String dodo = bundle.getString("data");
    String message = bundle.getString("message");
    
    //Do something...
    Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}

【讨论】:

  • 我试过了,但没用。它会启动主要活动,但不会将数据发送到 tvNotify.setText()
  • 我尝试了那里的 cmets 提供的解决方案,但无济于事。我仍然得到空值。有些解决方案甚至无法编译......我感觉自己要朝自己的脑袋开枪。
  • 吐司是空的。
  • 我刚刚做了,它使应用程序崩溃了。
  • @NdeKong 你永远不应该想开枪。耐心是开发人员的最高技能。有时您必须取消所有假设并一一证明。通常这是通过断点和调试器工具以及使用 logcat 来完成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多