我需要蓝牙发现服务才能工作,即使该应用已被终止或已从堆栈中删除

时间:2019-05-23 17:34:03

标签: android

我有一个通过查找特定的mac地址而工作的应用程序,当我找到它们时,就会触发一个事件。但是,即使应用程序被终止,我也需要此程序才能正常工作,因此用户并不需要总是打开该应用程序。

即使应用程序已死,我也会在这里及其他地方通读有关服务运行问题的问答。 我尝试了将意图服务和作业调度程序添加到广播接收器中。 在那之前,我只在android 8.0上进行过测试,但没有成功。 下面是有关我测试过的蓝牙的测试代码:

public class TestActivity extends AppCompatActivity {

    private TextView txt_testa_botao;
    private Button btn_test_botao;
    private BluetoothAdapter bluetoothAdapter;
    private static final int TIMER_LENGTH = 15;
    private TimerView mTimerView;

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

        btn_test_botao = findViewById(R.id.btn_testa_botao);
        txt_testa_botao = findViewById(R.id.txt_testa_botao);
        mTimerView = (TimerView) findViewById(R.id.timer);

        bluetoothAdapter = BluetoothMethods.returnBluetoothAdapter(this);

        startCountdown();

    }

    private void startCountdown() {
        mTimerView.start(TIMER_LENGTH);
       if(!bluetoothAdapter.isEnabled()){
           bluetoothAdapter.enable();
       }
        new CountDownTimer(15000, 1000) {

            public void onTick(long millisUntilFinished) {
                txt_testa_botao.setText(""+millisUntilFinished / 1000);
            }

            public void onFinish() {
                txt_testa_botao.setVisibility(View.GONE);
                btn_test_botao.setVisibility(View.VISIBLE);
                mTimerView.stop();
                startBluetoohScan();
            }
        }.start();
    }

    private void startBluetoohScan() {
        bluetoothAdapter.startLeScan(leScanCallback);
    }

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
            if (device.getAddress().equals(SaveSharedPreferences.getMacDevice(TestActivity.this))) {
                txt_testa_botao.setVisibility(View.VISIBLE);
                txt_testa_botao.setText("Working well...");
                btn_test_botao.setVisibility(View.GONE);
                bluetoothAdapter.stopLeScan(leScanCallback);
            }
        }
    };
}

当然,此代码会随着从堆栈中删除应用程序而消失。 搜索,我已经看到了Twilight这个应用程序,它始终在运行,并且在适当的时候提供了它应该做的服务。如何构建像这样的东西,但是对于我的问题,或者他用什么呢?这是可能的? 谢谢! enter image description here

0 个答案:

没有答案