Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从FirebaseMessagingService类更改MainActivity中的TextView txtView_Android_Firebase_Textview_Firebase Cloud Messaging_Main Activity - Fatal编程技术网

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

Android 如何从FirebaseMessagingService类更改MainActivity中的TextView txtView,android,firebase,textview,firebase-cloud-messaging,main-activity,Android,Firebase,Textview,Firebase Cloud Messaging,Main Activity,我做过研究,但没有成功。有人能告诉我如何从类FirebaseMessagingService更改MainActivity中的TextView txtView吗。程序似乎没有错误,但在Firebase控制台之后,应用程序立即被txt.setText(a)关闭(销毁) MainActivity.java: package com.islk.gcmexample; import android.content.Context; import android.support.v7.app.AppCom

我做过研究,但没有成功。有人能告诉我如何从类
FirebaseMessagingService
更改MainActivity中的
TextView txtView
吗。程序似乎没有错误,但在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");
    }





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

    }
}
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
    }
}
<?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>
myFirebaseInstancedService.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");
    }





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

    }
}
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
    }
}
<?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>
activity\u main.xml:

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





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

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


提前感谢。

您可以使用LocalBroadcastManager将任何值从服务发送到主活动

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

   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
在你的主要活动中

@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.

你想要实现什么?是否有任何内容写入错误日志?能否将错误日志粘贴到此处。您的
onMessageReceived
运行在不同的线程上,无法访问UI。您可以使用本地广播将消息发送到UI线程并在那里执行更新。见弗兰克:谢谢你,我已经按照你的建议使用了本地广播,现在正在运行。很好,再次感谢各位。更改id无效=始终销毁appare是否要将值设置为textview?没错,只需在2-ns步骤将remoteMessage传递到arrayList时从FirebaseMessagingService.java更改textview即可。添加(“iSLK”);从FirebaseMessagingService.javaI开始,我已经按照您的建议使用了本地广播,现在它正在工作。是的,本地广播是最好的解决方案,让我也更新我的答案。