微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数据显示在 logcat 上,但我无法在我的 android 上显示它

如何解决数据显示在 logcat 上,但我无法在我的 android 上显示它

所以,我试图从连接到我的 arduino Uno 的 HC05 接收数据,从温度传感器 DHT11 接收值。我制作了一个应用程序,所以我可以获得这些值,但它们只显示在 logcat 上,而不显示在我的 android 屏幕上。

这是我的 ShowInfoActivity,我在其中激活 BT 并允许我显示不同的 BT 设备。

package com.example.temperaturaehumidade;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.broadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.UUID;


public class ShowInfoActivity extends AppCompatActivity{


    private static final String TAG = "ShowInfoActivity";

    private Button btndiscoverability;
    private Button btnSearch;
    private Button btnONOFF;
    private Button btnConnect;
    private ListView listView;

    BluetoothAdapter mBluetoothAdapter;
    Button btnEnabledisable_discoverable;

    BluetoothConnection mBluetoothConnection;

    TextView etSend;

    private static final UUID MY_UUID_INSECURE =
            UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    BluetoothDevice mBTDevice;

    public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();

    public Devicelistadapter mDevicelistadapter;

    ListView lvNewDevices;





    // Create a broadcastReceiver for ACTION_FOUND
    private final broadcastReceiver mbroadcastReceiver1 = new broadcastReceiver() {
        public void onReceive(Context context,Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,mBluetoothAdapter.ERROR);

                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        Log.d(TAG,"onReceive: STATE OFF");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Log.d(TAG,"mbroadcastReceiver1: STATE TURNING OFF");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Log.d(TAG,"mbroadcastReceiver1: STATE ON");
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Log.d(TAG,"mbroadcastReceiver1: STATE TURNING ON");
                        break;
                }
            }
        }
    };


    /**
     * broadcast Receiver for changes made to bluetooth states such as:
     * 1) discoverability mode on/off or expire.
     */
    private final broadcastReceiver mbroadcastReceiver2 = new broadcastReceiver() {

        @Override
        public void onReceive(Context context,Intent intent) {
            final String action = intent.getAction();

            if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {

                int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,BluetoothAdapter.ERROR);

                switch (mode) {
                    //Device is in discoverable Mode
                    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_disCOVERABLE:
                        Log.d(TAG,"mbroadcastReceiver2: discoverability Enabled.");
                        break;
                    //Device not in discoverable mode
                    case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                        Log.d(TAG,"mbroadcastReceiver2: discoverability disabled. Able to receive connections.");
                        break;
                    case BluetoothAdapter.SCAN_MODE_NONE:
                        Log.d(TAG,"mbroadcastReceiver2: discoverability disabled. Not able to receive connections.");
                        break;
                    case BluetoothAdapter.STATE_CONNECTING:
                        Log.d(TAG,"mbroadcastReceiver2: Connecting....");
                        break;
                    case BluetoothAdapter.STATE_CONNECTED:
                        Log.d(TAG,"mbroadcastReceiver2: Connected.");
                        break;
                }

            }
        }
    };


    /**
     * broadcast Receiver for listing devices that are not yet paired
     * -Executed by btndiscover() method.
     */
    private broadcastReceiver mbroadcastReceiver3 = new broadcastReceiver() {
        @Override
        public void onReceive(Context context,Intent intent) {
            final String action = intent.getAction();
            Log.d(TAG,"onReceive: ACTION FOUND.");

            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mBTDevices.add(device);
                Log.d(TAG,"onReceive: " + device.getName() + ": " + device.getAddress());
                mDevicelistadapter = new Devicelistadapter(context,R.layout.list_item,mBTDevices);
                lvNewDevices.setAdapter(mDevicelistadapter);
            }
        }
    };


    /**
     * broadcast Receiver that detects bond state changes (Pairing status changes)
     */
    private final broadcastReceiver mbroadcastReceiver4 = new broadcastReceiver() {
        @Override
        public void onReceive(Context context,Intent intent) {
            final String action = intent.getAction();

            if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //3 cases:
                //case1: bonded already
                if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                    Log.d(TAG,"broadcastReceiver: BOND_BONDED.");
                    //inside broadcastReceiver4
                    mBTDevice = mDevice;
                }
                //case2: creating a bone
                if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                    Log.d(TAG,"broadcastReceiver: BOND_BONDING.");
                }
                //case3: breaking a bond
                if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                    Log.d(TAG,"broadcastReceiver: BOND_NONE.");
                }
            }
        }
    };


    @Override
    protected void onDestroy() {
        Log.d(TAG,"onDestroy: called.");
        super.onDestroy();
        unregisterReceiver(mbroadcastReceiver1);
        unregisterReceiver(mbroadcastReceiver2);
        unregisterReceiver(mbroadcastReceiver3);
        unregisterReceiver(mbroadcastReceiver4);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);

        btnConnect=findViewById(R.id.id_connect);
        btndiscoverability = findViewById(R.id.id_discoverability);
        btnONOFF = findViewById(R.id.id_ONOFF);
        btnSearch = findViewById(R.id.id_search);
        lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
        etSend = (TextView) findViewById(R.id.txtReceive);
        mBTDevices = new ArrayList<>();


        //broadcasts when bond state changes (ie:pairing)
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mbroadcastReceiver4,filter);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        lvNewDevices.setonItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,View view,int i,long id) {
                //first cancel discovery because its very memory intensive.
                mBluetoothAdapter.canceldiscovery();

                Log.d(TAG,"onItemClick: You Clicked on a device.");
                String deviceName = mBTDevices.get(i).getName();
                String deviceAddress = mBTDevices.get(i).getAddress();

                Log.d(TAG,"onItemClick: deviceName = " + deviceName);
                Log.d(TAG,"onItemClick: deviceAddress = " + deviceAddress);

                //create the bond.
                //NOTE: Requires API 17+? I think this is JellyBean
                if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
                    Log.d(TAG,"Trying to pair with " + deviceName);
                    mBTDevices.get(i).createBond();

                    mBTDevice = mBTDevices.get(i);
                    mBluetoothConnection = new BluetoothConnection(ShowInfoActivity.this);
                }

            }
        });

        btnConnect.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startConnection();

            }
        });


        btnONOFF.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"onClick: enabling/disabling bluetooth.");
                enabledisableBT();
            }
        });

        btndiscoverability.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"btnEnabledisable_discoverable: Making device discoverable for 300 seconds.");
                enabledisablediscoverability();

            }
        });
        btnSearch.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"btndiscover: Looking for unpaired devices.");
                enablediscover();
            }
        });

    }

    //create method for starting connection
//***remember the conncction will fail and app will crash if you haven't paired first
    public void startConnection(){
        startBTConnection(mBTDevice,MY_UUID_INSECURE);
    }

    /**
     * starting chat service method
     */
    public void startBTConnection(BluetoothDevice device,UUID uuid){
        Log.d(TAG,"startBTConnection: Initializing RFCOM Bluetooth Connection.");

        mBluetoothConnection.startClient(device,uuid);
    }



    public void enabledisableBT() {
        if (mBluetoothAdapter == null) {
            Log.d(TAG,"enabledisableBT: Does not have BT capabilities.");
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Log.d(TAG,"enabledisableBT: enabling BT.");
            Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableBTIntent);

            IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(mbroadcastReceiver1,BTIntent);
        }
        if (mBluetoothAdapter.isEnabled()) {
            Log.d(TAG,"enabledisableBT: disabling BT.");
            mBluetoothAdapter.disable();

            IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(mbroadcastReceiver1,BTIntent);
        }

    }

    public void enabledisablediscoverability() {

        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_disCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_disCOVERABLE_DURATION,300);
        startActivity(discoverableIntent);

        IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        registerReceiver(mbroadcastReceiver2,intentFilter);
    }

    public void enablediscover() {
        if (mBluetoothAdapter.isdiscovering()) {
            mBluetoothAdapter.canceldiscovery();
            Log.d(TAG,"btndiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startdiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mbroadcastReceiver3,discoverDevicesIntent);
        }
        if (!mBluetoothAdapter.isdiscovering()) {

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startdiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mbroadcastReceiver3,discoverDevicesIntent);
        }

    }


    /**
     * This method is required for all devices running API23+
     * Android must programmatically check the permissions for bluetooth. Putting the proper permissions
     * in the manifest is not enough.
     * <p>
     * NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
     */

    private void checkBTPermissions() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001); //Any number
            }
        } else {
            Log.d(TAG,"checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
        }
    }


}```

蓝牙连接

package com.example.temperaturaehumidade;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;

/**
 * Created by User on 12/21/2016.
 */

public class BluetoothConnection {
    private static final String TAG = "BluetoothConnectionServ";

    private static final String appName = "MYAPP";

    private static final UUID MY_UUID_INSECURE =
            UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    private final BluetoothAdapter mBluetoothAdapter;
    Context mContext;

    private AcceptThread mInsecureAcceptThread;

    private ConnectThread mConnectThread;
    private TextView mTxtReceive;
    private BluetoothDevice mmDevice;
    private UUID deviceUUID;
    ProgressDialog mProgressDialog;

    private ConnectedThread mConnectedThread;

    public BluetoothConnection(Context context) {
        mContext = context;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        start();
    }


   
     Finally the ConnectedThread which is responsible for maintaining the BTConnection,Sending the data,and
     receiving incoming data through input/output streams respectively.
     **/
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;


        private class ReadInput implements Runnable {

            private boolean bStop = false;
            private Thread t;

            public Readinput() {
                t = new Thread(this,"Input Thread");
                t.start();
            }

            public boolean isRunning() {
                return t.isAlive();
            }

            @Override
            public void run() {
                InputStream inputStream;

                try {
                    inputStream = mmSocket.getInputStream();
                    while (!bStop) {
                        byte[] buffer = new byte[256];
                        if (inputStream.available() > 0) {
                            inputStream.read(buffer);
                            int i = 0;
                            /*
                             * This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
                             */
                            for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
                            }
                            final String strInput = new String(buffer,i);

                            /*
                             * If checked then receive text,better design would probably be to stop thread if unchecked and free resources,but this is a quick fix
                             */

                        }
                        Thread.sleep(500);
                    }
                } catch (IOException e) {
// Todo Auto-generated catch block
                    e.printstacktrace();
                } catch (InterruptedException e) {
// Todo Auto-generated catch block
                    e.printstacktrace();
                }

            }

            public void stop() {
                bStop = true;
            }

        }

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG,"ConnectedThread: Starting.");

            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            //dismiss the progressdialog when connection is established
            try{
                mProgressDialog.dismiss();
            }catch (NullPointerException e){
                e.printstacktrace();
            }


            try {
                tmpIn = mmSocket.getInputStream();
                tmpOut = mmSocket.getoutputStream();
            } catch (IOException e) {
                e.printstacktrace();
            }

            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) {
                // Read from the InputStream
                try {
                    bytes = mmInStream.read(buffer);
                    String incomingMessage = new String(buffer,bytes);
                    Log.d(TAG,"InputStream: " + incomingMessage);
                } catch (IOException e) {
                    Log.e(TAG,"write: Error reading Input Stream. " + e.getMessage() );
                    break;
                }
            }
        }

        //Call this from the main activity to send data to the remote device
        public void write(byte[] bytes) {
            String text = new String(bytes,Charset.defaultCharset());
            Log.d(TAG,"write: Writing to outputstream: " + text);
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
                Log.e(TAG,"write: Error writing to output stream. " + e.getMessage() );
            }
        }

        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    private void connected(BluetoothSocket mmSocket,BluetoothDevice mmDevice) {
        Log.d(TAG,"connected: Starting.");

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(mmSocket);
        mConnectedThread.start();
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     *
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;

        // Synchronize a copy of the ConnectedThread
        Log.d(TAG,"write: Write Called.");
        //perform the write
        mConnectedThread.write(out);
    }



}

XML 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">

        <Button
            android:id="@+id/id_ONOFF"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:gravity="center_vertical|center_horizontal"
            android:hint="ON/OFF"
            android:textColorHint="@color/white" />
        <Button
            android:id="@+id/id_discoverability"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="discoverability"
            android:layout_margin="20dp"
            android:gravity="center_vertical|center_horizontal"
            android:textColorHint="@color/white"/>

        <Button
            android:id="@+id/id_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Search"
            android:layout_margin="20dp"
            android:gravity="center_vertical|center_horizontal"
            android:textColorHint="@color/white"/>

        <Button
            android:id="@+id/id_connect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:gravity="center_vertical|center_horizontal"
            android:hint="Connect"
            android:textColorHint="@color/white" />

    <ListView
        android:layout_below="@id/id_connect"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:id="@+id/lvNewDevices"/>


    <TextView
            android:id="@+id/txtReceive"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#eeeeee"
            android:hint="Message shows up here ..." />


</LinearLayout>

LogCat

而且这些值出现在 logcat 上而不是 android 屏幕上,有人可以帮助我吗?万分感谢。为了您的信息,我关注了这个家伙关于如何设置蓝牙连接的 YouTube 视频https://www.youtube.com/watch?v=y8R2C86BIUc&list=PLgCYzUzKIBE8KHMzpp6JITZ2JxTgWqDH2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。