проверить расстояние между устройствами Bluetooth в Android - PullRequest
0 голосов
/ 25 августа 2018

Я хочу иметь приложение для Android, которое находит близлежащие устройства Bluetooth и показывает расстояние между ними. Я хочу запустить это в фоновом режиме, что, когда телефон далеко от устройства Bluetooth, приложение показывает уведомление, даже если приложение не работает. Я знаю, что следует использовать Service, но когда я это реализую, это не сработает.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        Intent intent2 = new Intent(MainActivity.this, BR.class);
        startService(intent2);}<br/>

и в своем классе обслуживания я зарегистрировал свой BroadcastReceiver, который находит близлежащие устройства Bluetooth.

public class BR extends IntentService {
        private BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();
    public BR() { super("BR"); }

    protected void onHandleIntent(Intent intent) {
        try {
            PermissionResponse response = PermissionEverywhere.getPermission(getApplicationContext(),
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0,
                    "Notification title",
                    "This app needs  a location permission",
                    R.mipmap.ic_launcher)
                    .call();
            boolean is_Granted=response.isGranted();
            PermissionResponse r2=PermissionEverywhere.getPermission(getApplicationContext(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1,"Title","This app needs permision",R.mipmap.ic_launcher).call();
        boolean is2=r2.isGranted();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        proceedDiscovery();

    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
                ((name) BR.this.getApplication()).setBname(((name) BR.this.getApplication()).getBname() + "\n" + name);
                Toast.makeText(context, ((name) BR.this.getApplication()).getBname(), Toast.LENGTH_LONG).show();
                Toast.makeText(context, "my br happened", Toast.LENGTH_LONG).show();
                double m = 10;
                double m1 = pow(m, (27.55 - (20 * 3.3875) + rssi) / 20);
                String m_meter = Double.toString(m1);
                ((name) BR.this.getApplication()).setMeter(m_meter);
                  if(m1>5)
                send_notification();

            }
        }
    };
    public  void send_notification()
    {
        Toast.makeText(this,"Notif",Toast.LENGTH_LONG).show();
        final Intent emptyIntent = new Intent();
        long[] pattern = {500,500,500,500,500,500,500,500,500};
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext() , 0, emptyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder mn=new NotificationCompat.Builder(this).setSmallIcon(R.drawable.logo)
                .setContentTitle("My notification")
                .setContentText("Hello World!").setPriority(NotificationManager.IMPORTANCE_MAX).setVibrate(pattern).setSound(alarmSound).setFullScreenIntent(pendingIntent,true);

        int mId=1;
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //  NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(mId, mn.build());
    }
    protected void proceedDiscovery() {
        Intent intent=new Intent(BluetoothDevice.ACTION_FOUND);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
        BTAdapter.startDiscovery();

    }


PermissionResponse - это класс из библиотеки, который получает разрешения в службе. и мой BroadcastReceiver получает значение RSSI устройств Bluetooth для измерения расстояния.

...