public class SwitchRelays extends Activity {
LinearLayout layout1;
LinearLayout.LayoutParams params;
String keyswitch = "http://192.168.2.200/key.php";
final Context context = this;
int respcode;
String codedisplay = "none";
static int responseCode = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.switches);
String urlString = "http://192.168.2.200/android/get_sensors.php";
new ProcessJSON().execute(urlString);
}
public int coderesult(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
final String basicAuth = "Basic " + Base64.encodeToString("user:passw".getBytes(), Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", basicAuth);
responseCode = urlConnection.getResponseCode();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseCode;
}
private class ProcessJSON extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream = null;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
customButton(stream);
}
}
}
private void customButton(String stream) {
// TODO Auto-generated method stub
if (stream != null) {
try {
JSONObject reader = new JSONObject(stream);
JSONArray sensorsArray = reader.getJSONArray("sensors");
params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
layout1 = (LinearLayout) findViewById(R.id.linearswitches);
for (int j = 0; j <= sensorsArray.length()-1; j++) {
JSONObject c = sensorsArray.getJSONObject(j);
String title = c.getString("key_title");
final String pios = c.getString("key_pio");
final String label = c.getString("key_label");
int status = Integer.parseInt(pios);
// Create Button
final Switch btn = new Switch(this);
//btn.setLayoutParams(lp);
layout1.addView(btn,params);
btn.setId(j + 1);
btn.setText(title);
btn.setChecked(true);
if (status == 0)
{btn.setChecked(false) ;}
final int index = j;
// Set click listener for button
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
String urlstring = "http://192.168.2.200/key.php?key_label=termo3&key_pio=1";
respcode = coderesult(urlstring);
Toast.makeText(getApplicationContext(), "Success:"+respcode,
Toast.LENGTH_SHORT).show();
} else {
String urlstring = "http://192.168.2.200/key.php?key_label=termo3&key_pio=0";
respcode = coderesult(urlstring);
Toast.makeText(getApplicationContext(), "Success:"+respcode,
Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
如果我切换按钮,我会得到:“不幸的是,项目已停止”
在这一行:
responseCode = urlConnection.getResponseCode();
如果从
respcode = coderesult(urlstring);
在服务器端,我得到:
“” GET /key.php?key_label=termo3&key_pio=1 HTTP / 1.1“ 200 5”-“” Dalvik / 2.1.0(Linux; U; Android 6.0; Android SDK for x86 Build / MASTER)“
错误日志:
*FATAL EXCEPTION: main Process: ru.smartsurgut.smart9, PID: 22820
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:249)
at libcore.io.IoBridge.recvfrom(IoBridge.java:549)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:481)
at java.net.PlainSocketImpl.-wrap0(PlainSocketImpl.java)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
at com.android.okhttp.okio.Okio$2.read(Okio.java:135)
at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:904)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:788)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:439)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:497)
at ru.smartsurgut.smart9.HTTPGet.GetHTTPResponse(HTTPGet.java:24)
at ru.smartsurgut.smart9.SwitchRelays$1.onCheckedChanged(SwitchRelays.java:126)
at android.widget.CompoundButton.setChecked(CompoundButton.java:156)
at android.widget.Switch.setChecked(Switch.java:1070)
at android.widget.Switch.toggle(Switch.java:1065)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)*
最佳答案
使用异步任务来调用codeResult()函数
AsyncTask.execute(new Runnable() {
@Override
public void run() {
codeResult()
}
});
您不能在邮件Ui线程上调用网络请求