Android 应用程序在蓝牙连接时崩溃?

标签 android exception-handling bluetooth android-bluetooth crash

我正在尝试通过我的应用程序使用蓝牙连接到其他 Android 设备。该应用程序在发现附近的蓝牙设备时运行良好。但是,在连接后,该应用程序崩溃了。

除了 MainActivity.java 之外,我还有两个 JAVA 文件负责发现和连接到其他蓝牙设备。他们的代码贴在下面:

SearchBTDevice.java(用于发现附近的设备)

package vertex2016.mvjce.edu.bluealert;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.Set;

public class SearchBTDevice extends AppCompatActivity {

    public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
    public ArrayAdapter PairedArrayAdapter;
    public ArrayAdapter BTArrayAdapter;
    BluetoothDevice btd;

    public ListView devicesFound;


    private final BroadcastReceiver BTReceiver= new BroadcastReceiver(){

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

           if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                   btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                   BTArrayAdapter.add(btd.getName() + "\t" + btd.getAddress() + "\n");

               }
           }

    };

    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);




    @Override
    protected void onResume() {
        super.onResume();
        this.registerReceiver(BTReceiver,filter1);



    }

    @Override
    protected void onPause() {
        super.onPause();
        BlueAdapter.cancelDiscovery();
        this.unregisterReceiver(BTReceiver);
        Toast.makeText(SearchBTDevice.this, "Discovery Stopped!!", Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_btdevice);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);




       searchBTDevices();


    }


    public void searchBTDevices()
    {
        if(!BlueAdapter.startDiscovery())
            Toast.makeText(SearchBTDevice.this, "Failed to Start Discovery", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(SearchBTDevice.this, "Discovery Startred", Toast.LENGTH_SHORT).show();
        BTArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
        devicesFound = (ListView)findViewById(R.id.searchpagelistView);
        devicesFound.setAdapter(BTArrayAdapter);
        devicesFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent connectedBTintent = new Intent(SearchBTDevice.this, ConnectedBTDevice.class);
                connectedBTintent.putExtra("BluetoothDevice", btd);
                startActivity(connectedBTintent);

            }
        });

    }


}

这是更新 ConnectedBTDevice.java,负责连接设备

package vertex2016.mvjce.edu.bluealert;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

public class ConnectedBTDevice extends AppCompatActivity {

    public BluetoothDevice btd;
    public BluetoothSocket btSocket, tempSocket;
    private UUID myUUID;
    ArrayAdapter arr;
    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connected_btdevice);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);


        arr  = new ArrayAdapter(this, android.R.layout.simple_list_item_2);

        btd = getIntent().getParcelableExtra("BluetoothDevice");

        connectBT();
        displayStuff();

    }

    public void connectBT() {
        Thread myThread = new Thread() {

            public void run() {
                tempSocket = null;

                try {
                    tempSocket = btd.createRfcommSocketToServiceRecord(myUUID);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                BluetoothAdapter.getDefaultAdapter().cancelDiscovery();

                try {
                    tempSocket.connect();
                    arr.add("CONNECTED TO-->" + btd.getName());
                } catch (IOException e) {
                    e.printStackTrace();
                    try {
                        tempSocket.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }


            }

        };
        myThread.start();
    }




    public void displayStuff()
    {
        lv = (ListView)findViewById(R.id.connectedBTlistView);
        lv.setAdapter(arr);
    }

}

这是用于 ConnectedBTDevice.java Activity 的 activity_connected_btdevice.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="vertex2016.mvjce.edu.bluealert.SearchBTDevice">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.NoActionBar.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.NoActionBar.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_connected_btdevice" />

</android.support.design.widget.CoordinatorLayout>

这是用于 ConnectedBTDevice.java 的 content_connected_btdevice.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="vertex2016.mvjce.edu.bluealert.ConnectedBTDevice"
    tools:showIn="@layout/activity_connected_btdevice">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/connectedBTimageView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:src="@drawable/bluealert_bg"
        android:scaleType="centerCrop"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Connected Bluetooth Device"
        android:id="@+id/connectedBTtextextView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="105dp"
        android:textSize="25dp"
        android:textAlignment="center"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/connectedBTlistView"
        android:layout_below="@+id/connectedBTtextextView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp" />


</RelativeLayout>

这是AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="vertex2016.mvjce.edu.bluealert">

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/bluealerticon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <activity
            android:name=".SplashScreen"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
        <activity
            android:name=".SearchBTDevice"
            android:label="@string/title_activity_search_btdevice"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="vertex2016.mvjce.edu.bluealert.MainActivity" />
        </activity>
        <activity
            android:name=".ConnectedBTDevice"
            android:label="@string/title_activity_connected_btdevice"
            android:parentActivityName=".SearchBTDevice"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="vertex2016.mvjce.edu.bluealert.SearchBTDevice" />
        </activity>
    </application>

</manifest>

这是我的更新 logcat 显示的异常

03-24 00:19:40.541 7205-9703/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: Thread-35890
                                                                              Process: vertex2016.mvjce.edu.bluealert, PID: 7205
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.UUID.getMostSignificantBits()' on a null object reference
                                                                                  at android.os.ParcelUuid.writeToParcel(ParcelUuid.java:129)
                                                                                  at android.bluetooth.IBluetooth$Stub$Proxy.connectSocket(IBluetooth.java:1767)
                                                                                  at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:309)
                                                                                  at vertex2016.mvjce.edu.bluealert.ConnectedBTDevice$1.run(ConnectedBTDevice.java:63)

我不明白这是什么问题。我尝试了几个在线教程,但似乎没有任何效果。我知道问题出在我的 ConnectedBTDevice.java 中,但无法弄清楚它抛出异常的位置。

感谢您的宝贵时间。

最佳答案

您正在将 BluetoothSocket 分配给 tempSocket,然后您尝试调用 null 的 btSocket 上的 connect() 方法。

关于Android 应用程序在蓝牙连接时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185731/

相关文章:

java - 通过模块 B gradle 将类从模块 A 引用到模块 C

通过策略模式处理 Java 异常?

asp.net-mvc - CompressFilter 与 asp.net MVC 中的 ExceptionHandlerFilter 冲突

c++ - 如何在一个 catch block 中捕获所有类型的异常?

c++ - Windows 7 蓝牙堆栈和 API 是否支持耳机连接

java - 应用程序意外停止: Fatal Exception

java - RecyclerView ItemTouchHelper.Callback : Dragging swap condition

android - 手机休眠时播放声音

android - ajax 和 jsonp 的 PhoneGap 问题

android - 如何在 Android 中通过蓝牙流式传输来电音频