【发布时间】:2016-04-24 22:21:06
【问题描述】:
我试图在 AsyncTask Activity 中每 X 秒运行一段代码,但在进入任何打印语句之前它就崩溃了。我不确定它为什么会崩溃,但我也发布了我遇到的错误。谁有想法?太感谢了!
public class AppListener extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... uri) {
final Handler h = new Handler();
final int delay = 5000; //milliseconds
h.postDelayed(new Runnable() {
public void run() {
try {
String msg_received = null;
System.out.println("LISTENING FOR LAST INSTALLED APP");
System.out.println("TRY");
Socket socket = new Socket("85.190.178.23", 5050);
// Get data sent through socket
DataInputStream DIS = new DataInputStream(socket.getInputStream());
System.out.println("DataInputStream Started");
// read data that got sent
msg_received = DIS.readUTF();
System.out.println("Message from server" + msg_received);
// Might not want to close socket, or only the first string will be sent and none after
socket.close();
}
catch (Exception e) {
System.out.println("Did not receive string");
}
h.postDelayed(this, delay);
}
}, delay);
String msg_received = null;
return msg_received;
}
}
我的错误
原因:java.lang.RuntimeException: Can't create handler inside the thread that has not called Looper.prepare()
以下是我如何让循环每 X 秒执行一次,而不会干扰我的 GUI,如果它对其他人有帮助的话:我没有单独的类,而是在我的主要活动中发布了我的代码应用启动
public class MainActivity extends FragmentActivity{
private Thread repeatTaskThread;
// called when the activity is first created
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Go into loop that is repeated every X seconds
RepeatTask();
}
private void RepeatTask()
{
repeatTaskThread = new Thread()
{
public void run()
{
while (true)
{
//Post your code here that you want repeated every X seconds
// My "try" and "catch" statements from above got inserted here
try
{
// Sleep for 5 seconds
Thread.sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
};
repeatTaskThread.start();
}
}
【问题讨论】:
-
我使用此链接解决了我的问题:stackoverflow.com/questions/28028954/…
标签: java android asynchronous handler runtimeexception