我有一个工作正常的蓝牙应用程序,其中我创建了一个广播接收器,我也在onDestroy()
方法上销毁它但是当我按下我的手机上的后退按钮时它显示不幸的是你的应用程序已停止并在Android监视器窗口中显示
[接收者未注册] [1]
@Override
protected void onCreate(Bundle savedInstanceState)
{
BA=BluetoothAdapter.getDefaultAdapter();
filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
} //onCreat End
public void turnOn(View v)
{
if(!BA.isEnabled())
{
Intent turnOn=new Intent(BA.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 1);
Toast.makeText(this,"Turned On",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this,"Already on", Toast.LENGTH_LONG).show();
}
}
public void turnOff(View v)
{
BA.disable();
}
public void getVisible(View v)
{
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void getList(View v)
{
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName()+"\n"+bt.getAddress());
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
TextView v = (TextView) view;
}
});
}
public void exitApp(View v)
{
// finish();
System.exit(0);
}
public void getDiscoveredDevices(View v) // onclick is in XML
{
// BA.startDiscovery();
if(BA.isDiscovering())
{
BA.cancelDiscovery();
}
else {
Toast toast=Toast.makeText(getApplicationContext(),"Device Discovery On",Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP,0,30);
toast.show();
BA.startDiscovery();
mReceiver = new BroadcastReceiver() //// Create a BroadcastReceiver for ACTION_FOUND
{
ArrayList listt = new ArrayList();
// Register the BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) // // When discovery finds a device
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_NAME);// Get the BluetoothDevice object from the Intent
listt.add(device.getName() + "\n" + device.getAddress());
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, listt);
lv.setAdapter(adapter);
Toast toast=Toast.makeText(getApplicationContext(),"Device Found",Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP,0,20);
toast.show();
}
else
{
Toast toast=Toast.makeText(getApplicationContext(),"No Device Found",Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP,0,20);
toast.show();
}
}
};
IntentFilter(BluetoothDevice.ACTION_FOUND);
}
}
@Override
public void onDestroy(){
this.unregisterReceiver(mReceiver);
super.onDestroy();
}
}
} //Class End
答案 0 :(得分:1)
BroadcastReceiver mReceiver
registerReceiver
之前onCreate
尚未初始化mReceiver
,注册时getDiscoveredDevices
为空。虽然您稍后在{{1}}创建它,但它没有在那里注册。至于那个,你试图取消注册一个实际上从未注册的接收器。
所以首先创建你的接收器,然后注册它,反之亦然。