蓝牙Android - Arduino应用程序错误 - java.lang.IllegalArgumentException:null不是有效的蓝牙地址

时间:2017-12-04 02:02:30

标签: android bluetooth arduino

我需要你的帮助!

第一:我来自奥地利,所以我的英语不太好。所以我为我将犯的错误道歉!

这是我尝试使用Android Studio的第一个项目。我是编程新手。我在Arduino和Android程序语言方面的技能不是很高,但是我的学士学位项目需要它,所以我必须学习它!

我使用西班牙语的教程视频,所以我不知道那个人在谈论什么,但我完全理解这些代码。

我的问题是,当我在手机上启动应用程序时,第一个屏幕(配对设备)工作正常。但是当我按下配对设备时...

发生以下错误:

  

从应用程序捕获并显示logcat消息。这个   可以在“Logcat输出”部分中禁用行为   “调试器”设置页面。 d / OpenGLRenderer:   ProgramCache.generateProgram:103079215104 D / AndroidRuntime:正在关闭   VM E / AndroidRuntime:FATAL EXCEPTION:main                     流程:bachelor_projekt.bluetoothcontroller,PID:11061                     java.lang.RuntimeException:无法恢复活动   {bachelor_projekt.bluetoothcontroller / bachelor_projekt.bluetoothcontroller.UserInterface}:   java.lang.IllegalArgumentException:null不是有效的蓝牙   地址                         在android.app.ActivityThread.performResumeActivity(ActivityThread.java:3506)                         在android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)                         在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)                         在android.app.ActivityThread.-wrap12(ActivityThread.java)                         在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1527)                         在android.os.Handler.dispatchMessage(Handler.java:110)                         在android.os.Looper.loop(Looper.java:203)                         在android.app.ActivityThread.main(ActivityThread.java:6247)                         at java.lang.reflect.Method.invoke(Native Method)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1063)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)                      引起:java.lang.IllegalArgumentException:null不是有效的蓝牙地址                         在android.bluetooth.BluetoothDevice。(BluetoothDevice.java:668)                         在android.bluetooth.BluetoothAdapter.getRemoteDevice(BluetoothAdapter.java:553)                         at bachelor_projekt.bluetoothcontroller.UserInterface.onResume(UserInterface.java:122)                         在android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1272)                         在android.app.Activity.performResume(Activity.java:6917)                         在android.app.ActivityThread.performResumeActivity(ActivityThread.java:3477)                         在android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)                         在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)                         在android.app.ActivityThread.-wrap12(ActivityThread.java)                         在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1527)                         在android.os.Handler.dispatchMessage(Handler.java:110)                         在android.os.Looper.loop(Looper.java:203)                         在android.app.ActivityThread.main(ActivityThread.java:6247)                         at java.lang.reflect.Method.invoke(Native Method)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1063)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)   I /处理:发送信号。 PID:11061 SIG:9申请终止。

在该消息之后,应用程序关闭:

我将我的应用分成了:

蓝牙 - 用于蓝牙连接

以下是代码:

    package bachelor_projekt.bluetoothcontroller;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Set;

public class Bluetooth extends AppCompatActivity {



    // Cleaning of the Logcat (Systemlog)
    private static final String TAG = "Bluetooth";

    // Declaration of ListView
    ListView IdList;

    // String which will be sended to the main frame
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // Declaration of the fields
    private BluetoothAdapter myBluetooth;
    private ArrayAdapter<String> myPairedDevicesArray;

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

    @Override
    public void onResume()
    {
        super.onResume();
        //----------------------------
        VerificationBT();

        // Initialze the array which keeps the bluetooth devices
        myPairedDevicesArray=new ArrayAdapter<String>(this, R.layout.device_name);
        IdList = findViewById(R.id.idList);
        IdList.setAdapter(myPairedDevicesArray);
        IdList.setOnItemClickListener(myDeviceClickListener);

        // Get local default bluetooth adapter
        myBluetooth = BluetoothAdapter.getDefaultAdapter();

        // Includes the bluetooth member which is paired with the device
        Set<BluetoothDevice> pairedDevices =myBluetooth.getBondedDevices();

        // Pair with an already in the array included device.
        if (pairedDevices.size()>0)
        {
            for (BluetoothDevice device : pairedDevices){
                myPairedDevicesArray.add(device.getName() + "\n" + device.getAddress());
            }
        }

    }

    // Configuration for the "on click" ability for the liste
    private AdapterView.OnItemClickListener myDeviceClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView av , View v, int arg2, long arg3) {

            // Detect the MAC-Adress of the device ( last 17 caracters)
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // 1 Try to connect if MAC adress is the same
            Intent i = new Intent(Bluetooth.this, UserInterface.class);
            startActivity(i);
        }

    };

    private void VerificationBT(){
        // Checks if the device has bluetooth and if it is activated

        myBluetooth=BluetoothAdapter.getDefaultAdapter();

        if(myBluetooth==null) {
            Toast.makeText(getBaseContext(), "Device doesn't have bluetooth", Toast.LENGTH_SHORT).show();
        } else{
            if (myBluetooth.isEnabled()) {
                Log.d(TAG, "...Bluetooth Avtivated...");
            } else{

                // Ask the user to activate bluetooth
                Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBt,1);

            }
        }
    }

}

第二部分是用户界面 - 这应该是仅用于启动的实际项目(3个按钮,1个用于LED开启,1个用于LED关闭,1个用于断开连接)。

以下是代码:

package bachelor_projekt.bluetoothcontroller;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class UserInterface extends AppCompatActivity {

    Button IdLedON, IdLedOFF, IdDisconnect;
    TextView IdBuffer;
    //-------------------------------------------------

    Handler bluetoothIn;
    final int handlerState = 0;

    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder DataStringIN = new StringBuilder();
    private ConnectedThread MyConnection;

    // Special service - SPP UUID
    private static final UUID BTMODULE_UUID = UUID.fromString
            ("00001101-0000-1000-8000-00211300ACCD"); //805F9B34FB

    // String direction of the MAC
    private static String address = null;


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

        // Connection between inferface and variables
        IdLedON = (Button) findViewById(R.id.IdLedON);
        IdLedOFF = (Button) findViewById(R.id.IdLedOFF);
        IdDisconnect = (Button) findViewById(R.id.IdDisconnect);
        IdBuffer = findViewById(R.id.IdBuffer);

            bluetoothIn = new Handler(){
                public void handleMessage(android.os.Message msg){

                    if (msg.what == handlerState) {
                        String readMessage = (String) msg.obj;
                        DataStringIN.append(readMessage);

                    int endOfLineIndex = DataStringIN.indexOf("#");

                    if (endOfLineIndex > 0) {
                        String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
                        IdBuffer.setText("Data: " + dataInPrint);
                        DataStringIN.delete(0, DataStringIN.length());
                   }
                }
            }
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        VerificationBT();

        IdLedON.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v)  {
                MyConnection.write("1");
            }
        });

        IdLedOFF.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                MyConnection.write("0");
            }
        });

        IdDisconnect.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (btSocket != null)
                {
                    try {
                        btSocket.close();
                    } catch (IOException e) {
                        Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();;}
                }
                finish();
            }
        });

    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
    {
        // Creates a save Connection for the device
        return device.createRfcommSocketToServiceRecord(BTMODULE_UUID);
    }

    @Override
    public void onResume()
    {
        super.onResume();

        // Receives MAC Adress Direction out of DeviceListActivity via intent
        Intent intent = getIntent();

        // Receives MAC Adress Direction out of DeviceListActivity via EXTRA
        address = intent.getStringExtra(Bluetooth.EXTRA_DEVICE_ADDRESS);

        // adjust MAC Adress
        BluetoothDevice device = btAdapter.getRemoteDevice(address);


        try
        {
            btSocket = createBluetoothSocket(device);
            } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Error while Connection with device accured ", Toast.LENGTH_SHORT).show();
        }

        // Creates a connection with bluetooth
        try
        {
            btSocket.connect();
        } catch (IOException e){
            try{
                btSocket.close();
            } catch (IOException e2){}

        }
        MyConnection = new ConnectedThread(btSocket);
        MyConnection.start();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        try
        {
            // If you leave the application there can be no access to the bluetooth adapter
            btSocket.close();
        } catch (IOException e2){}
    }

    // Check if bluetooth device is available and connect with it
    private void VerificationBT()
    {
        if (btAdapter == null) {
            Toast.makeText(getBaseContext(), "Device doesn't support bluetooth", Toast.LENGTH_LONG);
        } else {
            Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBt, 1);
        }

    }


    // class for making a connection
    private class ConnectedThread extends Thread
    {
        private final InputStream myInStream;
        private final OutputStream myOutStream;

        public ConnectedThread(BluetoothSocket socket)
        {
            InputStream tmpIn=null;
            OutputStream tmpOut=null;
            try
            {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {}
        myInStream=tmpIn;
        myOutStream=tmpOut;
        }

        public void run()
        {
            byte[] buffer = new byte[256];
            int bytes;

            // Device stays in the "try to connect" mode
            while(true) {
                try {
                    bytes = myInStream.read(buffer);
                    String readMessage = new String(buffer, 0, bytes);
                } catch (IOException e) {
                    break;
                }
            }
        }

        public void write(String input)
        {
            try{
                myOutStream.write(input.getBytes());
            } catch (IOException e)
            {
                // If it is not possible to send data
                Toast.makeText(getBaseContext(), " Connection failed", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}

因此,如果您需要信息,请告诉我。 希望你们中的某个人能理解我的问题,并能帮助我:)。

祝福 半

1 个答案:

答案 0 :(得分:0)

似乎代码中存在错误。

此错误: android.app.ActivityThread.handleResumeActivity

出现的方式太多次,这意味着活动冻结或崩溃,然后试图重新启动,但仍然失败了很多次它最终放弃了。

此外,您似乎使用VM来测试代码,因此请尝试将其与真实设备一起使用。

如果您无法发现问题,请尝试从头再次编写代码或通过错误解释器运行代码。

祝你好运, 保罗!