以编程方式配对蓝牙设备

时间:2014-06-28 13:01:17

标签: android

package com.example.bt02_connect;
import java.lang.reflect.Method;

 import android.support.v7.app.ActionBarActivity;
 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.View.OnClickListener;
 import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.Toast;
 public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button button1;
private Button button2;
private  ArrayAdapter<String> btArrayAdapter;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(this);
    button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(this);
}   

@Override
public void onClick(View v) {  
    int id = v.getId();
     if (id == R.id.button1) {
         if (!mBluetoothAdapter.isEnabled()) {
         mBluetoothAdapter.enable();
             }
         }
      else if (id== R.id.button2) {
      btArrayAdapter.clear(); 
      mBluetoothAdapter.startDiscovery();
      Toast.makeText(MainActivity.this, "Scanning Devices", Toast.LENGTH_LONG).show();
        }
        }
        }

我试图在按钮2上进行扫描设备, 它没有向我展示吐司所以这个按钮出了问题。我想这就是问题所在。       我用button2解决了问题,现在当我点击它崩溃时。

2 个答案:

答案 0 :(得分:1)

不要只是复制/粘贴你在其他地方找到的代码。

  1. 检查括号。你遗失了很多。
  2. pairDevice()之外定义函数onClick并在onClick上调用它。

答案 1 :(得分:0)

ublic void pairDevice(BluetoothDevice device)
{
    String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
    Intent intent = new Intent(ACTION_PAIRING_REQUEST);
    String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
    intent.putExtra(EXTRA_DEVICE, device);
    String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
    int PAIRING_VARIANT_PIN = 0;
    intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(EXTRA_DEVICE, device);
int PAIRING_VARIANT_PIN = 272;
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
sendBroadcast(intent);

Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(intent, REQUEST_PAIR_DEVICE);

我希望这会有所帮助

参考:http://pastebin.com/N8dR4Aa1

相关问题