Wakelock和wifilock无法正常工作

时间:2015-02-20 11:30:02

标签: java android android-wifi wakelock

我已经阅读了大量有关使用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>
  • 我已经阅读了this,我怀疑问题是一样的,但实际上在我尝试过的所有手机上都会发生这种情况(galaxy Tab 7.1,galaxy tag 10,Galaxy SIII ,Galaxy Note 3 Neo,Galaxy SIII mini),安卓版本从4.0到4.4。

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

  • 我甚至尝试将&#34; Keep wifi选项设置为待机状态&#34;总是&#34;总是&#34;在我试过的所有手机中,但仍然没有。

  • 我已经研究过WakeFulIntentService类,应该按照每个人说的那样工作,但我的代码中看不到任何显着的不同。

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

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

新编辑:从编辑过的waqaslam回答中,我试图将多播锁添加到我的服务中,但是再次发生了任何变化。这变得很烦人,对于android来说,几乎没有什么容易和明确的事情。

非常感谢你 下进行。

3 个答案:

答案 0 :(得分:1)

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

在较新版本的Android中, 设置 - &gt;中还有其他设置。 Wi-Fi - &gt;名为Wi-Fi optimization高级 ,当显示屏关闭时(如果已开启)会禁用所有低优先级通信(如收听UDP广播)。

禁用该选项应该允许您的设备监听UDP广播,即使显示屏已关闭。

Wi-Fi optimization


您也可以使用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"/>

有关详情,请阅读this

答案 1 :(得分:1)

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

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

谢谢大家的帮助和建议 下进行。

答案 2 :(得分:0)

可能是this的原因。

  

Android从Android 6.0(API级别23)开始,引入了两个   节电功能可通过管理来延长用户的电池寿命   设备未连接电源时应用程序的行为方式。瞌睡   通过延迟后台CPU和网络来减少电池消耗   设备长时间不使用时的应用活动。   App Standby推迟了与   用户最近没有互动