服务停止在手机锁上

时间:2013-11-23 12:38:10

标签: android sockets android-intent service android-service

我有一个在Android应用程序中运行的服务,它在局域网中接收消息,我的服务在电话打开时一直正常工作但当我手动锁定屏幕或自动锁定时我的服务不起作用并且没有收到任何消息,有时它会收到2到3条消息,但之后会再次停止。 我的服务是:

public class Server extends Service {
    static String UDP_BROADCAST = "soft.b.peopleassist";
    public static String ip;
    //Boolean shouldListenForUDPBroadcast = false;
    DatagramSocket socket;

    //Intent intent;
    @SuppressLint("DefaultLocale")

    public String getIpAddr() {
           WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
           WifiInfo wifiInfo = wifiManager.getConnectionInfo();
           int ip = wifiInfo.getIpAddress();

           String ipString = String.format(
           "%d.%d.%d.%d",
           (ip & 0xff),
           (ip >> 8 & 0xff),
           (ip >> 16 & 0xff),
           (ip >> 24 & 0xff));

           return ipString;
        }





void setIP()


    {
      ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mWifi.isConnected()) {

        ip="192.168.1.255";
        Log.i("server", "AP connected so 192");
        }
        if (!mWifi.isConnected()) {

        ip="192.168.49.255";
        Log.i("server", "AP not connected so"+ip);
        }
        }





    private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
        byte[] recvBuf = new byte[15000];
        if (socket == null || socket.isClosed()) {
            socket = new DatagramSocket(port);
        //  socket.setBroadcast(true);
        }
        //socket.setSoTimeout(1000);
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        Log.e("UDP", "Waiting for UDP broadcast");
        socket.receive(packet);

        String senderIP = packet.getAddress().getHostAddress().trim();
        String message = new String(packet.getData());

        Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);

 String str=getIpAddr().trim();
//if(!str.equals(senderIP))
//{
    broadcastIntent(senderIP, message);
    String[] arr = message.split(" ", 5);
    char messagestatus = arr[1].charAt(0);
    Log.i("UDP", String.valueOf(messagestatus));
    if(messagestatus=='s')
    {
     Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
    }
    //      str=null;

//}
str=null;

        socket.close();
    }

    private void broadcastIntent(String senderIP, String message) {
    Intent  intent = new Intent(Server.UDP_BROADCAST);
        intent.putExtra("sender", senderIP);
        intent.putExtra("messages", message);
        sendBroadcast(intent);
    }

    Thread UDPBroadcastThread;

    void startListenForUDPBroadcast() {
        UDPBroadcastThread = new Thread(new Runnable() {
            public void run() {
                try {
                    InetAddress broadcastIP = InetAddress.getByName(ip); //172.16.238.42 //192.168.1.255
                    Integer port = 11111;
                    while (shouldRestartSocketListen) {
                        listenAndWaitAndThrowIntent(broadcastIP, port);
                    }
                    //if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
                } catch (Exception e) {
                    Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
                }
            }
        });
        UDPBroadcastThread.start();
    }

    private Boolean shouldRestartSocketListen=true;

    void stopListen() {
        shouldRestartSocketListen = false;
        if(socket!=null)
        socket.close();
    }

    @Override
    public void onCreate() {

    };

    @Override
    public void onDestroy() {
        stopListen();
        Log.i("UDP", "Service stoped");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        shouldRestartSocketListen = true;

        startListenForUDPBroadcast();
        Log.i("UDP", "Service started");
        return START_STICKY;
    }

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

}

1 个答案:

答案 0 :(得分:1)

您需要掌握WifiManager.WifiLock以防止wifi连接丢失。

***来自官方Android文档的COPY:

WifiLock允许应用程序保持Wi-Fi无线电清醒。通常,当用户暂时不使用设备时,Wi-Fi无线电可能会关闭。获取WifiLock将保持收音机开启,直到锁定被释放。多个应用程序可能会保留WifiLocks,只有在任何应用程序中都没有WifiLock时才会关闭收音机。

在使用WifiLock之前,请仔细考虑您的应用是否需要Wi-Fi接入,或者是否可以通过移动网络运行(如果有)。需要下载大文件的程序应该保存WifiLock以确保下载完成,但是网络使用偶尔或低带宽的程序不应该保留WifiLock以避免对电池寿命产生负面影响。

请注意,WifiLocks无法覆盖用户级“Wi-Fi Enabled”设置,也无法覆盖飞行模式。当Wi-Fi已经开启但设备闲置时,它们只是让收音机关闭。

任何使用WifiLock的应用程序都必须在应用程序清单的元素中请求android.permission.WAKE_LOCK权限。