Partial wake lock is not working

我们两清 提交于 2021-02-19 03:36:15

问题


My application is having activities and background service which has to run 24*7,

My application has to talk to the server via Wi-Fi to send and receive the information.

Problem: whenever any alarm send by the server my app should receive and pops up the app whether it is running in foreground or background and intimate to the user about the alarm.

So when device is in active state this feature working perfectly but when device goes to sleep mode, after 1 or 2 mins it disconnects from the server and stop communicating. so in order to resolve it I written code which will set the WiFi sleep policy to NEVER and acquire the partial lock in the OnCreate() method of Background service and releasing the lock in OnDestroy() method of the service.Now observation is for some time it is working fine means for 5 or 10 mins thereafter again it stop communicating.

App is developed on Android 2.1 and deployed on device supports Android 2.3 version.

I am not able to understand why partial lock behaves like this, please help me to resolve this issue.

regards, Piks.


回答1:


I was also facing the same problem and finally found the solution which works perfectly.

Try to acquire the wake lock by extending Application class: Code:

package com.example.MyApp.UserView;

import android.app.Application;
import android.content.Intent;
import android.os.PowerManager;
import android.provider.Settings;

/**
 * @author SDurai
 * 
 */
public class MyApp extends Application 
{
    private static final String TAG = MyApp.class.getSimpleName();
    private PowerManager.WakeLock mWakeLock = null;

    @Override
    public void onCreate() {
        super.onCreate();

        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();
    }

    @Override
    public void onTerminate() {
        if (mWakeLock.isHeld())
            mWakeLock.release();
        super.onTerminate();
    }
}

Let me know if you have any other doubts. Ready to help!




回答2:


You probably need a WifiManager.WifiLock, too:

WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wl = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "myId");
wl.acquire();

(where wl is your WifiManager.WifiLock, which s)



来源:https://stackoverflow.com/questions/9000563/partial-wake-lock-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!