当我尝试运行应用程序时,它的行为方式是黑屏->回到主要活动。
这是我的代码:
public class ResultsActivity extends AppCompatActivity {
final TextView textView = findViewById(R.id.textView);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
new NetworkTask().execute();
}
public void backToMain(View v) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private class NetworkTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
final String image = getExternalCacheDir() + "/image.jpeg";
File file = new File(image);
try {
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("images", "image.jpeg",
RequestBody.create(file, MEDIA_TYPE_JPEG))
.addFormDataPart("organs", "leaf")
.build();
Request request = new Request.Builder()
.url("insert url here")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String result = response.body().string();
return result;
} catch(IOException e) {
e.printStackTrace();
return "error";
}
}
@Override
protected void onPostExecute(String result) {
if(result.equals("error")) {
textView.setText("error");
} else {
textView.setText(result);
}
}
}
我相当确定,张贴请求工作得很好,因为我已经使用进行了测试
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
所以,也许问题在于我在AsyncTask中的处理方式。
正如Carl所说,我把这行代码放在doInBackground方法上。我的问题已经解决了。
@Override
protected String doInBackground(String... params) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//...
}
在某些情况下(例如发送图像队列(,使用AsyncTask是必要的。