保留BroadcastReceiver所做的更改

时间:2019-02-21 22:10:28

标签: java android android-activity textview broadcastreceiver

我现在被困住了:

 private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

            Bundle bundle = intent.getExtras();

            String number = bundle.getString("Time");
            GameTime.setText("" +number + " hours");

    }
};

在另一个Activity中,当按下一个Button时,MainActivity获得的是一个int。 每当我打开活动时,都看不到其中带有number变量的GameTime TextView。

我知道OnReceive方法是可行的,因为我在其中添加了一个吐司,并且在从另一个Activity发送int之后我可以看到该吐司。 更改“活动”时如何保留对TextView所做的更改?

谢谢。

1 个答案:

答案 0 :(得分:0)

一种方式:

在活动中定义一个接口,并在活动中实现该接口,并将其引用传递给另一个类,并在需要时调用该引用。

示例:

a)创建一个界面

public interface MyBroadcastListener{
 public void doSomething(String result);
}

b)初始化BroadCastReceiver

public class TestNotifAlarm extends BroadcastReceiver {
private MyBroadcastListener listener;
@Override
public void onReceive(Context context, Intent intent) {
    listener = (MyBroadcastListener)context;
    listener.doSomething("Some Result");
}
}

c)在“活动”中实现界面

public YourActivity extends AppCompatActivity implements MyBroadcastListener{
// Your Activity code 
public void updateTheTextView(String t) {
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(t);
}
@Override
public void doSomething(String result){
     updateTheTextView(result);          // Calling method from Interface
}
}

另一种方式:

a)将Receiver放入Activity类中

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
            textView.setText(intent.getStringExtra("extra"));
    }
};

b)注册BroadCastReceiver

registerReceiver(broadcastReceiver , new IntentFilter("trigger_broadcust"));

c)呼叫sendBroadcast

Intent intent = new Intent("trigger_broadcust");
intent.putStringExtra("extra", "data");
sendBroadcast(intent);