Android蓝牙应用程序单击按钮时崩溃

时间:2017-01-05 16:48:11

标签: android android-studio bluetooth

Android蓝牙应用程序在点击按钮时崩溃,我已经用Google搜索了问题,但是得到了相关的答案。请帮助我是android的新手。 我正在使用android studio创建一个蓝牙应用程序,每当我点击连接设备按钮时它就会崩溃。下面是我认为错误的代码。

DeviceActivity.java

package com.contec.activity;

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

import com.contec.spmw.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class DeviceActivity extends Activity {
    /** Called when the activity is first created. */

    private ListView mListView;
    private ArrayList<SiriListItem> list;
    private Button seachButton, serviceButton;
    ChatListAdapter mAdapter;
    Context mContext;
    private String mstraddress = "";


    private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 3);
        }
    }   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.devices);
        mContext = this;

        init();
    }    

    private void init() {
        list = new ArrayList<SiriListItem>();
        mAdapter = new ChatListAdapter(this, list);
        mListView = (ListView) findViewById(R.id.list);
        mListView.setAdapter(mAdapter);
        mListView.setFastScrollEnabled(true);
        mListView.setOnItemClickListener(mDeviceClickListener);     

        // Register for broadcasts when discovery has finished
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, foundFilter);

         // Register for broadcasts when a device is discovered
        IntentFilter discoveryFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, discoveryFilter);

        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), true));
                mAdapter.notifyDataSetChanged();
                mListView.setSelection(list.size() - 1);
            }
        } else {
            list.add(new SiriListItem("Some CHinese Text", true));
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(list.size() - 1);
        }

        seachButton = (Button)findViewById(R.id.start_seach);
        seachButton.setOnClickListener(seachButtonClickListener);

    }    
     private OnClickListener seachButtonClickListener = new OnClickListener() {
         @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(mBtAdapter.isDiscovering()) 
                {
                    mBtAdapter.cancelDiscovery();
                    //seachButton.setText("重新搜索");
                    seachButton.setText("Re Find");
                }
                else
                {
                    list.clear();
                    mAdapter.notifyDataSetChanged();

                    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
                    if (pairedDevices.size() > 0) {
                            for (BluetoothDevice device : pairedDevices) {
                                list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), true));
                                mAdapter.notifyDataSetChanged();
                                mListView.setSelection(list.size() - 1);
                            }
                    } else {
                            list.add(new SiriListItem("No devices have been paired", true));
                            mAdapter.notifyDataSetChanged();
                            mListView.setSelection(list.size() - 1);
                     }                  

                    mBtAdapter.startDiscovery();
                    //seachButton.setText("Some Chinese Text");
                    seachButton.setText("stop");
                }                
            }
        };


    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect     

            SiriListItem item = list.get(arg2);
            String info = item.message;
            mstraddress = info.substring(info.length() - 17);                 
        //    Bluetooth.BlueToothAddress = address;

             AlertDialog.Builder StopDialog =new AlertDialog.Builder(mContext);
             //StopDialog.setTitle("Some CHinese Text");          
             StopDialog.setTitle("connect");
             StopDialog.setMessage(item.message);
             //StopDialog.setPositiveButton("Some CHinese Text", new DialogInterface.OnClickListener() {  
             StopDialog.setPositiveButton("connect", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {  
                 // TODO Auto-generated method stub   
                 mBtAdapter.cancelDiscovery();
                 //seachButton.setText("Some Chinese Text");     
                 seachButton.setText("Re find");

         //      Bluetooth.serviceOrCilent=ServerOrCilent.CILENT;
         //        Bluetooth.mTabHost.setCurrentTab(1);   

                if(!mstraddress.equals("null"))
                {
                    //device = mBtAdapter.getRemoteDevice(mstraddress); 

                    //clientConnectThread = new clientThread();
                    //clientConnectThread.start();

                    Intent intent2 = new Intent();
                    intent2.setClass(DeviceActivity.this, MainActivity.class);

                    Bundle bundle = new Bundle();
                    bundle.putString("straddress", mstraddress);
                    intent2.putExtra("bundle", bundle);

                    setResult(0, intent2);
                    DeviceActivity.this.finish();
                }
                else
                {
                    Toast.makeText(DeviceActivity.this, "address is null !", Toast.LENGTH_SHORT).show();
                }

             }  
             });
             //StopDialog.setNegativeButton("Some CHinese Text",new DialogInterface.OnClickListener() {                       
             StopDialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {  
         //          Bluetooth.BlueToothAddress = null;
                 }
             });
             StopDialog.show();                            
        }
    };  

    private Handler LinkDetectedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 0)
            {
                Toast.makeText(mContext, (String)msg.obj, Toast.LENGTH_SHORT).show();
            }
            else if (msg.what == 1)
            {
                String str = "Some chinese Text:\r\n" + (String)msg.obj;
                Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();//测试
            }

        }

    };    

    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
                {
                    list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), false));
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
            // When discovery is finished, change the Activity title
            } 
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
            {
                setProgressBarIndeterminateVisibility(false);
                if (mListView.getCount() == 0) 
                {
                    //list.add(new SiriListItem("Some CHinese Text", false));
                    list.add(new SiriListItem("not find bluetooth", false));
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
                //seachButton.setText("Some CHinese Text");
                seachButton.setText("Re find");
            }
        }
    };  

    public class SiriListItem {
        String message;
        boolean isSiri;
        public SiriListItem(String msg, boolean siri) {
            message = msg;
            isSiri = siri;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }
}

logcat的

 --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.contec.spmw, PID: 1937
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contec.spmw/com.contec.activity.DeviceActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                      at android.app.ActivityThread.access$800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5221)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()' on a null object reference
                      at com.contec.activity.DeviceActivity.init(DeviceActivity.java:227)
                      at com.contec.activity.DeviceActivity.onCreate(DeviceActivity.java:204)
                      at android.app.Activity.performCreate(Activity.java:5937)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:144) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:135) 
                      at android.app.ActivityThread.main(ActivityThread.java:5221) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:372) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
I/Process: Sending signal. PID: 1937 SIG: 9
Application terminated.

1 个答案:

答案 0 :(得分:1)

在调用BluetoothAdapter之前尝试检查getBondedDevices是否为空,因为如果您的设备不支持蓝牙,它将返回null。根据您在问题中的评论,Android模拟器不支持蓝牙。请在documentation中查看。

  

BluetoothAdapter - 默认本地适配器,如果此硬件平台不支持蓝牙,则为null

检查如下:

if (mBtAdapter != null && mBtAdapter.isEnabled()) {
    // do your task
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
} else {
    // Bluetooth is not supported on your hardware
}

希望它对你有所帮助。