如何将MainActivity中的方法分离到其他类,并调用

时间:2016-09-15 16:43:35

标签: android class

我称之为这样的方法。

finishedFlag = new HttpUtil().execute(url, userid, workflag).get();

我希望将此方法分离到另一个类。 (例如,创建一个类:httpUtil。)

我怎么打电话,分开?

public class HttpUtil extends AsyncTask<String, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
           // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("ing...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        public Boolean doInBackground(String... params1) {
            try {

                String url = params1[0];
                URL obj = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

                if (params1[0].equals(aaa)) {                     
                    params.add(new BasicNameValuePair("time", params1[2]));
                    params.add(new BasicNameValuePair("userid", params1[1]));
                } else if (params1[2].equals("goWork")) {
                    Thread.sleep(300);

                    params.add(new BasicNameValuePair("userid", params1[1]));
                }
                if (params1[2].equals("3")) {
                    params.add(new BasicNameValuePair("userid", params1[1]));
                }

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getQuery(params));
                writer.flush();
                writer.close();
                os.close();

                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                br.close();

                String res = response.toString();

                HashMap<String, String> myHashMap = new HashMap<String, String>();
                myHashMap = convertToHashMap(res);

                String errmsg = "";
                String errmsg2 = "";
                String name = "";
                String OutToWork = "";

                if (params1[2].equals("goWork")) {
                    errmsg = myHashMap.get(" errmsg");
                    errmsg2 = myHashMap.get(" errmsg2");
                } else if (params1[0].equals(url4end_work)) {
                    String outWork = loadJSONFromAsset(params1[2]);
                    try {
                        JSONObject obj1 = new JSONObject(outWork);

                        WIFI_CHECK_TIMER = obj1.getString("wifi-check-timer");
                        WIFI_AUTO_ON_TIME = obj1.getString("wifi-auto-on-time");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    errmsg2 = myHashMap.get(" errmsg2");
                    name = myHashMap.get(" user-name");

                } else {

                }

                OutputStreamWriter writer1 = null;
                File dir = null;
                File jsonFile = null;
                if (params1[0].equals(url4end_work)) {                      jsonFile = new File(Environment.getExternalStorageDirectory(), "policy/OuttoWork.json");
                } else if (params1[2].equals("3")) {
                    jsonFile = new File(Environment.getExternalStorageDirectory(), "policy/policy.json");
                    if (jsonFile.exists()) {
                        boolean delete = jsonFile.delete();
                        Log.d("Code1 ==> ", " Json !");
                    }
                } else if (params1[2].equals("goWork")) {
                    jsonFile = new File(Environment.getExternalStorageDirectory(), "policy/GotoWork.json");
                }
                dir = new File(Environment.getExternalStorageDirectory(), "policy");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                try {
                    writer1 = new OutputStreamWriter(new FileOutputStream(jsonFile, true), "UTF-8");
                    if (params1[2].equals("3")) {
                        writer1.write(res.toString());

                    } else if (params1[0].equals(url4end_work)) {
                        writer1.write(res.toString());
                    } else if (params1[2].equals("goWork")) {
                        writer1.write(res.toString());
                    }
                    writer1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }


                if (params1[2].equals("bbb")) {
                    showpopup("", errmsg, errmsg2);
                    first_check_work--;

                } else if (params1[2].equals("ccc")) {
                    showpopup("", errmsg, errmsg2);
                    first_check_work++;
                } else { 
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean a = true;
            return a;

        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
        }
    }

1 个答案:

答案 0 :(得分:1)

嘿,你应该创建一个扩展异步适配器的类来处理后台操作(你做到了)并创建接口回调来获取活动/片段中的数据。

这是AsyncTask类:

public class HttpUtilClass extends AsyncTask<String, Void, Boolean> {

    TestListener testListener;
    Activity activity;

    public HttpUtilClass(Activity activity){
        this.activity = activity;
        testListener =(TestListener) activity;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... strings) {

        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (testListener!=null){
            testListener.getBool(aBoolean);
        }
    }
}

这是界面:

public interface TestListener {

    void getBool(boolean bool);
}

这是您的主要活动

public class MainActivity extends AppCompatActivity implements TestListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpUtilClass hh = new HttpUtilClass(this);
        hh.execute("test");
    }

    @Override
    public void getBool(final boolean bool) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("LOG", "getBool: " + bool);
            }
        });

    }
}
祝你好运;)