从处理程序的TextView上的InputStream打印字符串

时间:2014-01-18 21:05:53

标签: java android textview handler

我希望我的TextView LineHunt1每次在InputStream上都有更新,在收到MSG消息后由mHandler处理。来自流的正确数据显示在logcat中,但TextView上没有显示任何内容。我尝试了很多不同的方法,但都没有。

这是我的代码:

public class MainActivity extends Activity {

public static final int CONNECTION_SUCCESSFUL = 1;
protected static final int CONNECTION_FAILED = 0;
protected static final int DISCONNECTED = 2;
protected static final int MSG = 3;
public boolean connected=false;

static Handler mHandler;
Activity mActivity;
static String data="1";
String message="da4o";
static TextView LineHunt1;
SeekBar LRseek;
TextView LRprogress;

public BluetoothAdapter BTadapter = BluetoothAdapter.getDefaultAdapter();
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
ConnectThread connect;
ConnectedThread IOthread;
BluetoothDevice device;
BluetoothSocket socket;
String address = "20:13:06:14:02:72";

 float discrete=0; 
 float start=0; 
 float end=100; 
 float start_pos=50; 
 int start_position=50;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);



    mActivity = this;

    ImageView right = (ImageView) findViewById(R.id.right);
    ImageView left = (ImageView) findViewById(R.id.left);
    ImageView up = (ImageView) findViewById(R.id.up);
    ImageView down = (ImageView) findViewById(R.id.down);

    LRseek = (SeekBar) findViewById(R.id.LRseek);
    LRprogress = (TextView) findViewById(R.id.LRprogress);


mHandler = new Handler(){

        public void handleMessage(Message msg){
            super.handleMessage(msg);



            switch(msg.what){

            case CONNECTION_SUCCESSFUL:
                 Toast.makeText(getApplicationContext(), "Zariadenie pripojené", Toast.LENGTH_SHORT).show();
                 connected=true;
                 break;

            case CONNECTION_FAILED: Toast.makeText(getApplicationContext(),"Nepodarilo sa pripojiť" , Toast.LENGTH_SHORT).show();
                 connected=false;
                 break;

            case DISCONNECTED: Toast.makeText(getApplicationContext(), "Zariadenie bolo odpojené", Toast.LENGTH_SHORT).show();
                 connected=false; 
                 break;

            case MSG: setData((String) msg.obj);
                 if(data.contains("[B")){break;}
                 else {

                     mActivity.runOnUiThread(new Runnable() {
                            public void run() {
                                LineHunt1 = (TextView) findViewById(R.id.LineHunt1);
                                LineHunt1.setText(data);
                            }
                        });

                     Log.d("INPUT",data);
                     }
                 break;
            }
        }
    };





    LRseek.setProgress(start_position);
    LRseek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { 


        @Override 
        public void onStopTrackingTouch(SeekBar seekBar) { 

            LRseek.setProgress(50);
        } 

        @Override 
        public void onStartTrackingTouch(SeekBar seekBar) { 
            // TODO Auto-generated method stub 

        } 

        @Override 
        public void onProgressChanged(SeekBar seekBar, int progress,boolean         fromUser) { 
            // TODO Auto-generated method stub 
            // To convert it as discrete value 

            String seekProgress = "" + LRseek.getProgress();
            LRprogress.setText(seekProgress);
            send("LR " + seekProgress);
        } 
    }); 






    right.setOnTouchListener(new OnTouchListener(){

        @Override
        public boolean onTouch(View arg, MotionEvent event)
        {   
            String string;
            TextView tRight = (TextView) findViewById(R.id.tRight);
            string = arg.getTag().toString();
            switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                tRight.setText(string);
                send("r");
                break;

            case MotionEvent.ACTION_UP:
                tRight.setText("release");
                send("R");
                break;

            }
         return true;
        }



   });
     left.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View arg, MotionEvent event)
            {
                String string;
                TextView tLeft = (TextView) findViewById(R.id.tLeft);
                string = arg.getTag().toString();
                switch(event.getAction()){
                case MotionEvent.ACTION_DOWN :

                    tLeft.setText(string);
                    send("l");
                    break;

                case MotionEvent.ACTION_UP:
                    tLeft.setText("release");
                    send("L");
                    break;
                }
             return true;
            }



       });
     up.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View arg, MotionEvent event)
            {
                String string;
                TextView tUp = (TextView) findViewById(R.id.tUp);
                string = arg.getTag().toString();
                switch(event.getAction()){
                case MotionEvent.ACTION_DOWN :

                    tUp.setText(string);
                    send("f");
                    break;

                case MotionEvent.ACTION_UP:

                    tUp.setText("release");
                    send("F");
                    break;
                }
             return true;
            }



       });
     down.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View arg, MotionEvent event)
            {
                String string;
                TextView tDown = (TextView) findViewById(R.id.tDown);
                string = arg.getTag().toString();
                switch(event.getAction()){
                case MotionEvent.ACTION_DOWN :
                    tDown.setText(string);
                    send("b");
                    break;

                case MotionEvent.ACTION_UP:
                    tDown.setText("release");
                    send("B");
                    break;
                }
             return true;
            }



       });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}





public void send(String st){
if(connected)IOthread.write(st);
}   


public void connect(View v)  {



if (!BTadapter.isEnabled()) {


Intent enableIntent = new
            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableIntent);
        }

if(BTadapter.isEnabled()){

    if(connected){
       connect.cancel();
       Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();

        }


    if(!connected){                 
        Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_SHORT).show();
        device =  BTadapter.getRemoteDevice(address);
        connect = new ConnectThread(device);
        IOthread = new ConnectedThread(connect.mmSocket);

        connect.run();
        //IOthread.run();

            }}



}

public void Irun(View v)
{
IOthread.start();

} 

private class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    mmDevice = device;
    //Log.d("masaker",device.getUuids().toString());
    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        tmp =  mmDevice.createRfcommSocketToServiceRecord(MY_UUID);

    } catch (IOException e) {Log.d("lager","ta co"); }
    mmSocket = tmp;
}

public void run() {
    // Cancel discovery because it will slow down the connection
    BTadapter.cancelDiscovery();

    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception

        mmSocket.connect();

    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        try {
            mmSocket.close();

        } catch (IOException closeException) { 

        }


        // mHandler.obtainMessage(CONNECTION_FAILED, mmSocket).sendToTarget();
        return;
    }

    // Do work to manage the connection (in a separate thread)
    //manageConnectedSocket(mmSocket);
    mHandler.obtainMessage(CONNECTION_SUCCESSFUL, mmSocket).sendToTarget();
}



/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
    try {
        mmSocket.close();
        mHandler.obtainMessage(DISCONNECTED).sendToTarget();
    } catch (IOException e) { }
}
}

private class ConnectedThread extends Thread {


 /*   private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;*/
BluetoothSocket mmSocket;
InputStream mmInStream;
OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        OutputStream tmpOut = null;
        InputStream tmpIn = null;
        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read();

                mHandler.obtainMessage(MSG, bytes, -1, buffer.toString()).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }


 public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }

 public void write(String  strings) {
        try {
            mmOutStream.write(strings.getBytes());
            Log.d("", strings);
        } catch (IOException e) { Log.d("ERR_OUT", "FEJL");}
    }
 }

0 个答案:

没有答案