繁体   English   中英

Wakelock和wifilock无法正常工作

[英]Wakelock and wifilock not working

我已经阅读了很多关于使用WakeLock和WifiLock的教程和帖子,但仍然无法解决我的问题。

我正在编写一个应用程序,当你启动它时,创建和启动(前台)服务的唯一效果。 此服务运行两个线程,这些线程是UDP广播侦听器(使用java.io)和TCP服务器(使用java.nio)。 在服务的onCreate中,我获得了一个唤醒锁和一个wifilock,然后我在onDestroy中释放它们。

一旦电话处于唤醒状态,一切正常,但当显示屏关闭时,UDP广播接收器停止接收广播消息,直到我再次打开显示屏才会收到任何消息。 实际上,锁根本不起作用,把它们放在一起没有区别......我哪里错了? 我确定我在某个地方做了一些蠢事,但是我自己找不到。

这是一些代码:

这就是Activity的作用:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    onlyStartService = true;
}@Override
protected void onStart() {
    super.onStart();
    Intent bIntent = new Intent(this, FatLinkService.class);
    getApplicationContext().startService(bIntent);
    getApplicationContext().bindService(bIntent, flConnection, BIND_AUTO_CREATE);
} 
// service connection to bind idle service
private ServiceConnection flConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
       linkService.MyLinkBinder flBinder = (LinkService.MylinkBinder) binder;
       flServiceInstance = flBinder.getService();
       if (onlyStartService) {
           condLog("Service bound and finishing activity...");
           finish();
       }
    }
    public void onServiceDisconnected(ComponentName className) {
        flServiceInstance = null;
    }
}; 
@Override
protected void onStop() {
    super.onStop();

    if (fatFinish) {
        Intent bIntent = new Intent(this, FatLinkService.class);
        flServiceInstance.stopServices();
        flServiceInstance.stopForeground(true);
        flServiceInstance.stopService(bIntent);
        condLog("Service stop and unbound");
        flServiceInstance = null;
    }
    getApplicationContext().unbindService(flConnection);
}

这就是服务的方式:

public class LinkService extends Service {
    InetAddress iaIpAddr, iaNetMask, iaBroadcast;
    private final IBinder mBinder = new MyLinkBinder();
    private linklistenBroadcast flBroadServer = null;
    private linkTCPServer flTCPServer = null;
    private linkUDPClient flBroadClient = null;
    List<String> tokens = new ArrayList<String>();
    private PowerManager.WakeLock wakeLock;
    private WifiManager.WifiLock wifiLock;

public class MylLinkBinder extends Binder {
    lLinkService getService() { return LinkService.this; }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{        
    instantiateServices();
    // notifies presence to other fat devices
    condLog("Service notifying fat presence...");
    flBroadClient = new LinkUDPClient();
    flBroadClient.startSending(LinkProtocolConstants.BRCMD_PRESENCE + String.valueOf(LinkProtocolConstants.tcpPort), iaBroadcast, LinkProtocolConstants.brPort);
    return START_STICKY;
}

public void getLocks() {
    // acquire a WakeLock to keep the CPU running
    condLog("Acquiring power lock");
    WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
    wifiLock.acquire();
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wakeLock.acquire();
}

public void stopServices() {
    if (flTCPServer != null)
        flTCPServer.stopServer();
    if (flBroadServer != null)
        flBroadServer.stopSelf();
}

private void instantiateServices() {
    populateAddresses(); // just obtain iaIpAddr  
    if (flTCPServer == null) {
        condLog("Instantiating TCP server");
        flTCPServer = new LinkTCPServer(iaIpAddr, FatLinkProtocolConstants.tcpPort);
        flTCPServer.execute();
    }
    if (flBroadServer == null) {
        condLog("Instantiating UDP broadcast server");
        Intent notifyIntent = new Intent(this, LinkMain.class); // this is the main Activity class
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        notifyIntent.setAction("FROM_NOTIFICATION");
        PendingIntent notifyPIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);

        Notification fixNotification = new Notification.Builder(getApplicationContext())
                .setContentTitle("Link")
                .setSmallIcon(R.mipmap.imgLink)
                .setContentIntent(notifyPIntent)
                .build();
        startForeground(1234, fixNotification);
        flBroadServer = new LinklistenBroadcast();
        flBroadServer.start();
    }
}

private final class LinklistenBroadcast extends Thread {
    private boolean bStopSelf = false;
    DatagramSocket socket;
    public void stopSelf() {
        bStopSelf = true;
        socket.close();
    }

    @Override
    public void run() {
        condLog( "Listening broadcast thread started");
        bStopSelf = false;
        try {
        //Keep a socket open to listen to all the UDP trafic that is destinated for this port
        socket = new DatagramSocket(null);
        socket.setReuseAddress(true);
        socket.setSoTimeout(LinkGeneric.BR_SOTIMEOUT_MILS);
        socket.setBroadcast(true);
        socket.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), FatLinkProtocolConstants.brPort));
        while (true) {
                condLog("Ready to receive broadcast packets...");
                //Receive a packet
                byte[] recvBuf = new byte[1500];

                DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
                try {
                    socket.receive(packet);
                } catch (InterruptedIOException sException) {
                    condLog(sockExcept.toString());
                    break;
                } catch (SocketException sockExcept) {
                   condLog(sockExcept.toString());
                }
                if (bStopSelf) {
                    condLog("Broadcast server stopped...");
                    break;
                }
                int len = packet.getLength();
                String datarecvd = new String(packet.getData()).trim();
                //datarecvd = datarecvd.substring(0, len);
                //Packet received
                String message = new String(packet.getData()).trim();
                condLog("<<< broadcast packet received from: " + packet.getAddress().getHostAddress() + " on port: " + packet.getPort() + ", message: " + message);
                if (packet.getAddress().equals(iaIpAddr)) {
                    condLog("Ooops, it's me! discarding packet...");
                    continue;
                }
                else
                    condLog("<<< Packet received; data size: " + len + " bytes, data: " +  datarecvd);

                //See if the packet holds the right command (message)

                // protocol decode
                // here do some tuff
        } catch (IOException ex) {
            condLog(ex.toString());
        }

        if (socket.isBound()) {
            condLog( "Closing socket");
            socket.close();
        }
        condLog( "UDP server thread end.");
        flTCPServer = null;
        flBroadServer = null;
    }

    public boolean isThreadRunning() {
        return !bStopSelf;
    };
}

// Utility functions
public boolean checkBroadcastConnection (DatagramSocket socket, int timeOutcycles) {
    int tries = 0;
    while (!socket.isConnected()) {
        tries++;
        if (tries >= timeOutcycles)
            return false;
    }
    return true;
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (wakeLock != null) {
        if (wakeLock.isHeld()) {
            wakeLock.release();                
        }
    }
    if (wifiLock != null) {
        if (wifiLock.isHeld()) {
            wifiLock.release();
        }
    }
}

}

而且,最后,这是清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xxxxxx.ink" >
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/imgLinkmascotte"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LinkMain"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".LinkService" />
    </application>
</manifest>
  • 我已经读过这个了 ,我怀疑这个问题是一样的,但它实际上发生在我试过的所有手机上(Galaxy Tab 7.1,galaxy tag 10,Galaxy SIII,Galaxy Note 3 Neo,Galaxy SIII mini)安卓从4.0到4.4发布。

  • 我已经尝试过这里发布的解决方案,但任何改变了(再次......这有点令人沮丧)。

  • 我甚至试图在我试过的所有手机中将“保持wifi待机状态”设置为“始终”,但仍然没有。

  • 我已经研究过WakeFulIntentService类,它应该可以正常工作,因为每个人都说它是,但我在代码中看不到任何显着的不同。

我真的希望有人可以帮助我,自上周以来我真的坚持这个。

编辑:按照waqaslam的答案,我已经检查了Wifi-Advaced设置中具有“Wifi优化”选项的设备,它实际上在我取消选项后立即工作。 那么,现在,问题变成了:我可以在没有高级菜单中显示的选项的设备中禁用Wifi优化吗? 正如我在评论中写的那样,这似乎与Android版本没有关系,因为我有两个设备(两个都是三星)和4.4.2,他们没有显示选项。

新编辑:从编辑过的waqaslam回答中,我试图将多播锁添加到我的服务中,但是一切都改变了。 这变得很烦人,几乎没有什么容易和安全的android。

非常感谢C.

我认为问题不在于WakeLocks,而在于Wi-Fi设置。

在较新版本的Android中,设置中有一个额外的设置 - > Wi-Fi - > 高级称为Wi-Fi optimization ,当显示为时,(如果已打开)禁用所有低优先级通信(如收听UDP广播)关闭。

禁用该选项应允许您的设备监听UDP广播,即使关闭显示器也是如此。

Wi-Fi优化


你也可以使用WifiManager.MulticastLock获取WiFi锁,当你关闭屏幕时应该收听这些特殊的广播。

WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("lockWiFiMulticast");
lock.setReferenceCounted(false);
lock.acquire();

当完成锁定时,然后调用:

lock.release();

另外,不要忘记向清单添加以下权限:

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

有关详细信息,请阅读此内容

写这只是为了将帖子标记为已回答。 我终于明白,没有解决方案,或者至少没有解决方案在“所有”Android手机分配(或至少从JB)手机上运行良好。

我已经解决了我的个人问题,只是重新审视了我的应用程序的概念,考虑到: - 即使在空闲模式下发送UDP广播总是工作 - TCP服务器不受WiFi优化的影响。

谢谢大家的帮助和建议C.

可能的原因是这个

从Android 6.0(API级别23)开始,Android引入了两项省电功能,通过管理设备未连接电源时应用程序的行为方式,延长了用户的电池续航时间。 当设备长时间不使用时,Doze会通过推迟应用程序的后台CPU和网络活动来减少电池消耗。 App Standby推迟用户最近未与之交互的应用的后台网络活动

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM