主题 : 关于编程时网络检测的代码 复制链接 | 浏览器收藏 | 打印
级别: 新手上路
UID: 56880
精华: 0
发帖: 6
金钱: 30 两
威望: 6 点
贡献值: 0 点
综合积分: 12 分
注册时间: 2011-10-15
最后登录: 2014-12-08
楼主  发表于: 2012-04-02 22:28

 关于编程时网络检测的代码


我想问二个Tiny6410下编程的问题:

问题一、程序启动后设置竖屏:

从资料上看,可以用下述代码实现:
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
但我试了,不起作用。

问题二、在程序中检测网络是否开通,如果不通,则打开以太网的配置界面:

我用下述代码检测是否有网络:
    /**
     * 获得IP地址,任意一个非Loopback地址.
     * @return
     */
    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()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception ex) {
        }
        return null;
    }
这段代码可以正确执行,当返回null时,表明网络没有启动,这时打开网络配置界面:
    public static void setupNetwork(final Activity activity) {
        final String APP_SETTINGS = "com.friendlyarm";
        // 以下是friendlyarm的以太网界面, 不知如何启动.
        final String APP_ETHERNET = "com.friendlyarm.ethernetsettings";
        new AlertDialog.Builder(activity)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("网络连接")
        .setMessage("启动哪种网络连接?")
        .setPositiveButton("无线网",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent i = new Intent(
                        android.provider.Settings.ACTION_WIFI_SETTINGS);
                    activity.startActivityForResult(i,0);
                }
            })
        .setNegativeButton("有线网",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent mIntent = new Intent("/");
                    ComponentName comp = new ComponentName(
                            APP_SETTINGS,
                            APP_ETHERNET);
                    mIntent.setComponent(comp);
                    mIntent.setAction("<span class='hilite'>android</span>.intent.action.VIEW");
                    activity.startActivity(mIntent);
                }
            })
        .show();
    }
这段代码中打开无线网络配置界面的一段代码可以正确执行,但有线网络的界面则无法打开,原因是调
用com.friendlyarm.ethernetsettings的代码不正确,请问,该如何调用它。即:
ComponentName comp = new ComponentName(
                            APP_SETTINGS,
                            APP_ETHERNET);
中的二个参数是什么?还有在AndroidManifest.xml文件中还需要配置什么?

谢谢?