我创建了我注册了我的主类(内广播接收器的应用Main Activity
),每当我收到我的东西BroadcastReceiver
我要更新例如我要显示一个警告框,或设置我的一些文本视图UI MainActivity
。 我收到的所有值在我的接收器,但无法对其进行设置,可以有人帮助我,让我可以更新我的UI中的BroadcastReceiver
。
我的广播接收器类是内部类MainActivity像这样的: -
public class MainActivity extends Activity {
..........
public static class NissanTabBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences shrd = context.getSharedPreferences("NissanGallery", context.MODE_WORLD_READABLE);
type = shrd.getString("type", "null");
badges = shrd.getString("badge_count", "null");
//badge_tips_text.setText(badges);
/*Editor edit = shrd.edit();
edit.remove("type");*/
Toast.makeText(context, "" + type + "\n" + badge_tips_text.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
任何帮助将很可观
谢谢
Answer 1:
我建议你使用一个处理器。
- 在活动,例如初始化处理程序:
handler = new Handler()
- 在构造函数中提供处理程序的广播接收器,以同样的方式为我做了NissanTabBroadcast以上
- 使用
post()
处理程序实例的方法中onReceive()
方法来提交更新UI了Runnable
这是最干净的解决方案,我可以想像的。
public class MainActivity extends Activity {
private MyReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new MyReceiver(new Handler()); // Create the receiver
registerReceiver(receiver, new IntentFilter("some.action")); // Register receiver
sendBroadcast(new Intent("some.action")); // Send an example Intent
}
public static class MyReceiver extends BroadcastReceiver {
private final Handler handler; // Handler used to execute code on the UI thread
public MyReceiver(Handler handler) {
this.handler = handler;
}
@Override
public void onReceive(final Context context, Intent intent) {
// Post the UI updating code to our Handler
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Toast from broadcast receiver", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Answer 2:
我的情况是由我发现了这个MainActivity.The简单的解决方案主办的一个片段来更新文本字段: -
在我的MainActivity类别检索MainActivtiy.This的运行实例是我MAinActivity
private static MainActivity mainActivityRunningInstance;
public static MainActivity getInstace(){
return mainActivityRunningInstance;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivityRunningInstance =this;
----------
}
现在,在广播reciever的onRecieve方法,获取实例并调用Update方法
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches(Intents.PROVIDER_CHANGED_ACTION)) {
String textValue="the text field value";
// the null check is for, if the activity is not running or in paused state, in my case the update was required onlyif the main activity is active or paused
if(MainActivity.getInstace()!=null)
MainActivity.getInstace().updateUI(textValue);
}
现在,我们需要运行在UIThread更新的一部分,MainActivity的updateUI方法将调用片段更新方法。
public void updateUI(final String str) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
//use findFragmentById for fragments defined in XML ((SimpleFragment)getSupportFragmentManager().findFragmentByTag(fragmentTag)).updateUI(str);
}
});
}
而最后一步是更新片段的文本字段
public void updateUI(String str){
tv_content.setText(str);
}
和宾果,它的完成。 我提到这个链接来解决我的问题。 希望它可以帮助别人。
Answer 3:
使用runOnUiThread
:
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// show alert
}
});
Answer 4:
我用意图让广播接收机知道主活动线程和所使用的消息的处理程序实例来传递消息给主要业务
我用这种机制来检查,如果广播接收器已经被注册或没有。 有时,当你动态地注册您的广播接收器,不希望把它的两倍,或者你如果广播接收器运行呈现给用户它是必要的。
主要活动:
public class Example extends Activity {
private BroadCastReceiver_example br_exemple;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private boolean running = false;
static class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
running = false;
switch (msg.what) {
case BroadCastReceiver_example.ALIVE:
running = true;
....
break;
default:
super.handleMessage(msg);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction("pl.example.CHECK_RECEIVER");
br_exemple = new BroadCastReceiver_example();
getApplicationContext().registerReceiver(br_exemple , filter); //register the Receiver
}
// call it whenever you want to check if Broadcast Receiver is running.
private void check_broadcastRunning() {
/**
* checkBroadcastHandler - the handler will start runnable which will check if Broadcast Receiver is running
*/
Handler checkBroadcastHandler = null;
/**
* checkBroadcastRunnable - the runnable which will check if Broadcast Receiver is running
*/
Runnable checkBroadcastRunnable = null;
Intent checkBroadCastState = new Intent();
checkBroadCastState .setAction("pl.example.CHECK_RECEIVER");
checkBroadCastState .putExtra("mainView", mMessenger);
this.sendBroadcast(checkBroadCastState );
Log.d(TAG,"check if broadcast is running");
checkBroadcastHandler = new Handler();
checkBroadcastRunnable = new Runnable(){
public void run(){
if (running == true) {
Log.d(TAG,"broadcast is running");
}
else {
Log.d(TAG,"broadcast is not running");
}
}
};
checkBroadcastHandler.postDelayed(checkBroadcastRunnable,100);
return;
}
.............
}
广播接收器:
public class BroadCastReceiver_example extends BroadcastReceiver {
public static final int ALIVE = 1;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
String action = intent.getAction();
if (action.equals("pl.example.CHECK_RECEIVER")) {
Log.d(TAG, "Received broadcast live checker");
Messenger mainAppMessanger = (Messenger) extras.get("mainView");
try {
mainAppMessanger.send(Message.obtain(null, ALIVE));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
.........
}
}
Answer 5:
我现在用完全不同的方法对that.Pass处理程序的实例,将其置于intent.Than在广播接收机广播接收机使用的处理程序将消息发送到您的活动类更新UI中的自定义处理程序的您onHandleMessage方法类。
create handler class like
public class MyHandler extends Handler{
onHandlerMessage(Message msg){//do whatever you want here after broadcast get fired}
}
现在使用Myhandler handler=new MyHandler();
在创建活动中全球范围内该处理对象。
现在把这个处理程序到你的意图通过putExtra
,然后通过发送此意图sendBraodcast(intent)
。
在广播接收器类由getExtras得到这个处理程序对象,并使用它下面喜欢onReceive()
方法
handler.sendEmptyMessage();
Answer 6:
在我来说,我想在我与进入SMS活动来更新我的TextView的,我做什么用putextra,然后加入所需的信息开始从广播接收器的活动:
Intent intentone = new Intent(context.getApplicationContext(), enroll.class);
intentone.putExtra("pinbody",message);
intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentone);
然后就在登记活动接收端即我中提取出的信息,使用下面的和更新的TextView的我:
Bundle extras = getIntent().getExtras();
String message = extras.getString("pinbody");
不知道是否有帮助,但肯定要带你到你想要的。
干杯!
Answer 7:
使用getter和setter方法可以很容易地解决这个问题。
只是声明一个类,如下所示。
public class DetailsGetters {
private View view;
public View getview() {
return view;
}
public void setview(View view) {
this.view = view;
}
}
在您的主要活动或片段活动,创建一个类DetailsGetters的实例。
DetailsGetters newdetailsinstance=new DetailsGetters();
Returing查看通话之前newdetailsinstance.setview(view);
在广播接收器获得视图newdetailsinstance.getview(view);
该follwing可用于从片段获取视图和使用的setText等UI更新..
有关主要活动更新UI传递的TextView和改变DeailsGetters类和TextView的创建getter和setter方法。 希望这可以帮助的人。
Answer 8:
在任何活动如何重新使用广播接收器?
考虑的情况下,
- 你想使用相同的
BroadcastReceiver
在不同的活动 - 你写
BroadcastReceiver
在一个单独的文件,要访问Activity
的方法,UI元素等
在使用接口这些案件是一个好主意。 我会解释的优点和使用情况的更多细节。 但首先,让我们来看看它是如何做。
1)创建的接口
public interface MyBroadcastListener{
public void doSomething(String value);
}
2)初始化监听器在你的广播接收器
public class MyReceiver extends BroadcastReceiver {
private MyBroadcastListener listener;
public MyReceiver(MyBroadcastListener listener){
this.listener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
listener.doSomething("Some Result");
}
}
3)实现在活动界面和覆盖的方法
public MainActivity extends AppCompatActivity implements MyBroadcastListener{
private BroadcastReceiver receiver;
@Override
public void onCreate(Bundle sis){
// Related code
receiver = new MyReceiver(this); // This is how you initialise receiver
// Register receiver etc
}
public void updateUI(String msg) {
TextView textView = (TextView) findViewById(R.id.textView);
textView .setText(msg);
}
@Override
public void doSomething(String result){
updateUI(result); // Calling method from Interface
}
}
优势和使用情况?
使用接口方法使任何活动的广播接收器独立。 让我们在今后的说,你想用这个广播接收器与另一个活动这需要从广播接收器的结果,并开始DetailActivity。
请注意,这是一个完全 不同的任务 ,但你可以使用相同的广播接收器 ,甚至没有在广播接收器内的任何代码更改。
怎么做?
简单! 实现在界面Activity
和覆盖的方法。 而已!
public ListActivity extends AppCompatActivity implements MyBroadcastListener{
// Your Activity code goes here
public void startDetailActivity(String title) {
Intent i = new Intent(ListActivity,this, DetailActivity.class);
i.putExtra("Title", title);
startActivity(i);
}
@Override
public void doSomething(String result){
startDetailActivity(String title); // Calling method from Interface
}
}
Answer 9:
我使用的处理器和它的post()方法。 相反runOnUiThread的()。 无需投语境活动。 其runOnUiThread替代()
Handler handler = new Handler();
Runnable runnable = new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
while (gameState == GameState.Playing) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000));
}
});
}
}
};
new Thread(runnable).start();
Answer 10:
你应该让广播接收机内部类,这样就可以访问所有字段更新UI。
见尼克屠夫这个格子的应用程序Plaid-尼克·布彻(Github上)
Answer 11:
获取当前日期时间及二和更新的UI通过广播接收器
package com.keshav.broadcasttest;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.keshav.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
@Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI_Runnable);
handler.postDelayed(sendUpdatesToUI_Runnable, 1000); // 1 second
}
private Runnable sendUpdatesToUI_Runnable = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 10000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("time", new Date().toLocaleString());
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI_Runnable);
super.onDestroy();
}
}
============================================
package com.keshav.broadcasttest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class BroadcastTest extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
@Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private void updateUI(Intent intent) {
String counter = intent.getStringExtra("counter");
String time = intent.getStringExtra("time");
Log.d(TAG, counter);
Log.d(TAG, time);
TextView txtDateTime = (TextView) findViewById(R.id.txtDateTime);
TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
txtDateTime.setText(time);
txtCounter.setText(counter);
}
}
=============================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout android:id="@+id/tableGPS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7px"
android:stretchColumns="1">
<TableRow
android:layout_margin="1dip">
<TextView android:layout_gravity="right"
android:text="Time:"
android:layout_marginRight="7px"
android:layout_width="130px" />
<TextView android:id="@+id/txtDateTime"
android:gravity="left"
android:layout_span="2" />
</TableRow>
<TableRow
android:layout_margin="1px">
<TextView android:layout_gravity="right"
android:text="Counter:"
android:layout_marginRight="7px"
android:layout_width="160px" />
<TextView android:id="@+id/txtCounter"
android:gravity="left" />
</TableRow>
</TableLayout>
</LinearLayout>
===========================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.keshav.broadcasttest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".BroadcastTest">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BroadcastService" />
</application>
</manifest>
文章来源: How to update UI in a BroadcastReceiver