首页 > 解决方案 > 即使在后台,如何使用蓝牙运行服务?

问题描述

我需要一项服务,该服务始终在运行,并且不时启动蓝牙发现。我看到了限制和谷歌文档并尝试了一些东西。就像乔布斯一样,但是,我不知道我是否做得正确,但我总是不得不重新安排工作,这让我的控制变量回到了初始状态。所以我尝试了下面的另一种方法:用户打开应用程序的那一刻,mainactivity 启动服务。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

                Log.d("TestService", "Inside_Method");
                //JobServiceUtil.scheduleJob(getApplicationContext());
                ContextCompat.startForegroundService(this, new Intent(getContext(), IntentServiceEm.class));
    }

然后我的 IntentService 运行:

 public class IntentServiceEm extends Service implements LocationListener {
                 ...

                @Override
                public void onCreate() {
                    super.onCreate();
            Log.d(TAG, "onCreate");

            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            //wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            //        "IntentServiceEm:Wakelock");
            //wakeLock.acquire();
            Log.d(TAG, "Wakelock acquired");
            mBluetoothAdapter = BluetoothMethods.returnBluetoothAdapter(this);
            if (mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }

    /*        receiver = new MyBroadcastReceiverEm();
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            this.registerReceiver(receiver, filter);*/
                    startForengroundEm();

                }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            receiver = new MyBroadcastReceiverEm();
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            this.registerReceiver(receiver, filter);

            if (mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }

            mBluetoothAdapter.startDiscovery();
            return START_STICKY;
        }

                private void startForengroundEm() {
                    Log.d(TAG, "myOwnForeground BLE");
                    String NOTIFICATION_CHANNEL_ID = "channelID";
                    String channelName = "My Background Service BLE";
                    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
                    chan.setLightColor(Color.TRANSPARENT);
                    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    assert manager != null;
                    manager.createNotificationChannel(chan);


                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
                    Notification notification = notificationBuilder.setOngoing(true)
                            .setSmallIcon(R.drawable.icon)
                            .setContentTitle("Foreground Notification")
                            .setPriority(NotificationManager.IMPORTANCE_DEFAULT)
                            .setCategory(Notification.CATEGORY_SERVICE)
                            .build();
                    startForeground(990, notification);
                }

                @Override
                protected void onHandleIntent(@Nullable Intent intent) {
                    Log.d(TAG, "onHandleIntent");
                   // mBluetoothAdapter.startDiscovery();
                    //mBluetoothAdapter.startLeScan(leScanCallback);

                    Log.d(TAG, "startLeScan");

                    // mBluetoothAdapter.stopLeScan(leScanCallback);

                }
                @Override
                public void onLocationChanged(Location location) {
                    Log.d(TAG, "OnLocationChanged");
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }

             private void fn_getlocation() {
                    Log.d(TAG, "getLocation");
                    unregisterReceiver(receiver);
                    locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
                    isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                    isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(firstTime){
        ...
        }
            }

                public class MyBroadcastReceiverEm extends BroadcastReceiver {
                    // private static final String TAG = "MyBroadcastReceiver";
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();
                        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                            // Discovery has found a device. Get the BluetoothDevice
                            // object and its info from the Intent.
                            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            String deviceName = device.getName();
                            String deviceHardwareAddress = device.getAddress(); // MAC address
                            if (deviceHardwareAddress.equals(SaveSharedPreferences.getMacDevice(IntentServiceEm.this))) {
                                mBluetoothAdapter.cancelDiscovery();
                                Log.d(TAG, "Inside IF Device: " + device.getAddress() + " Preferences: " + SaveSharedPreferences.getMacDevice(IntentServiceEm.this));
                                Log.d(TAG, "deviceIsEqualsPreferences");
                                fn_getlocation();
                                Log.d(TAG, "cancelDiscovery");
                            }

                        }
                    }
                }

            }

但是,我遇到了一些问题,服务只运行一次就无法继续,我怎样才能让它“永远”运行?

使用服务编辑代码,几乎相同:

public class IntentServiceEm extends Service implements LocationListener {

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        //wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        //        "IntentServiceEm:Wakelock");
        //wakeLock.acquire();
        Log.d(TAG, "Wakelock acquired");
        mBluetoothAdapter = BluetoothMethods.returnBluetoothAdapter(this);
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

/*        receiver = new MyBroadcastReceiverEm();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(receiver, filter);*/
        startForengroundEm();
        Log.d(TAG,"startCommand");

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        receiver = new MyBroadcastReceiverEm();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(receiver, filter);

        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        mBluetoothAdapter.startDiscovery();
        return START_STICKY;
    }

        private void startForengroundEm() {
        Log.d(TAG, "myOwnForeground BLE");
        String NOTIFICATION_CHANNEL_ID = "app.app_app";
        String channelName = "My Background Service BLE";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        chan.setLightColor(Color.TRANSPARENT);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.applogin)
                .setContentTitle("app está te protegendo em segundo plano")
                .setPriority(NotificationManager.IMPORTANCE_DEFAULT)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(990, notification);
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        mBluetoothAdapter.startDiscovery();
        Log.d(TAG, "myOwnForeground BLE Discovery");
    }
    private void fn_getlocation() {
    .....
    }
    public class MyBroadcastReceiverEm extends BroadcastReceiver {
        // private static final String TAG = "MyBroadcastReceiver";
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                if (deviceHardwareAddress.equals(SaveSharedPreferences.getMacDevice(IntentServiceEm.this))) {
                    mBluetoothAdapter.cancelDiscovery();
                    Log.d(TAG, "Inside IF Device: " + device.getAddress() + " Preferences: " + SaveSharedPreferences.getMacDevice(IntentServiceEm.this));
                    Log.d(TAG, "deviceIsEqualsPreferences");
                    fn_getlocation();
                    Log.d(TAG, "cancelDiscovery");
                }

            }
        }
    }

}

标签: android

解决方案


推荐阅读