如何从类FirebaseMessagingService更改MainActivity中的TextView txtView

时间:2018-06-28 11:13:58

标签: android firebase textview firebase-cloud-messaging main-activity

我进行了研究,但没有成功。任何人都可以帮我如何从类TextView txtView中更改MainActivity中的FirebaseMessagingService。该程序似乎没有错误,但是在Firebase控制台之后,该应用程序被txt.setText(a)完全关闭(破坏);

MainActivity.java:

package com.islk.gcmexample;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    ListView listView ;
    ArrayAdapter<String> adapter;
    ArrayList<String> arrayList;
    public static Context contextA;
    private static final String TAG = "MainActivity";

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

        TextView txtView = (TextView) findViewById(R.id.textView);
        txtView.setText("Hello i1");

        listView = (ListView) findViewById(R.id.list);
        String[] values = new String[] { "Android List View",
            "Adapter implementation",
            "Simple List View In Android",
            "Create List View Android",
            "Android Example",
            "List View Source Code",
            "List View Array Adapter",
            "Android Example List View"
        };

        arrayList = new ArrayList<>(Arrays.asList(values));
        adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, arrayList);
        listView.setAdapter(adapter);
        arrayList.add("iSLK");
        adapter.notifyDataSetChanged();

        setNotificationData(getIntent().getExtras());

        Utils.showToast(MainActivity.this, "FB: hello");

        Button btnShowToken = (Button) findViewById(R.id.button_show_token);
        btnShowToken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String token = FirebaseInstanceId.getInstance().getToken();
                Log.d(TAG, "Token: " + token);
                listView.setAdapter(null);
                Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
                jano();
            }
        });

    }

    private void jano(){
        TextView txtView = (TextView) findViewById(R.id.textView);
        txtView.setText("Hello i2");
    }





}

FirebaseMessagingService.java:

package com.islk.gcmexample;

import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import com.google.firebase.messaging.RemoteMessage;
import static com.islk.gcmexample.MainActivity.contextA;

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
    private static final String TAG = "MyFirebaseMsgService";

    TextView txt = (TextView) ((Activity)contextA).findViewById(R.id.textView);

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "FB: From: " + remoteMessage.getFrom());
        sendNotification(remoteMessage);

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

            if (/* Check if data needs to be processed by long running job */ true) {

            } else {

            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "FB: Message Notification Body: " + remoteMessage.getNotification().getBody());
        }
    }

    private void sendNotification(RemoteMessage remoteMessage) {
        setTextViewToModify("Hello i3");
    }

    public void setTextViewToModify (String a){
        txt.setText(a);

    }
}

MyFirebaseInstanceIDService.java:

package com.islk.gcmexample;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final  String TAG = "MyFirebaseInsIDService";

    @Override
    public void onTokenRefresh() {
        //Get update token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "New Token :" + refreshedToken);

        //sendRegistrationToServer(refreshedToken);


        // You can save the token into third party server to do anything you want
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_show_token"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Token and Clear Alarms EVENTS"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="2dp" />

    <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="50dp" >
    </ListView>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        tools:layout_editor_absoluteY="16dp" />


</android.support.constraint.ConstraintLayout>

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用LocalBroadcastManager将服务中的任何值发送到主要活动。

Intent intent = new Intent("filter_string");
   intent.putExtra("key", "My Data");
   // put your all data using put extra 

   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

在您的MainActivity中

@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
      lbm.registerReceiver(receiver, new IntentFilter("filter_string"));
  }

  public BroadcastReceiver receiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          if (intent != null) {
              String str = intent.getStringExtra("key");

          }
      }
  };

Hopefully this will solve your problem.