在我的活动中,我使用了一个处理程序
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//do GUI stuff, edit views, etc..
}
};
我也有一个Runnable
,它发布到 php 并等待 json 响应
Runnable runnable3 = new Runnable() {
public void run() {
JSONParserArray jsonParserRun = new JSONParserArray();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("p1", "myParam1"));
try {
String link = "http://mylink.com/someFileOnServer.php";
JSONArray jArray = jsonParserRun.makeHttpRequest(link , "POST",
params);
if (jArray != null && jArray.length() != 0) {
} else {
//either null (because of throwing exception) or empty
}
} catch (Exception e) {
}
}
handler.sendEmptyMessage(0);
handler.postDelayed(runnable, 30000);
}
我每 30 秒重复一次任务,最后在我的 onCreate() 中创建一个线程并将其传递给Runnable
@Override
public void onCreate(Bundle savedInstanceState) {
//other stuff
Thread t = new Thread(runnable3);
t.start();
}
这段代码android.os.NetworkOnMainThreadException
甚至认为我正在启动一个新线程并将其传递Runnable
给它。JSONParserArray 类在其他情况下工作正常(所以不用担心)
但是,当我在内部运行此方法时Runnable
,它工作正常。
private boolean hasActiveInternetConnection() {
try {
new Socket().connect(new InetSocketAddress("google.com", 80), 3000);
return true;
} catch (Exception e) {
Log.i("tag", e.toString());
return false;
}
}