0

我正在尝试在屏幕上显示进度条的屏幕(例如活动 A)上工作,并且我需要在进度条运行时将广播发送到不同的活动(活动 B)broadcastReceiver。如果活动 B 中的功能完成,它将显示回活动 A。

现在我在这样的工作线程中运行进度条并使用处理程序(Looper.getMainLooper())发送本地广播:

final Context context = Activity.this.getApplicationContext();
new Thread(new Runnable() {
  @Override
  public void run() {
     while (progressBar.getProgress() != 100) {
        try {
            progressBar.incrementProgressBy(2);
            Thread.currentThread().sleep(100);
        } catch (InterruptedException ie) {
            Log.e(LOG_TAG, "Interrupted exception in progress bar: " + ie);
        }
        if (progressBar.getProgress() == 10) {
           Handler handler = new Handler(Looper.getMainLooper());
           handler.post(new Runnable() {
               @Override
               public void run() {
                   // model is a parameter which I want to send using intents
                   Intent intent = new Intent("new_device");
                   intent.putExtra("device", model);
                           LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
               }
           });
        }
     }
  }
}).start(); 

但它不起作用。其他活动未接收到广播。我知道广播应该在 UI 线程上完成,如果我在 onResume() 或 onCreate() 方法中完成它工作正常。但是当我在线程内的处理程序中使用它时(在 onCreate() 内)它不起作用。

我做错了什么还是有其他方法可以做到这一点?

编辑

我在活动 B 中收到我的意图,如下所示:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Model model = (Model) intent.getSerializableExtra("device");
            onConnectDevice(model.getDevice());
        }
    };
4

2 回答 2

0

尝试在线程内使用活动的 runonuithread 方法

于 2016-01-26T19:19:36.370 回答
0

我相信您的问题在于progressBar.incrementProgress(),因为您正试图从 UI 线程外部更改 UI 元素。保持你的结构,你可以尝试这样的事情:

final Handler handler = new Handler(Looper.getMainLooper());
final Thread thread = new Thread(new Runnable() {
  @Override
  public void run() {
     while (progressBar.getProgress() != 100) {
        try {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    progressBar.incrementProgressBy(2);
                }
            });
            Thread.sleep(100);

        } catch (InterruptedException ie) {

        }
        if (progressBar.getProgress() == 10) {
           handler.post(new Runnable() {
               @Override
               public void run() {
                   Intent intent = new Intent("new_device");
                   intent.putExtra("device", model);
                   Context context = progressBar.getContext();
                   LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
               }
           });
        }
     }
  }
}); 

thread.start();

还要确保10曾经达到过(例如,序列可能是1-3-5-7-9-11但你不会得到任何东西。

我还从进度条中获取了上下文,您不需要先获取它。

有比这更好的解决方案,但我只是保留了你的结构。

于 2016-01-26T19:44:29.773 回答