当应用程序在后台运行时,Android Listener 停止运行

标签 android android-bluetooth

我正在开发一个应用程序,该应用程序将检测蓝牙信号(Sensoro Smart Beacon 设备)并打开 Activity 。但我希望应用程序即使在后台应用程序或什至被杀死时仍然能够检测到信号。我使用了前台服务,当我打开应用程序并在 Activity 之间移动时它会检测到信号,但是当将应用程序发送到后台并打开其他应用程序时,虽然服务仍在工作,但监听器会停止。我正在打印日志。 System.out.println("Sensoro 2" );即使我终止应用程序或打开另一个应用程序,也会继续打印。但是 BeaconManagerListener 中的打印日志不起作用。我尝试使用后台服务,但它也不起作用。
当应用程序在后台或被杀死时,您能否告知是否有办法让监听器在服务中工作?
这是服务代码:

public class MyService extends Service {
    public static final String CHANNEL_ID = "ForegroundServiceChannel";
    int service_timer=0;
    Timer timer = new Timer();
    SensoroManager sensoroManager;
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sensoroManager = SensoroManager.getInstance(MyService.this);
        String input = intent.getStringExtra("inputExtra");
        System.out.println("Sensoro 2" );
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1,notification);
        //do heavy work on a background thread
        //stopSelf();
                if (sensoroManager.isBluetoothEnabled()) {
                    sensoroManager.setCloudServiceEnable(true);
                    /**
                     * Enable SDK service
                     **/
                    try {
                        sensoroManager.startService();

                    } catch (Exception e) {
                        e.printStackTrace(); // Fetch abnormal info
                    }
                }
                else
                {
                    Toast.makeText(MyService.this,"Bluetooth off",Toast.LENGTH_LONG).show();
                }
        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
           public void run() {
                //your method
                System.out.println("Sensoro 2" );


                BeaconManagerListener beaconManagerListener = new BeaconManagerListener() {

                    @Override
                    public void onUpdateBeacon(ArrayList<Beacon> beacons) {
                        // Refresh sensor info
                        for (Beacon beacon : beacons
                        ) {
                            System.out.println("Sensoro 3" );
                           // System.out.println("Sensoro" +beacon.getAccuracy());
                        }
                    }

                    @Override
                    public void onNewBeacon(Beacon beacon) {

                        if (beacon.getSerialNumber().equals("0117C59B243C")){
                            System.out.println("Sensoro 3" );
                            System.out.println("Sensoro acc" +beacon.getAccuracy());
                }
            }

                    @Override
                    public void onGoneBeacon(Beacon beacon) {

                        if (beacon.getSerialNumber().equals("0117C59B243C")){
                            System.out.println("Sensoro acc gone");
                            System.out.println("Sensoro acc Timer" +service_timer);
                        }
                    }
                };
                sensoroManager.setBeaconManagerListener(beaconManagerListener);
            }
        }, 0, 2000);



        return START_NOT_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
       // timer.cancel();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }


}
这就是我所说的:
public class MainActivity extends AppCompatActivity {

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


    public void startService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
        System.out.println("Sensoro 1 ");
        ContextCompat.startForegroundService(this, serviceIntent);
    }
    public void stopService() {
        Intent serviceIntent = new Intent(this, MyService2.class);
        stopService(serviceIntent);
    }


    public void movingg(View view) {
        Intent intent=new Intent(this,Usermain.class);
       startActivity(intent);    }
}

最佳答案

这与您搜索的内容不是 100% 匹配,但与您想要的内容很接近。
您可以使用WorkManager这甚至在后台运行应用程序。 WorkManager 有两种类型。 1) OneTimeWorkRequest 2) PeriodicWorkRequest。
所以你可以你PeriodicWorkRequest它将每 15 分钟(最小间隔)调用一次,您可以在 WorkManager 中添加代码以检测蓝牙信号。因此,您可以每隔 15 分钟检测一次蓝牙单。
我希望这能帮助你解决你的问题。

关于当应用程序在后台运行时,Android Listener 停止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69863599/

相关文章:

java - 通过单击 ListView 项目来配对两个蓝牙设备,Android

android - 联系信标 : Inconsistent and unreliable results when determining beacon distance

android - BluetoothA2dpSink 和BluetoothAvrcpController 类无法访问,如何添加到SDK?

java - ffmpeg 在 android 上的视频 http

android - 如何在 fragment 类中声明按钮?

android - MediaPlayer.getDuration() 返回错误的持续时间

java - 如果连接丢失,Android 会重新连接到蓝牙设备

android - 如何在Android中打开原始文件夹中的文件

java - 如果 blob 超过 2MB,getBlob() 会崩溃,substr 方法不起作用

android - 如何在android中显示蓝牙连接状态