마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

String으로 리턴을 받아 IP 출력하려합니다

+1 추천
--------------------첫번째 MainActivity ------------------------------------

public class MainActivity extends ActionBarActivity {
 
 int mMainValue = 0;
 TextView mMainText;
 TextView mBackText;

 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
   mMainText = (TextView) findViewById(R.id.minValue);
         Button increaseBtn = (Button) findViewById(R.id.increase);
         increaseBtn.setOnClickListener(onClick);
        
  BackThread thread = new BackThread(mHandler);
  thread.setDaemon(true);
  thread.start();
  
 }
 OnClickListener onClick = new View.OnClickListener(){
  public void onClick(View v) {
   mMainText.setText("현재의 아이피 주소는 : " + mMainValue);
  }
 };

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
 
 // 버튼 클릭 -> 클레스 실행 - > 리턴 값을 새로 지정해서 집어 넣고 -> 핸들러 넣어서 출력 ;ㅇ
 // INTENT로 재구성을 해서 ACTIVITY 해야하고,
 
 Handler mHandler = new Handler() {
  
 };
 public Handler handler;
 
 class BackThread extends Thread {
  
  Handler mHandler;
  
  BackThread(Handler handler) {
   mHandler =  handler;
  }
  
  public void run() {
   while(true) {
    
    Message msg = Message.obtain(mHandler, 0);
    mHandler.sendMessage(msg);
    try {
     Thread.sleep(1000);
    // sleep 구문을 이용해서 시간 초단위 시간 단위별로 자동 업데이트 기능 가능 함.
   
    } catch(InterruptedException e) {}
   }
  }
 }
 ---------------------------------두번째 intent 되는 코드--------------------------------

import com.example.protext.R.string;

import android.support.v7.app.ActionBarActivity;
import android.util.Log;

public class SecondAct extends ActionBarActivity {
 private static final String DEBUG_TAG = null;
 
 String text1 = null;
 // IP 주소 얻는 Class 입니다. 클레스를 실행 시켯다.
 
 public String getLocalIpAddress()
  {
   try {
    for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
              NetworkInterface intf = en.nextElement();
              for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                  InetAddress inetAddress = enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                      return inetAddress.getHostAddress().toString();
                  }
              }
          }
      } catch (SocketException e) {
          Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
      }
      return null;
  }
}
 // 아이피를 얻는 클래스 임.

--------------------------------------------------------------------------------------------------

 이렇게 되어있어요. 근데 이제 핸들러로 ip를 뽑아 내야 할텐데...

return이 int로 만 나오고... 핸들러야 넣어야 하는데... 수정좀 부탁드립니다.

ip를 출력하는게 목적이랍니다.! 도와주세요!
익명사용자 님이 2014년 7월 22일 질문

1개의 답변

+1 추천
public void getIpAddress() {
        new AsyncTask<Context, Void, String>() {
            @Override
            protected void onPreExecute() {
                // show your progress dialog
            }
 
            @Override
            protected String doInBackground(Context... contexts) {
                Context context = contexts[0];
                String ipAddr;
 
                try {
                    while(true) {
                        ipAddr = wifiIpAddress(context);
                        if (ipAddr != null) {
                            break;
                        }
 
 
                            Thread.sleep(1000);
 
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return null;
                }
 
                return ipAddr;
            }
 
            protected String wifiIpAddress(Context context) {
                WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
                int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
 
                // Convert little-endian to big-endianif needed
                if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
                    ipAddress = Integer.reverseBytes(ipAddress);
                }
 
                byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
 
                String ipAddressString;
                try {
                    ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
                } catch (UnknownHostException ex) {
                    Log.e("WIFIIP", "Unable to get host address.");
                    ipAddressString = null;
                }
 
                return ipAddressString;
            }
 
            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    // hide your progress dialog
                    // yourTextView.setText(result);
                } else {
                    // hide your progress dialog and show error dialog
                }
            }
        }.execute(this);
    }
aucd29 (218,390 포인트) 님이 2014년 7월 23일 답변
출력이 이상해요...ㅠ
계속해서 수정하면서 연구해가고있습니다!
좋은 답변감사합니다 한단계 진전이 보였어요 ㅎ!
책좀 사서 읽으세요..
네ㅠ 무턱대고 뛰어드니까 너무 힘드네요... 아는것도 없고
어떤 메소드가 잇는지도 잘모르고ㅠ 책도 추천하나만 부탁드릴게요ㅠ
...