Android-wifi热点开关

工模测试过程中需要实现频繁的开启与关闭wifi热点,代码如下。

import java.lang.reflect.Method;  
import android.app.Activity;  
import android.content.Context;  
import android.net.wifi.WifiConfiguration;  
import android.net.wifi.WifiManager;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  

public class HotspotActivity extends Activity {  
    private WifiManager wifiManager;  
    private Button open;  
    private boolean flag=false;  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        //获取wifi管理服务  
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
        open=(Button)findViewById(R.id.open_hotspot);  
        //通过按钮事件设置热点  
        open.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                //如果是打开状态就关闭,如果是关闭就打开  
                flag=!flag;  
                setWifiApEnabled(flag);  
            }  
        });  
    }  

    // wifi热点开关  
    public boolean setWifiApEnabled(boolean enabled) {  
        if (enabled) { // disable WiFi in any case  
            //wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi  
            wifiManager.setWifiEnabled(false);  
        }  
        try {  
            //热点的配置类  
            WifiConfiguration apConfig = new WifiConfiguration();  
            //配置热点的名称(可以在名字后面加点随机数什么的)  
            apConfig.SSID = "YRCCONNECTION";  
            //配置热点的密码  
            apConfig.preSharedKey="12122112";  
                //通过反射调用设置热点  
            Method method = wifiManager.getClass().getMethod(  
                    "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);  
            //返回热点打开状态  
            return (Boolean) method.invoke(wifiManager, apConfig, enabled);  
        } catch (Exception e) {  
            return false;  
        }  
    }  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值