Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 扫描蓝牙设备_Android_Bluetooth_Broadcastreceiver_Network Scan - Fatal编程技术网

Android 扫描蓝牙设备

Android 扫描蓝牙设备,android,bluetooth,broadcastreceiver,network-scan,Android,Bluetooth,Broadcastreceiver,Network Scan,我有一个广播接收器,我想一直扫描蓝牙设备。 我想知道是否有一个设备名为X,如果他在附近(如果应用程序发现这个设备带有蓝牙),我想做点什么 所以,我需要的只是始终扫描设备的方法,而不停止,剩下的我可以做 谢谢 Scan.java import java.io.IOException; 导入java.io.OutputStream; 导入java.util.Set; 导入java.util.UUID; 导入android.annotation.SuppressLint; 导入android.app.

我有一个广播接收器,我想一直扫描蓝牙设备。 我想知道是否有一个设备名为X,如果他在附近(如果应用程序发现这个设备带有蓝牙),我想做点什么

所以,我需要的只是始终扫描设备的方法,而不停止,剩下的我可以做

谢谢

Scan.java
import java.io.IOException;
导入java.io.OutputStream;
导入java.util.Set;
导入java.util.UUID;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothSocket;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.Message;
导入android.util.Log;
导入android.view.view;
导入android.view.Window;
导入android.view.WindowManager;
导入android.widget.Button;
导入android.widget.Toast;
@SuppressLint(“新API”)
公共类扫描扩展活动实现可运行
{
受保护的静态最终字符串TAG=“TAG”;
专用静态最终int请求\u连接\u设备=1;
私有静态最终整数请求_ENABLE_BT=2;
按钮mScan;
//蓝牙适配器mBluetoothAdapter;
私有BluetoothAdapter mBluetoothAdapter=null;
专用UUID应用程序UID=UUID.fromString(“000011101-0000-1000-8000-00805F9B34FB”);
private ProgressDialog mBluetoothConnectProgressDialog;
私人蓝牙插座;
蓝牙设备;
字符串消息传递;
@凌驾
创建时的公共void(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_全屏,
WindowManager.LayoutParams.FLAG(全屏);
setContentView(R.layout.scan);
mScan=(按钮)findViewById(R.id.Scan);
mScan.setOnClickListener(新视图.OnClickListener()
{
公共void onClick(视图mView)
{
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter==null)
{
Toast.makeText(Scan.this,“Message1”,2000).show();
} 
其他的
{
如果(!mBluetoothAdapter.isEnabled())
{
Intent enablebintent=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(启用BTIntent、请求\启用\ BT);
} 
其他的
{
ListPairedDevices();
Intent connectIntent=新的Intent(Scan.this,DeviceListActivity.class);
startActivityForResult(连接内容、请求连接设备);
}
}
}
});
}
activityResult上的公共无效(int-mreRequestCode、int-mResultCode、Intent-mDataIntent)
{
super.onActivityResult(mRequestCode、mResultCode、mDataIntent);
开关(mRequestCode)
{
案例请求\u连接\u设备:
如果(mResultCode==Activity.RESULT\u确定)
{
Bundle-mExtra=mDataIntent.getExtras();
字符串mDeviceAddress=mExtra.getString(“DeviceAddress”);
Log.v(标记“即将到来的传入地址”+mDeviceAddress);
mBluetoothDevice=mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog=ProgressDialog.show(此“连接…”,mBluetoothDevice.getName()+”:“+mBluetoothDevice.getAddress(),true,false);
线程mBlutoothConnectThread=新线程(此线程);
mBlutoothConnectThread.start();
Toast.makeText(getBaseContext(),mBluetoothDevice.getAddress(),10000.show();
//NewMessage.macaddress=mDeviceAddress;
}
打破
案例请求\u启用\u BT:
如果(mResultCode==Activity.RESULT\u确定)
{
ListPairedDevices();
Intent connectIntent=新的Intent(Scan.this,DeviceListActivity.class);
startActivityForResult(连接内容、请求连接设备);
} 
其他的
{
Toast.makeText(Scan.this,“Message”,2000).show();
}
打破
}
}
私有void ListPairedDevices()
{
设置mPairedDevices=mBluetoothAdapter.getBondedDevices();
如果(mPairedDevices.size()>0)
{
用于(蓝牙设备mDevice:mPairedDevices)
{
Log.v(标记“PairedDevices:+mDevice.getName()+”+mDevice.getAddress());
}
}
}
公开募捐
{
尝试
{
mBluetoothSocket=mBluetoothDevice.CreateSecurerCommsocketToServiceRecord(ApplicationUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
字符串message=“欢迎使用SmarTec”;
byte[]tosend=message.getBytes();
OutputStream out=mBluetoothSocket.getOutputStream();
写出(tosend);
}
捕获(IOException eConnectException)
{
Log.d(标记“CouldNotConnectToSocket”,eConnectException);
闭式插座(mBluetoothSocket);
返回;
}
}
专用void closeSocket(BluetoothSocket nOpenSocket)
{
尝试
{
nOpenSocket.close();
日志d(标签“SocketClosed”);
} 
捕获(IOEX异常)
{
Log.d(标记“CouldNotClo
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

@SuppressLint("NewApi")
public class Scan extends Activity implements Runnable 
{
    protected static final String TAG = "TAG";
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    Button mScan;
    //BluetoothAdapter mBluetoothAdapter;

    private BluetoothAdapter mBluetoothAdapter = null;
    private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ProgressDialog mBluetoothConnectProgressDialog;
    private BluetoothSocket mBluetoothSocket;
    BluetoothDevice mBluetoothDevice;

    String MESSAGEPASS;

    @Override
    public void onCreate(Bundle mSavedInstanceState) 
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.scan);
        mScan = (Button) findViewById(R.id.Scan);
        mScan.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View mView) 
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null) 
                {
                    Toast.makeText(Scan.this, "Message1", 2000).show();
                } 
                else 
                {
                    if (!mBluetoothAdapter.isEnabled()) 
                    {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    } 
                    else 
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Scan.this, DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);

                    }
                }
            }
        });

    }

    public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent) 
    {
        super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

        switch (mRequestCode) 
        {
            case REQUEST_CONNECT_DEVICE:
                if (mResultCode == Activity.RESULT_OK) 
                {
                    Bundle mExtra = mDataIntent.getExtras();
                    String mDeviceAddress = mExtra.getString("DeviceAddress");
                    Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
                    mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);

                    Thread mBlutoothConnectThread = new Thread(this);
                    mBlutoothConnectThread.start();

                    Toast.makeText(getBaseContext(), mBluetoothDevice.getAddress(), 10000).show();
                   // NewMessage.MacAddressesss=mDeviceAddress;
                 }
                break;

            case REQUEST_ENABLE_BT:
                if (mResultCode == Activity.RESULT_OK) 
                {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(Scan.this, DeviceListActivity.class);
                    startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                } 
                else 
                {
                    Toast.makeText(Scan.this, "Message", 2000).show();
                }
                break;
        }
    }

    private void ListPairedDevices() 
    {
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
        if (mPairedDevices.size() > 0) 
        {
            for (BluetoothDevice mDevice : mPairedDevices) 
            {
                Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
            }
        }
    }

    public void run() 
    {
        try 
        {
            mBluetoothSocket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothSocket.connect();
            mHandler.sendEmptyMessage(0);
            String messsage = "Welcome to SmarTec";
            byte[] tosend=messsage.getBytes();
            OutputStream out=mBluetoothSocket.getOutputStream();
            out.write(tosend);

        }
        catch (IOException eConnectException) 
        {
            Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
             closeSocket(mBluetoothSocket);
             return;
        }
    }

    private void closeSocket(BluetoothSocket nOpenSocket) 
    {
        try 
        {
            nOpenSocket.close();
            Log.d(TAG, "SocketClosed");
        } 
        catch (IOException ex) 
        {
            Log.d(TAG, "CouldNotCloseSocket");
        }
    }

    private Handler mHandler = new Handler() 
    {
        @Override
        public void handleMessage(Message msg) 
        {
            mBluetoothConnectProgressDialog.dismiss();
            Toast.makeText(Scan.this, "Device Connected", 5000).show();


        }
    };



}
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class DeviceListActivity extends Activity 
{
    protected static final String TAG = "TAG";
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle mSavedInstanceState) 
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.device_list);

        setResult(Activity.RESULT_CANCELED);
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

        ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
        mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
        mPairedListView.setOnItemClickListener(mDeviceClickListener);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();

        if (mPairedDevices.size() > 0) 
        {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice mDevice : mPairedDevices) 
            {
                mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
            }
        } 
        else 
        {
            String mNoDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(mNoDevices);
        }
    }

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        if (mBluetoothAdapter != null) 
        {
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong) 
        {
            mBluetoothAdapter.cancelDiscovery();
            String mDeviceInfo = ((TextView) mView).getText().toString();
            String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
            Log.v(TAG, "Device_Address " + mDeviceAddress);

            Bundle mBundle = new Bundle();
            mBundle.putString("DeviceAddress", mDeviceAddress);
            Intent mBackIntent = new Intent();
            mBackIntent.putExtras(mBundle);
            setResult(Activity.RESULT_OK, mBackIntent);
            finish();
        }
    };

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