【问题标题】:broadcastreceiver Some codes do not workbroadcastreceiver 有些代码不起作用
【发布时间】:2017-06-19 20:19:35
【问题描述】:

当我向应用程序发送数据时遇到问题,我只接收消息,但我想更改按钮形状等,但它不起作用

package com.pioneer.it.gcmpro;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class PushReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String title="P";
        String text="T";

        if(intent.getStringExtra("message")!=null)
            text=intent.getStringExtra("message");

        Intent i=new Intent(context,MainActivity.class);
        PendingIntent pi=PendingIntent.getActivity
                (context,0,i,PendingIntent.FLAG_UPDATE_CURRENT);



        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.activity_main,null);
        Button b = (Button) v.findViewById(R.id.button);

        b.setText("" + text);
        Toast.makeText(context, "" + text, Toast.LENGTH_SHORT).show();



    }
}

此行仅适用 Toast.makeText(context, "" + text, Toast.LENGTH_SHORT).show();

但这行不起作用 b.setText("" + text);

为什么?

【问题讨论】:

    标签: android


    【解决方案1】:

    您永远不会显示膨胀的布局。因此,您将布局膨胀到 RAM 中,然后为文本框设置文本,但您永远不会在任何地方显示它。这就是你看不到它的原因。

    另外,直接在BroadcastReceiver 中扩展布局是不好的做法。如果你想显示一个视图,请从你的onReceive开始一个活动。

    【讨论】:

    • 我不明白你有解决问题的办法
    • 查看@meikiem 的回答
    【解决方案2】:

    您可以拥有活动或片段,而不是在 Reciever 中膨胀布局,为该活动或片段使用该布局。

    并在该 Activity/Fragment 中将该按钮初始化并创建为公共静态。

    当您收到消息(调用 onRecieve 方法)时,您可以从此处访问该按钮(因为它是公共静态的),您可以更新该按钮的 UI。

    【讨论】:

      【解决方案3】:

      这样你不能显示你的视图, 你应该像这样开始你的活动并将你的文本作为额外的发送给它:

      你在 onReceive 中有这样的意图:

      intent.putExtra(text, your_key);
      context.startActivity(intent);
      

      并在您的 MainActivity(我假设它是您的布局名称中的 MainActivity)获取您的 Extra 并将其设置为:

      Button yourButton = (Button) v.findViewById(R.id.button);
      yourButton.setText(getIntent().getStringExtra("your_key"));
      

      【讨论】:

      • 但应用程序踢了我
      • 告诉我这里有错误 context.startActivity(in);
      • 当你想发送BroadCast时,你会给你的接收者上下文吗?
      • 你有更好的教程视频吗
      • 检查您在发送广播时提供的上下文:LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent("your_intent_key"));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多