2017-10-12 12 views
-3

デバイスのネットワーク接続時にAsyncTaskを実行します。 このAsyncTaskはパブリックIPを取得します。アンドロイドの別のクラスからasynctask結果の値を取得するには?

MainActivityでasyncTask(インナー)

私は別のクラスの値(結果値がパブリックIPです)asyncTask結果が欲しいです。

別のクラスからパブリックIPを取得するにはどうすればよいですか?

public class MainActivity extends Activity { 
    static getAsyncPubIp async = new getAsyncPubIp(); 

    public static final class getAsyncPubIp extends AsyncTask<Void, Void, String> { 
     String result; 
     TextView pubView; 

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

     @Override 
     protected String doInBackground(Void... params) { 
      try { 
       URL pub = new URL("get public ip domain"); 
       BufferedReader in = new BufferedReader(new InputStreamReader( 
         pub.openStream())); 

       String strPub = in.readLine(); 
       result = strPub; 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

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

      pubView = (TextView) activity.findViewById(R.id.ip); 
      pubView.setText(result); 

      async = null; 
      pubView = null; 
     } 
    }  

通常私のソース、別のクラス

MainActivity.getAsyncPubIp asyncPub = new MainActivity.getAsyncPubIp(); asyncPub.execute();

にこのasynctaskを呼び出すが、私はどのようにこれを取得するために別のクラス

からのみasyncTask結果値をしたいですか?

+3

可能な複製を( AsyncTaskは別のクラスなのでメインアクティビティに移動しますか?](https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is -a) –

+0

他のクラスのオブジェクトにアクセスするには、Asシングルトンを使ったyncタスク。 – Vasant

+0

インターフェイスを使用して、別のクラスのインターフェイスを定義し、MainActivity – Yatish

答えて

1

SecondClass.javaという名前の二アクティビティのJavaクラスの静的変数を作成します。

public static String public_ip; 

次に、あなたのMainActivityに:OnPostExecuteの結果を取得する[方法の

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

      //Add this 
      SecondClass.public_ip = result; 

      pubView = (TextView) activity.findViewById(R.id.ip); 
      pubView.setText(result); 

      async = null; 
      pubView = null; 
     } 
関連する問題