如何在屏幕关闭时正确地保持phonestatelistener运行?

dzhpxtsq  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(210)

我有一个服务,使用phonestatelistener在手机信息更改时执行任务。当屏幕关闭时,服务仍然运行,但是在屏幕关闭后的一小段时间内,侦听器似乎停止了。
清单权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.INTERNET"/>

我的服务:

public class OnCellChangeService extends Service
{
    private TelephonyManager mTelephonyManager;
    private PowerManager mPowerManager;
    private PowerManager.WakeLock wakeLock;
    private boolean wakeLockSet;

    private PhoneStateListener mPhoneStateListener = new PhoneStateListener()
    {
        @Override
        public void onCellInfoChanged(List<CellInfo> cellInfoList)
        {
            Log.d("Phone Listeneer", "Cell Change");
        }

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength)
        {
            Log.d("Phone Listener", "Signal Strength Changed");
        }
    };

    @Override
    public void onDestroy()
    {
        // stuff
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        mPhoneStateListener = null;
        if (wakeLockSet) wakeLock.release();
        Log.d("Service", "Destroy");
    }

    @Override
    public void onCreate()
    {
        mTelephonyManager = (TelephonyManager) getSystemService(getApplicationContext().TELEPHONY_SERVICE);
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CELL_INFO);

        // stuff
    }

    @SuppressLint("MissingPermission")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        wakeLockSet = intent.getBooleanExtra("Wake Lock", false);

        if (wakeLockSet) setWakeLock();
        // stuff

        return START_REDELIVER_INTENT;
    }

   private void setWakeLock()
    {
        Log.d("Service", "Wake Lock");
        getApplicationContext();
        mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "Service::WakelockTag");
        wakeLock.acquire();
    }

}

我正在开发一个最低的api 27。我试着对此进行研究,但我发现的都是2年多前的答案,而且似乎都有不同的关于安卓手机在关闭屏幕和节省电池时的行为信息。wake锁似乎不能保持侦听器运行。保持侦听器运行的正确方法是什么。前台服务?服务以外的东西?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题