2016-12-14 62 views
0

我已經在名爲mylibrary的android studio庫模塊中定義了一個異步任務。我已將類getDeviceIP定義爲mylibrary中的異步任務。我已將該庫模塊導入另一個項目testMyLibrary。當我嘗試在testMyLibrary中調用主Actvitiy的異步方法時,出現無法解析符號execute()的錯誤。當我把類getDeviceIP放在與testMyLibrary相同的項目中時,它工作正常。但是,當方法存在於庫中時,getDeviceIP被識別,但在getDeviceip.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); 
    } 
} 

在線,**執行()**不被認可。

感謝您的幫助。

+0

getDeviceIP類應該擴展的AsyncTask –

回答

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); 
     } 
    } 
+0

咄!真是愚蠢的我。甚至沒有將整個函數複製到庫中,因此它在另一個項目中工作,但不在庫中。非常感謝您的快速響應。 –