救命!应用程序等待,直到第二次运行强制关闭

时间:2011-08-28 09:56:49

标签: android android-asynctask multicast

我对android很新,我把一个简单的应用程序放在一起测试AsyncTask中的多播数据包。

我第一次运行应用程序时,一切都按预期进行,但是如果我关闭它并尝试再次运行它,应用程序就会挂起,直到强制关闭对话框启动。

在此之后,我可以再次正常运行程序一次,依此类推。我认为有些东西我没有正确关闭。

我检查了logCat,但我得到的唯一消息是:

WARN/ActivityManager(1193): Activity idle timeout for HistoryRecord{45b352c0 android.projects.bserver/.BroadcastServer}
WARN/ActivityManager(1193): Activity pause timeout for HistoryRecord{45b352c0 android.projects.bserver/.BroadcastServer}

如果有人能告诉我我做错了什么导致第二轮冻结,我将不胜感激。

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import android.app.Activity;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class BroadcastServer extends Activity {
public static final int PORT = 1200;
TextView textStatus;
String data = "this is a test";
public static boolean running = true;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textStatus = (TextView)findViewById(R.id.writeBlock);

    textStatus.append("\nStarting");

    MyAsync ma = new MyAsync();
    ma.execute(data);
    textStatus.append("\nTaskRunning");
    /////////////////////////////////////////////
    try
    {
        InetAddress address = getBroadcastAddress();/////////
        InetAddress multiGroup = InetAddress.getByName("224.0.5.255");

        ///////////////////////////////time to receive

        MulticastSocket socket2 = new MulticastSocket(PORT);//////
        socket2.joinGroup(multiGroup);

        byte[] buf = new byte[1024]; 
        DatagramPacket packet2 = new DatagramPacket(buf, buf.length); 

        textStatus.append("\nWaiting to Receive");

        socket2.receive(packet2);

        textStatus.append("\nReceived");

        String received = new String(packet2.getData());

        textStatus.append("\n" + received);
        running = false;

        textStatus.append("\nFinished");

    }
    catch(IOException e)
    {
        textStatus.append("\nTaskFailed Outer: " + e.getMessage());
    }
    textStatus.append("\nProgramDone");
}

///////////////////////////////////////////////////

InetAddress getBroadcastAddress() throws IOException { 
    //Original Line: WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
    WifiManager wifi = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);

    DhcpInfo dhcp = wifi.getDhcpInfo();
    // handle null somehow      
    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;     
    byte[] quads = new byte[4];     
    for (int k = 0; k < 4; k++)       
        quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);     
    return InetAddress.getByAddress(quads); 
}

class MyAsync extends AsyncTask<String, Integer, String>
{
    @Override
    protected void onPreExecute()
    {
        textStatus.append("\nAsyncStarted");
    }

    @Override
    protected String doInBackground(String... params) {
        ///////////////////////////////time to send
        String data = params[0];

        try
        {
        InetAddress address = getBroadcastAddress();///////////////
        InetAddress multiGroup = InetAddress.getByName("224.0.5.255");

        MulticastSocket socket = new MulticastSocket(PORT);
        socket.setBroadcast(true); 
        socket.joinGroup(multiGroup);//////////
        DatagramPacket packet = new DatagramPacket(data.getBytes(), 
                data.length(), address, PORT); 

        //int count = 0;
        while(BroadcastServer.running)
        {
            socket.send(packet);  
            //publishProgress(count);
            //count++;
        }
        }
        catch(IOException e)
        {
            textStatus.append("\nTaskFailed Inner: " + e.getMessage());
        }

        return "AsyncDone";
    }

    @Override
    protected void onProgressUpdate(Integer... count)
    {
        textStatus.append("\n" + count.toString());
    }

    @Override
    protected void onPostExecute(String results)
    {
        textStatus.append("\n"+results);
    }
}
}

1 个答案:

答案 0 :(得分:2)

首先,你说它强制关闭,但我怀疑你所看到的不是强制关闭,而是应用无响应(ANR),这是完全不同的。 ANR不是崩溃,这意味着您的应用程序在UI线程上耗费大量时间。

您正在UI线程上进行网络调用。您已将一些内容移至AsyncTask,但您需要从UI线程中获取与网络相关的所有内容。如果您注释掉网络代码,您的应用将会再次响应。

作为一般性提示,您可能还希望了解IntentService,这是另一种传递要在后台执行的操作的方法。