Проблема с registerReceiver

#android #bluetooth

#Android #bluetooth

Вопрос:

Код не входит в registerReceiver функцию. Не могли бы вы мне помочь, пожалуйста (или порекомендовать пример кода, который я мог бы просмотреть)? Я пытаюсь найти доступные устройства Bluetooth.

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



                }
            }
        }
    });


}
  

}

Комментарии:

1. вы можете зарегистрировать BroadcastReceiver вне OnClickListener. В противном случае ваша активность будет пытаться зарегистрировать уже зарегистрированного получателя при каждом нажатии. Кроме того, не забудьте отменить регистрацию получателя после того, как он больше не нужен.

2. Код не вводит действие, найденное в части кода……….. я перепроверил, чтобы найти любые доступные устройства по Bluetooth телефона, и я могу найти несколько .. где, как и в приложении, которое я создал, это невозможно… можете ли вы мне помочь?