实现了AsyncTask但仍然获得了NetworkOnMainThreadException

时间:2016-05-19 13:13:50

标签: android android-asynctask

我有这两个班级:

public class EmailManager {

    private RetrieveEmailResultTask retrieveEmailResultTask;

    public EmailManager(SMSAndEmailResponseListener smsAndEmailResponseListener) {
        retrieveEmailResultTask = new RetrieveEmailResultTask();
        retrieveEmailResultTask.SMSAndEmailResponseListener = smsAndEmailResponseListener;
    }

    public void send(String subject, String body, String nonHTMLBody) throws IOException{
        String uri = "subject=" + Utils.encode(subject);
        uri += "&body=" + Utils.encode(body);
        uri += "&non_html_body=" + Utils.encode(nonHTMLBody);
        retrieveEmailResultTask.execute(uri);
    }

    public Exception getException() {
        return retrieveEmailResultTask.e;
    }

    private class RetrieveEmailResultTask extends AsyncTask<String, Void, Boolean> {

        protected Exception e;
        protected SMSAndEmailResponseListener SMSAndEmailResponseListener = null;

        @Override
        protected Boolean doInBackground(String... strings) {
            try {
                URL url = new URL("http://tarzz.com.pk/emailapi/sendemail.php");

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);

                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(strings[0]);
                writer.flush();

                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String res = rd.readLine();
                Log.d("YOLO", res);

                writer.close();
                rd.close();

                if(res != "Message has been sent") {
                    return false;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                this.e = e;
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                this.e = e;
                return false;
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            this.SMSAndEmailResponseListener.onResult(aBoolean);
        }
    }

}

public class SMSManager {
    private RetrieveSMSResultTask retrieveSMSResultTask;

    public SMSManager(SMSAndEmailResponseListener SMSAndEmailResponseListener) {
        retrieveSMSResultTask = new RetrieveSMSResultTask();
        retrieveSMSResultTask.SMSAndEmailResponseListener = SMSAndEmailResponseListener;
    }

    public void send(String to, String msg) throws IOException {
        String uri = "id=" + Utils.encode("rchibltarzz");
        uri += "&pass=" + Utils.encode("karachi1");
        uri += "&msg=" + Utils.encode(msg);
        uri += "&lang=" + Utils.encode("English");
        uri += "&to=" + Utils.encode(to);
        uri += "&mask=" + Utils.encode("Tarzz");
        uri += "&type=" + Utils.encode("json");

        retrieveSMSResultTask.execute(uri);
    }

    public Exception getException() {
        return retrieveSMSResultTask.e;
    }

    private class RetrieveSMSResultTask extends AsyncTask<String, Void, Boolean> {

        protected Exception e;
        protected SMSAndEmailResponseListener SMSAndEmailResponseListener = null;

        @Override
        protected Boolean doInBackground(String... urls) {
            try {
                URL url = new URL("http://www.outreach.pk/api/sendsms.php/sendsms/url");
                URLConnection con = url.openConnection();
                con.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
                writer.write(urls[0]);
                writer.flush();

                BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String line = "", res = "";
                while ((line = rd.readLine()) != null) {
                    res += line + " ";
                }

                writer.close();
                rd.close();

                JSONObject jsonObj = new JSONObject(res);
                JSONArray jsonArray = jsonObj.optJSONArray("corpsms");
                JSONObject response = jsonArray.getJSONObject(0);
                Log.d("YOLO", (String) response.get("type"));
                if(((String) response.get("type")).equals("Success")) {
                    return true;
                } else {
                    return false;
                }
            } catch(IOException e) {
                e.printStackTrace();
                this.e = e;
                return false;
            } catch (JSONException e) {
                e.printStackTrace();
                this.e = e;
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            this.SMSAndEmailResponseListener.onResult(aBoolean);
        }
    }
}

这是我的倾听者:

public interface SMSAndEmailResponseListener {
    void onResult(Boolean a);
}

这就是我在主要活动中使用这些类的方法:

@Override
public void onResult(Boolean a) {
    if(a == true) {
        Toast.makeText(getApplicationContext(), "Your feedback has been submitted. Thanks for your cooperation.", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getApplicationContext(), "An error occurred in submitting your application. Please try again.", Toast.LENGTH_SHORT).show();
    }
}

btnSubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        try {
            smsManager.send(etMobileNumber.getText().toString(), "Your feedback has been submitted. Thanks for your cooperation.");
            emailManager.send("Feedback from customer", emailBody, "Non Html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

每当我尝试运行我的应用程序时,都会显示以下错误:

05-19 16:11:24.690    2208-2208/com.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.myapplication, PID: 2208
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
            at java.net.InetAddress.getAllByName(InetAddress.java:215)
            at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
            at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
            at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
            at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
            at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
            at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
            at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
            at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
            at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
            at com.myapplication.SMSManager.sendSMS(SMSManager.java:31)
            at com.myapplication.LoyaltyForm$1.onClick(LoyaltyForm.java:84)
            at android.view.View.performClick(View.java:5198)
            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)

我不知道我做错了什么,为什么AsyncTask没有工作。请告诉我。谢谢。 :)

1 个答案:

答案 0 :(得分:0)

我重新启动了Android Studio并且运行良好。

奖励。