Диспетчер работ с Broadcast Receiver не работает, когда приложение закрыто - PullRequest
0 голосов
/ 10 июня 2019

Я просто хочу оставить Bluetooth, и для этого я прослушиваю состояние Bluetooth, и если он выключен, приемник вещания может включить его. И я хочу, чтобы он запускался , когда приложение тоже закрыто . Поэтому я пытаюсь запустить широковещательный прием Bluetooth * даже после закрытия приложения (когда оно не работает). Для этого я узнал, что мне нужно использовать Work Manager для поддержки всех устройств. Я пытался объединить Broadcast Receiver и Work Manager . Но мне не удалось заставить его работать, когда приложение закрыто.

Это мой MainActivity.java Здесь я поставил рабочий запрос в очередь.

package com.example.workmanagersample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

public class MainActivity extends AppCompatActivity {

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

        final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).build();
        WorkManager.getInstance().enqueue(workRequest);

    }
}

Следующий класс - мой MyWorker.java Здесь я зарегистрировал получателя.

package com.example.workmanagersample;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import androidx.work.Worker;
import androidx.work.WorkerParameters;


public class MyWorker extends Worker {
    private BlueToothBroadcastReceiver myReceiver;

    public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    /*
     * This method is responsible for doing the work
     * so whatever work that is needed to be performed
     * we will put it here
     *
     * For example, here I am calling the method displayNotification()
     * It will display a notification
     * So that we will understand the work is executed
     * */

    @NonNull
    @Override
    public Result doWork() {
        displayNotification("My Worker", "Hey I finished my work");


        setReceiver();

        return Worker.Result.success();
    }

    /*
     * The method is doing nothing but only generating
     * a simple notification
     * If you are confused about it
     * you should check the Android Notification Tutorial
     * */
    private void displayNotification(String title, String task) {
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("simplifiedcoding", "simplifiedcoding", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "simplifiedcoding")
                .setContentTitle(title)
                .setContentText(task)
                .setSmallIcon(R.mipmap.ic_launcher);

        notificationManager.notify(1, notification.build());
    }


    private void setReceiver() {
        myReceiver = new BlueToothBroadcastReceiver();
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        getApplicationContext().registerReceiver(myReceiver, filter);

    }
}

Следующий класс - мой BlueToothBroadcastReceiver.java Здесь я слушаю, изменилось ли состояние Bluetooth, и попытался открыть его, если он выключился. Это работало, когда приложение работает. Но я хотел, чтобы это работало и в том случае, если приложение закрыто, но я не смог этого добиться.

package com.example.workmanagersample;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BlueToothBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final 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:
                    setBluetooth(true);
                    // Bluetooth has been turned off;
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    setBluetooth(true);
                    // Bluetooth is turning off;
                    break;
                case BluetoothAdapter.STATE_ON:
                    // Bluetooth has been on
                    break;
                case BluetoothAdapter.STATE_DISCONNECTING:
                    setBluetooth(true);
                    // Bluetooth is turning on
                    break;

                case BluetoothAdapter.STATE_DISCONNECTED:
                    setBluetooth(true);
                    // Bluetooth is turning on
                    break;
            }
        }
    }

    public static boolean setBluetooth(boolean enable) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        boolean isEnabled = bluetoothAdapter.isEnabled();
        if (enable && !isEnabled) {
            return bluetoothAdapter.enable();
        }
        else if(!enable && isEnabled) {
            return bluetoothAdapter.disable();
        }
        // No need to change bluetooth state
        return true;
    }
}

Наконец, мой Манифест файл;

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.workmanagersample">

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".BlueToothBroadcastReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
                <action android:name="android.bluetooth.adapter.action.STATE_OFF"/>
                <action android:name="android.bluetooth.adapter.action.STATE_TURNING_OFF"/>
                <action android:name="android.bluetooth.adapter.action.STATE_ON"/>
                <action android:name="android.bluetooth.adapter.action.STATE_DISCONNECTING"/>
                <action android:name="android.bluetooth.adapter.action.STATE_DISCONNECTED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Я решил использовать Диспетчер работ после исследования в выходные, но он не работал, когда я закрывал приложение. Есть ли что-то, чего мне не хватает или есть какие-то ограничения? Если так, как я могу решить это? Любая помощь могла бы быть полезна! Спасибо!

Ответы [ 2 ]

0 голосов
/ 10 июня 2019

WorkManager предназначен для выполнения задач, даже если ваше приложение находится в фоновом режиме. Вы можете назначить некоторые ограничения вашим классам Worker, чтобы они выполнялись только при соблюдении этих ограничений (т. Е. Наличие ограничений на соединение WiFi, если вам необходимо загрузить некоторые данные на сервер).

ЭТО , поэтому WorkManager использует широковещательные приемники (до уровня API 22) или JobScheduler: чтобы знать, когда эти ограничения изменяются.

Как и другие ответили, вам нужно использовать Службу (и, вероятно, хорошей идеей будет Служба Foreground, если вам нужно запускать ее в течение длительного времени). Несколько вещей, которые вы должны оценить:

  1. Сначала проверьте сценарии для Foreground Services. Рассмотрите этот пост в блоге
  2. Затем документация по приоритетным службам .
  3. Наконец, обзор Bluetooth .
0 голосов
/ 10 июня 2019

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...