帮助!应用程序等待第二次运行时强制关闭
我对 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);
}
}
}
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
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您说它强制关闭,但我怀疑您看到的不是强制关闭,而是应用程序未响应(ANR),这是完全不同的。 ANR 并不是崩溃,它意味着您的应用程序正在 UI 线程上执行一些耗时的操作。
您正在 UI 线程上进行网络调用。您已将一些内容移至 AsyncTask,但您需要从 UI 线程中获取与网络相关的所有内容。如果您注释掉网络代码,您的应用程序将再次响应。
作为一般提示,您可能还希望了解 IntentService,这是传递要在后台执行的操作的另一种方法。
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.