在库中定义类时,Async Task不会执行

时间:2016-12-14 04:05:39

标签: java android asynchronous

我在名为mylibrary的android studio库模块中定义了一个异步任务。我已将类getDeviceIP定义为mylibrary中的异步任务。我已将该库模块导入另一个项目testMyLibrary。当我尝试从testMyLibrary中的Main Actvitiy调用异步方法时,我得到的错误无法解析符号execute()。当我将类getDeviceIP放在与testMyLibrary相同的项目中时,它可以正常工作。但是,当该方法存在于库中时,getDeviceIP会被识别,但在getDeviceip.execute()中,execute()方法无法识别。

mylibrary代码是:

    package com.example.ramesh.mylibrary;

import android.util.Log;
import android.os.AsyncTask;


public class getDeviceIP {
    private String Url;
    private Integer tos;

    public getDeviceIP(String url, Integer typeOfService) {
        Url = url;
        tos = typeOfService;
    }
    protected String doInBackground(Void... params) {
        //now call your ipify method which is doing the networking or calling a method that might be doing the networkign

        //getContents("http://localhost:8080");
        String ip = "";

        if (tos == 1) {

            ip = getipify(Url);
            Log.i("Service = ", "Get IP address");

        } else {
            Log.i("Service = ", "Not Defined");
            ip = ">>>>Not Defined<<<<";
        }

        Log.i("ip after getipify call ",ip);

        return ip;
    }

    private String getipify(String url) {

        String IP="";

        try (java.util.Scanner s = new java.util.Scanner(new java.net.URL(url).openStream(), "UTF-8").useDelimiter("\\A")) {
            IP = s.next();
            System.out.println("My current IP address is " + IP.toString());
            //IP = s.next();
        } catch (java.io.IOException e) {
            System.out.println("======");
            System.out.println(e);
            System.out.println("======");

        }


        Log.i("Test","IP");

        return(IP);
    }

}

主要活动是

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String myUrl = "https://api.ipify.org";
        String result = "";

        try {
            result = new getDeviceIP(myUrl,1).execute().get();


        } catch (Exception e) {

            System.out.println("Execution Excepton" + e);
        }
        Log.i("IP in main  = ", result);
    }
}

在该行中,** execute()**无法识别。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

将getDeviceIP类扩展为: -

public class getDeviceIP extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... strings) {
            return null;
        }

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

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }