如果在运行之前关闭蓝牙并在运行时打开,则Android蓝牙连接不起作用

时间:2014-07-14 13:20:36

标签: android bluetooth

我实现了一个通过蓝牙找到一些设备的应用程序。按下按钮时执行搜索,如果在运行应用程序之前打开了手机的蓝牙,则搜索结果很好。执行搜索时会显示进度对话框。如果不是,则按下搜索按钮时,会弹出打开蓝牙的通知。我点击是,蓝牙已打开,但现在搜索正在运行而没有给出答案。 这是我的代码:

package com.yast;
import android.app.ProgressDialog;
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.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class ConnectionScreen extends ActionBarActivity {
    //Declaration of components
    private static final String TAG = "ConnectionScreen";
    public static final String BROADCAST = "PACKAGE_NAME.android.action.broadcast";
    private static final int REQUEST_ENABLE_BT = 1;
    private Button buttonSearch;
    private CheckBox checkBoxAutoConnect;
    private ListView listOfDevices;
    private TextView statusId;
    private TextView statusConnection;
    private BluetoothAdapter bluetoothadapt;
    private Set<BluetoothDevice> pairedDevices;
    private ArrayAdapter<String> deviceAdapter;
    private ProgressDialog dialog;


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

        linkViewToResources();


        listOfDevices.setAdapter(deviceAdapter);


        bluetoothadapt = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothadapt == null) {
            statusConnection.setText("Not supported");
            Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth", Toast.LENGTH_LONG).show();
            buttonSearch.setEnabled(false);
        } else {
            buttonSearch.setEnabled(true);
        }


    }


 @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

    }

private void linkViewToResources() {
    buttonSearch = (Button) findViewById(R.id.searchButton);
    buttonSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            find(view);

        }
    });



 checkBoxAutoConnect = (CheckBox) findViewById(R.id.checkBoxAutoconnect);
    listOfDevices = (ListView) findViewById(R.id.listOfDevices);
    deviceAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
}

    final BroadcastReceiver bReceiver = new BroadcastReceiver() {
        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);
                // add the name and the MAC address of the object to the arrayAdapter
                // get paired devices
                if (device.getName().startsWith("HXM") && device.getName().length() == 9) {
                    deviceAdapter.add(device.getName() + "\n" + device.getAddress());
                    //deviceAdapter.notifyDataSetChanged();
                }
            }
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    };


 public void find(View view) {
        if (bluetoothadapt.isDiscovering()) {
            // the button is pressed when it discovers, so cancel the discovery
            bluetoothadapt.cancelDiscovery();
        }
            dialog = new ProgressDialog(ConnectionScreen.this);
            this.dialog.setMessage("Searching");
            this.dialog.show();

            deviceAdapter.clear();
            bluetoothadapt.startDiscovery();
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            sendBroadcast(enableBtIntent);
            //new ProgressTask().execute(null, null, null);
            //////////////////////////



    }



 @Override
    protected void onPause() {
        super.onPause();
        try {
            if (bReceiver != null) {
                unregisterReceiver(bReceiver);
            }
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }


 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.connection_screen, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

1 个答案:

答案 0 :(得分:0)

启用蓝牙后,您需要重新启动蓝牙发现:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if( requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_OK ) {
        // A bluetooth was enabled, restart discovery
        if( bluetoothadapt != null )
            bluetoothadapt.startDiscovery();
     }
}