I am very new to android, and I have thrown together a simple app to test out multi-casting packets in an AsyncTask
.
The first time I run the app everything goes as I expect, but if I close it and attempt to run it a second time the app just hangs until the force close dialog launches.
After this I can once again run the program normally one time, and so on. I assume that there is something that I am not closing properly.
I have checked logCat, but the only messages I get are:
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}
If anyone can tell me what I'm doing wrong that's causing the freeze on the second run, I would be grateful.
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
开发者_如何学Go 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);
}
}
}
Firstly, you said it force closes, but I suspect what you are seeing is not a Force Close, but an Application Not Responding (ANR) which is quite different. An ANR isn't a crash, it means your app is tied up doing something time-consuming on the UI thread.
You're making a network call on the UI thread. You've moved some to an AsyncTask, but you need to get everything network-related off the UI thread. If you comment out the network code, your app will be responsive again.
As a general tip, you may also wish to learn about IntentService, which is another approach to passing off actions to be performed in the background.
精彩评论