但是在4.0 下 会出现类似fe80::b607:f9ff:fee5:487e的IP地址, 这个是IPV6的地址,我们需要获得是的IPV4的地址,所以要在上诉代码中加一个判断
[java]
InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())
package com.example.androidtsetip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView text;
private int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.txet);
handler.post(runnable);
}
Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(1);
//开始
handler.postDelayed(runnable, 1000);
}
};
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case 1:
String IP = getLocalIpAddress();
i++;
text.setText( "第"+i+"次IP地址"+IP);
break;
default:
break;
}
}
};
//获取地址
public static 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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress().toString();
}
}
}
}catch (SocketException e) {
// TODO: handle exception
Log.e("liwenquan","WifiPreference IpAddress---error-" + e.toString());
}
return null;
}
private void Broadcast(){
final IntentFilter filter = new IntentFilter();
// 屏幕灭屏广播
filter.addAction(Intent.ACTION_SCREEN_OFF);
// 屏幕亮屏广播
filter.addAction(Intent.ACTION_SCREEN_ON);
// 屏幕解锁广播
filter.addAction(Intent.ACTION_USER_PRESENT);
BroadcastReceiver broa = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)) {
Log.d("liwenquan", "screen on");
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
Log.d("liwenquan", "screen off");
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
Log.d("liwenquan", "screen unlock");
}
}
};
}
}