我的蓝牙应用程序有时无法发现设备

时间:2016-03-17 19:02:37

标签: android bluetooth android-bluetooth

我开发了这个Android应用程序(使用在线提供的教程)搜索附近的蓝牙设备&在kernel32.dll中显示它们。

我的应用程序遇到的问题是:

  • 它不会搜索附近的所有设备。如果有6个蓝牙设备保持非常靠近手机,则最大应用检测到4.然而,我的Android手机的实际蓝牙(可通过手机设置访问的那个)显示所有6个。
  • 有时甚至在之前发现的设备都不会出现在下一轮搜索中。

我想知道它是否与我的代码或蓝牙设备本身有关。但话说回来,我的手机的BT始终会检测到所有这些。

这是我的 MainActivity.java

ListView

这是我的 SearchBTDevice.java (这个实际执行搜索操作)

package vertex2016.mvjce.edu.bluealert;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
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.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import static java.lang.Thread.sleep;

public class MainActivity extends AppCompatActivity {

    public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
    private int REQ_CODE = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void connect(View v)
    {
        if(BA == null)
            Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();

        else if(!BA.isEnabled())
        {
            Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBT, REQ_CODE);
        }
        else {
            Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
            searchBTDevices();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_CANCELED) {
            Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
            searchBTDevices();
        }
        else
            Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
    }




    public void searchBTDevices()
    {
        Thread searchThread = new Thread() {
            @Override
            public void run() {
                Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
                startActivity(searchBT);
            }
        };
        searchThread.start();
    }
}

此处为搜索活动的 activity_search_btdevice.xml

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.os.Bundle;
import android.bluetooth.BluetoothAdapter;
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.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;

    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))
           {
               BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                BTArrayAdapter.add(btd.getName() + "\t" + btd.getAddress() + "\n");

           }


       }
    };

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);


    @Override
    protected void onResume() {
        super.onResume();
        this.registerReceiver(BTReceiver,filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.unregisterReceiver(BTReceiver);
    }


    @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);


       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);

    }


}

这是我的搜索活动 content_search_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_search_btdevice" />

</android.support.design.widget.CoordinatorLayout>

这是 AndroidManifest.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.SearchBTDevice"
    tools:showIn="@layout/activity_search_btdevice">


        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/searchpageimageView"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:src="@drawable/bluealert_bg"
            android:scaleType="centerCrop"/>

        <ListView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:id="@+id/searchpagelistView"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="0dp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Nearby Devices"
            android:id="@+id/nearbydevicestextView"
            android:layout_above="@+id/searchpagelistView"
            android:layout_centerHorizontal="true"
            android:textAlignment="center"
            android:textColor="#E7F1FA"/>


</RelativeLayout>

如何让我的应用以手机中的蓝牙方式执行?

感谢您的时间!!

0 个答案:

没有答案