Как подключить маяки с помощью BLE Native Library

Я хочу подключить маяки в Android, используя BLE ( Bluetooth с низким энергопотреблением), а не Alt-маяки.

Заранее спасибо.

1 ответ

Чтобы сначала использовать технологию Beacon с использованием Bluetooth, нам нужно реализовать обратные вызовы соединения googleapiclient, а также код включения Bluetooth.

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private GoogleApiClient mGoogleApiClient = null;
Context context;

private BroadcastReceiver mBroadcastreceiverBTEnable = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

            switch (state) {

                case BluetoothAdapter.STATE_OFF:
                    Log.e(TAG, "mBroadcastreceiverBTEnable : STATE OFF");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.e(TAG, "mBroadcastreceiverBTEnable : STATE TURNING OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.e(TAG, "mBroadcastreceiverBTEnable : STATE ON");
                    //buildGoogleApiClient();
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.e(TAG, "mBroadcastreceiverBTEnable : STATE TURNING ON");
                    break;

            }
        }
    }
};

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

    if (!mBluetoothAdapter.isEnabled()) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_BT);
    } else {
        buildGoogleApiClient();
    }

    connectBluetooth();
}

private void connectBluetooth() {

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter == null) {
        Log.e(TAG, "your bluetooth does not have capabilities");
    }

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_BT);


        *//*IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastreceiverBTEnable, btIntent);*//*

    }

    if (mBluetoothAdapter.isEnabled()) {

        *//*IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastreceiverBTEnable, btIntent);*//*

        checkBTPermissions();

        //buildGoogleApiClient();
    }
}

//Enable google api client after enabling bluetooth and Location Permissions
private synchronized void buildGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Nearby.MESSAGES_API, new MessagesOptions.Builder()
                        .setPermissions(NearbyPermissions.BLE).build())
                .addConnectionCallbacks(this)
                .enableAutoManage(this, this)
                .build();

    }


}

private PendingIntent getPendingIntent() {
    return PendingIntent.getService(this, 0, getBackgroundSubscribeServiceIntent(), PendingIntent.FLAG_UPDATE_CURRENT);
}

private Intent getBackgroundSubscribeServiceIntent() {

    return new Intent(this, BackgroundSubscribeIntentService.class);
}

//Subscribe to the MessageListener on Google Api Connected
@Override
public void onConnected(@Nullable Bundle bundle) {

    subscribe();


}

private void subscribe() {


    mMessageListener = new MessageListener() {
        @Override
        public void onFound(Message message) {
            String messageSting = new String(message.getContent(), Charset.forName("UTF-8"));
            Log.e("beaconMessage", "Found Message : " + messageSting);
            Log.e("beaconMessage", "Message Namespace : " + message.getNamespace());
            Log.e("beaconMessage", "Message type :" + message.getType());
            Log.e("beaconMessage", "Message type :" + messageSting);
            Log.e("beaconMessage", "Message type :" + Arrays.toString(message.getContent()));
        }

        @Override
        public void onLost(Message message) {
            String messageString = new String(message.getContent());
            Log.e("beaconMessage", "Lost sight of message " + messageString);
        }
    };


    if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    } else {

        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(Strategy.BLE_ONLY)
                .build();


        Nearby.Messages.subscribe(mGoogleApiClient, getPendingIntent(), options).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                if (status.isSuccess()) {
                    Log.e("beaconMessage", "Subscribed Succesfully");

                    startService(getBackgroundSubscribeServiceIntent());


                } else {
                    Log.e("beaconMessage", "Operation failed Error : " +
                            NearbyMessagesStatusCodes.getStatusCodeString(status.getStatusCode()));
                    startService(getBackgroundSubscribeServiceIntent());

                }
            }
        });
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

//Enable bluetooth on accepting Permission
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_BT && resultCode == RESULT_OK) {
        mBluetoothAdapter.enable();
        checkBTPermissions();

    } else if (requestCode == REQUEST_BT && resultCode == RESULT_CANCELED) {

        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("Bluetooth Settings")
                .setMessage("Sarath City Capital needs your device's Bluetooth Permission.You can change this at anytime in settings")
                .setPositiveButton("GOTO APP SETTINGS", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // navigate to app settings
                        startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
                    }
                }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //cancel the dialog
                dialog.dismiss();
            }
        });

        AlertDialog dialog = alertDialogBuilder.create();
        dialog.show();

    }
}

//Check Bluetooth Location Permission on Enabling the Bluetooth
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermissions() {

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        int permissionCheck = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        }

        if (permissionCheck != 0) {
            this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION);

        } else {
            Log.e(TAG, "CheckBTPERmissions : No need to check permissions.  SDK Version < Lollipop");
        }
    }
}


//Enable googleApi Client on accepting the Location Permission
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case 1101:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
    }
}

}

Это то, что я попробовал в своем проекте, и я добился успеха в сканировании маяка рядом со мной. Вы можете пинговать меня, если у вас есть какие-либо вопросы. Спасибо.

Другие вопросы по тегам