0

我对 android 编程有点陌生,但现在我想尝试编写一个应用程序,通过蓝牙将我的手机(三星 Galaxy Note 2)与电路板连接起来。我只想打开/关闭一些 LED。我在电路板上使用 bc417 调制解调器。

我已经搜索了蓝牙示例,但它们似乎都很困难,我只想要我需要的命令。但是目前,当我在 ListView 上选择一个项目时,我的应用程序一直崩溃。

有人可以帮我吗?

package com.test.bluetoothtest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;


import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.bluetooth.BluetoothSocket;

public class MainActivity extends Activity {

private static final int REQUEST_ENABLE_BT = 1;
private static final UUID myuuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");



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


    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null)
    {
        Toast.makeText(MainActivity.this, "Bluetooth couldn't be started.", Toast.LENGTH_SHORT).show();
    }
    if(!mBluetoothAdapter.isEnabled())
    {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        Toast.makeText(MainActivity.this, "Bluetooth started succesfully", Toast.LENGTH_SHORT).show();
    }
    List<String> devicelist = new ArrayList<String>();

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
        for(BluetoothDevice device : pairedDevices)
        {
            devicelist.add(device.getName());

        }
    }
    ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, devicelist);
    final ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            try
            {
                Toast.makeText(MainActivity.this, lv.getAdapter().getItem(arg2).toString(), Toast.LENGTH_SHORT).show();
                BluetoothDevice finaldevice = (BluetoothDevice) lv.getAdapter().getItem(arg2);                  
                BluetoothSocket clientSocket = finaldevice.createRfcommSocketToServiceRecord(myuuid);
                clientSocket.connect();
                Toast.makeText(MainActivity.this, "Connectin successful!", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                Toast.makeText(MainActivity.this, "Error!", Toast.LENGTH_SHORT).show();
            }
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

目录:

07-10 20:38:55.115: D/AbsListView(16942): Get MotionRecognitionManager
07-10 20:38:55.335: D/libEGL(16942): loaded /system/lib/egl/libEGL_mali.so
07-10 20:38:55.345: D/libEGL(16942): loaded /system/lib/egl/libGLESv1_CM_mali.so
07-10 20:38:55.345: D/libEGL(16942): loaded /system/lib/egl/libGLESv2_mali.so
07-10 20:38:55.350: D/(16942): Device driver API match
07-10 20:38:55.350: D/(16942): Device driver API version: 10
07-10 20:38:55.350: D/(16942): User space API version: 10 
07-10 20:38:55.350: D/(16942): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012 
07-10 20:38:55.400: D/OpenGLRenderer(16942): Enabling debug mode 0
07-10 20:39:05.145: D/GestureDetector(17303): [Surface Touch Event] mSweepDown False, mLRSDCnt : -1 mTouchCnt : 2 mFalseSizeCnt:0
07-10 20:39:05.240: D/AndroidRuntime(17303): Shutting down VM
07-10 20:39:05.240: W/dalvikvm(17303): threadid=1: thread exiting with uncaught exception (group=0x40db82a0)
07-10 20:39:05.245: E/AndroidRuntime(17303): FATAL EXCEPTION: main
07-10 20:39:05.245: E/AndroidRuntime(17303): java.lang.ClassCastException: java.lang.String cannot be cast to android.bluetooth.BluetoothDevice
07-10 20:39:05.245: E/AndroidRuntime(17303):    at com.test.bluetoothtest.MainActivity$1.onItemClick(MainActivity.java:74)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.widget.AbsListView.performItemClick(AbsListView.java:1283)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3074)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.widget.AbsListView$1.run(AbsListView.java:4147)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.os.Handler.handleCallback(Handler.java:615)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.os.Looper.loop(Looper.java:137)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at android.app.ActivityThread.main(ActivityThread.java:4898)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at java.lang.reflect.Method.invokeNative(Native Method)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at java.lang.reflect.Method.invoke(Method.java:511)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
07-10 20:39:05.245: E/AndroidRuntime(17303):    at dalvik.system.NativeStart.main(Native Method)
07-10 20:41:33.045: D/AbsListView(18494): Get MotionRecognitionManager
07-10 20:41:33.155: D/libEGL(18494): loaded /system/lib/egl/libEGL_mali.so
07-10 20:41:33.160: D/libEGL(18494): loaded /system/lib/egl/libGLESv1_CM_mali.so
07-10 20:41:33.165: D/libEGL(18494): loaded /system/lib/egl/libGLESv2_mali.so
07-10 20:41:33.170: D/(18494): Device driver API match
07-10 20:41:33.170: D/(18494): Device driver API version: 10
07-10 20:41:33.170: D/(18494): User space API version: 10 
07-10 20:41:33.170: D/(18494): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012 
07-10 20:41:33.225: D/OpenGLRenderer(18494): Enabling debug mode 0
07-10 20:41:34.975: D/GestureDetector(18494): [Surface Touch Event] mSweepDown False, mLRSDCnt : -1 mTouchCnt : 3 mFalseSizeCnt:0
07-10 20:41:35.110: D/AndroidRuntime(18494): Shutting down VM
07-10 20:41:35.110: W/dalvikvm(18494): threadid=1: thread exiting with uncaught exception (group=0x40db82a0)
07-10 20:41:35.115: E/AndroidRuntime(18494): FATAL EXCEPTION: main
07-10 20:41:35.115: E/AndroidRuntime(18494): java.lang.ClassCastException: java.lang.String cannot be cast to android.bluetooth.BluetoothDevice
07-10 20:41:35.115: E/AndroidRuntime(18494):    at com.test.bluetoothtest.MainActivity$1.onItemClick(MainActivity.java:75)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.widget.AbsListView.performItemClick(AbsListView.java:1283)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3074)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.widget.AbsListView$1.run(AbsListView.java:4147)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.os.Handler.handleCallback(Handler.java:615)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.os.Looper.loop(Looper.java:137)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at android.app.ActivityThread.main(ActivityThread.java:4898)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at java.lang.reflect.Method.invokeNative(Native Method)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at  java.lang.reflect.Method.invoke(Method.java:511)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
07-10 20:41:35.115: E/AndroidRuntime(18494):    at dalvik.system.NativeStart.main(Native Method)
07-10 20:41:47.780: I/Process(18494): Sending signal. PID: 18494 SIG: 9
4

2 回答 2

1

您的问题是以下行

BluetoothDevice finaldevice = (BluetoothDevice) lv.getAdapter().getItem(arg2); 

getItem 返回字符串而不是蓝牙设备。你的施法失败。

请执行下列操作。

您查询配对的设备并将它们显示在列表视图中。在配对设备上,您需要其 Mac 地址才能创建连接。当您遍历配对设备时,您可以提取每个设备的地址。稍后在您的单击中执行以下操作以获取蓝牙设备。

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
    // Loop through paired devices
    for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}

稍后当从项目的文本中单击项目时提取此地址并相应地使用它。

BluetoothDevice device = btAdapter.getRemoteDevice(address);

然后使用以下内容获取BluetoothSocket

 btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);

然后就可以使用这个socket进行连接了。

btSocket.connect();
于 2013-07-10T21:01:19.280 回答
0

很高兴知道您的应用程序在哪里崩溃。LogCat 也可能会有所帮助。因为我自己有一些关于 UUID 的问题,所以我正在使用

Method m = finaldevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
clientSocket = (Bluetoothsocket) m.invoke(finaldevice, Integer.valueOf(1));
clientSocket.connect();

这个对我有用。

于 2013-07-10T18:31:42.730 回答