android蓝牙扫描不起作用

时间:2018-04-11 05:22:07

标签: java android android-studio bluetooth android-7.0-nougat

我不擅长英语:( 请理解我。

我有两部智能手机。一个是Android 4.4.4版,支持蓝牙4.0。另一个是Android 7.0版,支持蓝牙4.1。我编写了代码来扫描蓝牙。但是,当我在智能手机(即)7.0版的Android上扫描蓝牙时,会发出一条消息"没有找到任何设备"出现。我对两者都使用相同的代码,我不知道7.0版为什么不扫描蓝牙

MainActivity调用BluetoothSevice,它提供蓝牙服务,ScanDevice函数调用DeviceListActivity到BluetoothSevice。我认为扫描功能在DeviceListActivity中,所以我认为仅仅看到DeviceListActivity就足够了。

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hansung.bluetooth4">

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

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".DeviceListActivity"
            android:theme="@android:style/Theme.DeviceDefault.Dialog">
        </activity>
    </application>

</manifest>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //debugging
    private static final String TAG = "Main";

    //Intent request code
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT=2;

    private Button btn_Connect;

    private BluetoothService bluetoothService_obj = null; 


    private final Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {

            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG,"onCreate");
        setContentView(R.layout.activity_main);

        if(bluetoothService_obj==null){
            bluetoothService_obj = new BluetoothService(this,mHandler);
        }



        if(bluetoothService_obj.getDeviceState())
        {

            bluetoothService_obj.enableBluetooth();
        }
        else
        {
            finish();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.d(TAG, "onActivityResult입니다. resultCode : " + resultCode);
    // TODO Auto-generated method stub

        switch(requestCode)
        {

            case REQUEST_ENABLE_BT: //블루투스가 비활성화 됬음을 확인했을 경우.활성화 요청
            //When the request to enable Bluetooth returns
                if(resultCode == Activity.RESULT_OK) 
                {
                    bluetoothService_obj.scanDevice();
                }else{
                    Log.d(TAG, "cancel");
                }
                break;

            case REQUEST_CONNECT_DEVICE:
                if(resultCode==Activity.RESULT_OK)
                {
                    //bluetoothService_obj.getDevifeInfo(data);
                }
                break;
        }
    }

}

BluetoothService.java

public class BluetoothService {

    //Intent request code
    private static final int REQUEST_CONNEXT_DEVICE =1;
    private static final int REQUEST_ENABLE_BT=2;

    //Debugging
    private static final String TAG = "BluetoothService";

    //RFCOMM Protocol
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private BluetoothAdapter btAdapter;
    private Activity mActivity;
    private Handler mHandler;



    public BluetoothService(Activity activity, Handler handler)
    {
        mActivity = activity;
        mHandler = handler;


        btAdapter = BluetoothAdapter.getDefaultAdapter();
    }


    public boolean getDeviceState()
    {
        Log.d(TAG, "check Bluetooth enable");

        if(btAdapter==null)
        {
            Log.d(TAG, "You can't use Bluetooth ");
            return false;
        }

        else
        {
            Log.d(TAG, "You can use Bluetooth");
            return true;
        }
    }

          public void enableBluetooth()
    {
        Log.i(TAG, "블루투스 활성화 여부 확인");

        if(btAdapter.isEnabled())
        {

            Log.d(TAG, "Bluetooth enable");

            scanDevice();

        }
        else
        {

            Log.d(TAG, "Bluetooth doesn't enable");

            Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            mActivity.startActivityForResult(i, REQUEST_ENABLE_BT);
        }
    }

    public void  scanDevice(){
        Log.d(TAG,"Scan Device");

        Intent serverIntent = new Intent(mActivity, DeviceListActivity.class);
        mActivity.startActivityForResult(serverIntent,REQUEST_CONNEXT_DEVICE);

    }

}

DeviceListActivity.java

package com.example.hansung.bluetooth4;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;




public class DeviceListActivity extends Activity {


    private static final String TAG = "DeviceListActivity";




    private BluetoothAdapter mBtAdapter;


    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.activity_device_list);


        setResult(Activity.RESULT_CANCELED);



        Button scanButton = (Button) findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (mBtAdapter.isDiscovering()) {
                    mBtAdapter.cancelDiscovery();
                }


                mBtAdapter.startDiscovery();

                v.setVisibility(View.GONE);
           }
        });


        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);





        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);


        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);


        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);


        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    }






    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();


            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


                short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MAX_VALUE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()+"(RSSI: "+rssi+"dBm)");
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };

}

0 个答案:

没有答案