Как решить Android-ошибку в списке ibeacon с библиотекой altbeacon? - PullRequest
0 голосов
/ 23 апреля 2019

Я сканирую устройство ibeacon на Android с библиотекой altbeacon.У меня есть 2 устройства ibeacon.Я уже могу сканировать ibeacon, но его нет в списке.это просто показывает 1 устройство, но я хочу показать 2 устройства, которые у меня были.

это мой код (MainActivity)

public class MainActivity extends AppCompatActivity implements BeaconConsumer {

protected static final String TAG = "MainActivity";
private BeaconManager beaconManager;

private BluetoothAdapter bluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private int REQUEST_ENABLE_LOCATION = 1;

private List<Beacon> beaconDevice;
private RecyclerView rv;
private BeaconAdapter adapter;

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

    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "BLE Not Supported", Toast.LENGTH_SHORT).show();
    }

    //bluetooth manager
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();

    if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            MainActivity.this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_ENABLE_LOCATION);
        return;
    }

    final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE );

    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
        enableGPS();

    //beacon library
    beaconManager = BeaconManager.getInstanceForApplication(this);
    // To detect proprietary beacons, you must add a line like below corresponding to your beacon
    // type.  Do a web search for "setBeaconLayout" to get the proper expression.
     beaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
    beaconManager.bind(this);

    //ui
    rv = findViewById(R.id.recyclerview);
    rv.setLayoutManager(new LinearLayoutManager(this));

}

private void enableGPS() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Enable",
                    new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id){
                            Intent callGPSSettingIntent = new Intent(
                                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(callGPSSettingIntent);
                        }
                    });
    alertDialogBuilder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    dialog.cancel();
                }
            });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

@Override
protected void onResume() {
    super.onResume();
    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    beaconManager.unbind(this);
}

@Override
public void onBeaconServiceConnect() {
    beaconManager.removeAllRangeNotifiers();
    beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
            if (beacons.size() > 0) {
                beaconDevice = new ArrayList<>(beacons);
                adapter = new BeaconAdapter(getApplicationContext(),beaconDevice);
                rv.setAdapter(adapter);
            }
        }
    });

    try {
        beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
    } catch (RemoteException e) {
        Toast.makeText(MainActivity.this, "error: "+e, Toast.LENGTH_LONG).show();

    }
}

Адаптер

public class BeaconAdapter extends RecyclerView.Adapter<BeaconAdapter.BeaconViewHolder> {

private Context context;
private List<Beacon> beacons;

public BeaconAdapter(Context context, List<Beacon> beacons) {
    this.context = context;
    this.beacons = beacons;
}

@NonNull
@Override
public BeaconViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(context).inflate(R.layout.beacon_item, viewGroup, false);
    return new BeaconViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull BeaconViewHolder holder, int position) {
    Beacon beacon = beacons.get(position);
    holder.uuid.setText(String.valueOf(beacon.getId1()));
    holder.major.setText(String.valueOf("major: "+beacon.getId2()));
    holder.minor.setText(String.valueOf("minor: "+beacon.getId3()));
    holder.distance.setText(String.valueOf("distance: "+beacon.getDistance()+" m"));
    holder.mac.setText(beacon.getBluetoothAddress());
    holder.rssi.setText("RSSI: " + beacon.getRssi());
}

@Override
public int getItemCount() {
    return beacons.size();
}

public class BeaconViewHolder extends RecyclerView.ViewHolder{

    private TextView uuid,major,minor,distance,rssi,mac;

    public BeaconViewHolder(@NonNull View itemView) {
        super(itemView);

        uuid = itemView.findViewById(R.id.uuid);
        distance = itemView.findViewById(R.id.distance);
        major = itemView.findViewById(R.id.major);
        minor = itemView.findViewById(R.id.minor);
        rssi = itemView.findViewById(R.id.rssi);
        mac = itemView.findViewById(R.id.mac);
    }
}

Я думаю, мой код выше был в порядке.но когда я запускаю приложение, оно просто показывает 1 устройство, как это изображение

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...