2016-06-10 22 views
0

我在不同的类中有我的MainActivity,ConnectThread和ConnectedThread。Android将Thread中的数据从单独的java类发送到UI线程

我正在侦听来自ConnectedThread中Bluetoothmodule的大量数据。

我有Broadcastreciever在我的主线程像这样:

final BroadcastReceiver bReciever = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     String message = intent.getStringExtra("data"); 

     if(BluetoothDevice.ACTION_FOUND.equals(action)){    // Bluetooth discovery result found 
      BTArrayAdapter_found_filter.clear();    //Remove Duplicates 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      BTArrayAdapter_found.add(device.getName()+"\n"+device.getAddress()); 
      BTArrayAdapter_found.notifyDataSetChanged(); 

      for(int i = 0;i< BTArrayAdapter_found.getCount();i++){  // Iterate original Arrayadapter for filtering 
       String filter = "RCD"; 

       if(BTArrayAdapter_found.getItem(i).toString().toLowerCase().contains(filter.toLowerCase())){ 

        BTArrayAdapter_found_filter.add(BTArrayAdapter_found.getItem(i)); 
        BTArrayAdapter_found_filter.notifyDataSetChanged(); 


       } 
      } 
     } 
     if(message!=null) 
     textview_terminal.setText(message); 


    } 
}; 

我会听消息,并把它传递给一个TextView。另一个只是蓝牙部分,这里不相关。

我有这样的ConnectedThread的意图:

public void sendData(){ 
    Intent sendDataIntent = new Intent("SendData_EVENT"); 
    sendDataIntent.putExtra("data",passData); 
    LocalBroadcastManager.getInstance().sendBroadcast(sendDataIntent); 

} 

但由于该线程有一个活动没有联系的Broadcastmanagers的getInstance不起作用。

我试图用这个例子:LINK

我有很多的例子来看看,我不认为处理程序是对我最好的方法。

我怎样才能成功地从我的后台线程发送数据?

通过发送发送getApplicationContext()来ConnectedThread构造函数和传递,为的getInstance(上下文)解决

+0

你注册解决** BroadcastReceiver **? – Alexander

+0

是的,我有LocalBroadcastManager.getInstance(this).registerReceiver(bReciever,new IntentFilter(“SendData_EVENT”));我的问题是LocalBroadcastmanager.getinstante()我不能在那里放置任何参数,因为ConnectedThread只是一个没有上下文或活动的线程,如果我理解正确的话。 – VikingPingvin

+0

可能是您可以将逻辑从**线程**移动到**服务**。它可以帮助你。不要忘记服务在UI线程中默认工作。 – Alexander

回答

0

通过发送发送getApplicationContext()来ConnectedThread构造函数和传递,为的getInstance(上下文)

相关问题