Android应用在蓝牙连接上崩溃了?

时间:2016-03-23 18:14:42

标签: 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_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中,但无法弄清楚它是否会引发异常。

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

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