代码未进入registerReceiver
功能。你能帮帮我吗(或推荐我可以通过的代码示例)?我正试图找到可用的蓝牙设备。
package com.example.mahe.toddler;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.bluetooth.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Main_Page extends AppCompatActivity {
public BluetoothAdapter btAdapter;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private ArrayList<String> mDeviceList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__page);
final ListView listView = (ListView) findViewById(R.id.listView);
btAdapter=BluetoothAdapter.getDefaultAdapter();
findViewById(R.id.off).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if(btAdapter==null)
{
Toast.makeText(Main_Page.this, "Bluetooth not enabled phone.", Toast.LENGTH_SHORT).show();
}
else
{
if (btAdapter.isEnabled())
{
btAdapter.disable();
}
}
}
});
final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Toast.makeText(getBaseContext(), action,Toast.LENGTH_LONG).show();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_activated_1, mDeviceList));
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
Log.v(" ","discovery Finished ");
}
}
};
findViewById(R.id.on).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if(btAdapter==null)
{
Toast.makeText(Main_Page.this, "Bluetooth not enabled phone.", Toast.LENGTH_SHORT).show();
}
else
{
if (btAdapter.isEnabled())
{
//do nothing
btAdapter.startDiscovery();
}
else
{
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
btAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
}
}
});
}
}