Android 学习

来源:互联网 发布:c语言if语句的嵌套 编辑:程序博客网 时间:2024/06/11 12:06

Android wifi学习

获取WifiManager对象

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

再得到WifiInfo,就可以知道连接状态和ip地址

WifiInfo info = wifiManager.getConnectionInfo();
 if (info!=null && info.getNetworkId()>-1) {
    int i = info.getIpAddress();

    String ip = String.format("%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff,i >> 16 & 0xff,i >> 24 & 0xff);

}

Android Handler的使用

    private final Handler handler = new Handler() {
   
    public void handleMessage(Message msg) { 
    switch (msg.what) {
    case RtspServer.MESSAGE_ERROR:
    Exception e1 = (Exception)msg.obj;
    lastCaughtException = e1;
    log(e1.getMessage()!=null?e1.getMessage():"An error occurred !");
    break;
    case RtspServer.MESSAGE_LOG:
    //log((String)msg.obj);
    break;
    case HttpServer.MESSAGE_ERROR:
    Exception e2 = (Exception)msg.obj;
    lastCaughtException = e2;
    break;    
    case Session.MESSAGE_START:
    streaming = true;
    streamingState(1);
    break;
    case Session.MESSAGE_STOP:
    streaming = false;
    displayIpAddress();
    break;
    }
    }
   
    };

BroadcastReceiver

  在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。而BroadcastReceiver是对发送出来的 Broadcast进行过滤接受并响应的一类组件。

下面将详细的阐述如何发送Broadcast和使用BroadcastReceiver过滤接收的过程:

  首先在需要发送信息的地方,把要发送的信息和用于过滤的信息(如Action、Category)装入一个Intent对象,然后通过调用 sendOrderBroadcast()或sendStickyBroadcast()方法,把 Intent对象以广播方式发送出去。

  当Intent发送以后,所有已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiver的onReceive()方法。所以当我们定义一个BroadcastReceiver的时候,都需要实现onReceive()方法

    private final BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // This intent is also received when app resumes even if wifi state hasn't changed :/
        if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        if (!streaming) displayIpAddress();
        }
        } 
    };