android的日积月累-进行WIFI,CMWAP和CMNET的自动判断访问

来源:互联网 发布:赵薇收购万家文化知乎 编辑:程序博客网 时间:2024/05/16 15:29

智能进行WIFI,CMWAP和CMNET的自动判断访问

引用文件:
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

 

变量定义
         Cursor cursor_current,cursor_need;
         Uri PREFERRED_APN_URI, APN_TABLE_URI;
         int newCreateAPN_Id;
         String APN_Id;
         TelephonyManager tm;
         WifiManager wifi;

         String strAPN;

使用到的函数如下:
    //获取当前APN属性
    private boolean getCurrentAPN(){
            PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn");
            cursor_current = this.getContentResolver().query(PREFERRED_APN_URI, null, null, null, null);
            if(cursor_current != null && cursor_current.moveToFirst()){
                    String proxy = cursor_current.getString(cursor_current.getColumnIndex("proxy"));
                    String apn = cursor_current.getString(cursor_current.getColumnIndex("apn"));
                    String port = cursor_current.getString(cursor_current.getColumnIndex("port"));
                    String current = cursor_current.getString(cursor_current.getColumnIndex("current"));
                    if(proxy == null || apn == null || port == null || current == null
                                    || proxy.equals("") || port.equals("")){
                            return false;
                    }

                    if((proxy.equals("10.0.0.172") || proxy.equals("010.000.000.172")) && port.equals("80") &&
                                    apn.equals("cmwap") && current.equals("1")){
                            return true;
                    }
            }
                return false;          
    }
   
    //
检查是否存在cmwap网络
    private boolean checkHasWapAPN(){
            APN_TABLE_URI = Uri.parse("content://telephony/carriers");
            cursor_need = this.getContentResolver().query(APN_TABLE_URI, null, null, null, null);
   
            while(cursor_need != null && cursor_need.moveToNext()){
                    String id = cursor_need.getString(cursor_need.getColumnIndex("_id"));      
                String port = cursor_need.getString(cursor_need.getColumnIndex("port"));  
                String proxy = cursor_need.getString(cursor_need.getColumnIndex("proxy"));
                String current = cursor_need.getString(cursor_need.getColumnIndex("current"));
                String mmsc = cursor_need.getString(cursor_need.getColumnIndex("mmsc"));
                if(proxy == null || port == null || current == null){
                        continue;
                }
               if((proxy.equals("10.0.0.172") || proxy.equals("010.000.000.172"))
                                && port.equals("80") && current.equals("1")
                                && mmsc == null){
                        APN_Id = id;
                        return true;
                }
            }
                return false;         
    }
   
    //
设置为cmwap网络
    public boolean setAPN(int id){
                           
            boolean res = false;
            ContentResolver resolver = this.getContentResolver();
            ContentValues values = new ContentValues();
            values.put("apn_id", id);
            try{
                    resolver.update(PREFERRED_APN_URI, values, null, null);
                    Cursor c = resolver.query(PREFERRED_APN_URI, new String[]{"name", "apn"}, "_id=" + id, null, null);
                    if(c != null){
                            res = true;
                            c.close();
                    }
            }catch(SQLException e){
                    Log.e("lhl", e.getMessage());
            }
                return res;
    }
   
    //
添加cmwap网络
    private int addCmwapAPN(){
            ContentResolver cr = this.getContentResolver();
            ContentValues cv = new ContentValues();
            cv.put("name", "cmwap");
            cv.put("apn", "cmwap");
            cv.put("proxy", "010.000.000.172");
            cv.put("port", "80");
            cv.put("current", 1);

            tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            String imsi =tm.getSubscriberId();
            if(imsi != null){
                    if(imsi.startsWith("46000")){
                            cv.put("numeric", "46000");
                            cv.put("mcc", "460");
                            cv.put("mnc", "00");
                    }
                    else if(imsi.startsWith("46002")){
                            cv.put("numeric", "46002");
                            cv.put("mcc", "460");
                            cv.put("mnc", "02");
                    }
            }
           
            Cursor c = null;
            try{
                    Uri newRow = cr.insert(APN_TABLE_URI, cv);
                    if(newRow != null){
                            c = cr.query(newRow, null, null, null, null);
                            c.moveToFirst();
                            String id = c.getString(c.getColumnIndex("_id"));
                            setAPN(Integer.parseInt(id));
                            return Integer.parseInt(id);
                    }
                   
            }catch(SQLException e){
                    Log.e("lhl", e.getMessage());
            }
            finally{
                    if(c != null){
                            c.close();
                    }
            }       
                return 0;          
    }           

判断逻辑如下:
                private Search search;
                //
网络判断
               
                //
如果wifi是打开的,则直接调用就可以了
                    wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
                    if(wifi.isWifiEnabled()){
                            strAPN = "WIFI";
                            search.asyncRequest(queryCompanyName, queryDttime, queryBeginCity, queryEndCity, queryBeginCity1, queryEndCity1, strAPN, listener);
                            return;
                    }
                   
            boolean isCmwap = getCurrentAPN();
            boolean wCheckWapApn = checkHasWapAPN();
            if(!isCmwap){       
                    if(!wCheckWapApn){
                            newCreateAPN_Id = addCmwapAPN();
                            strAPN = "CMNET";
                    }
                    else{
                            strAPN = "CMNET";
                    }try{
                            Thread.sleep(1000);
                    }catch(InterruptedException e){
                            e.printStackTrace();
                    }
            }
            else{
                    strAPN = "CMWAP";
            }
            //
异步调用
            search.asyncRequest(woeid, strAPN, listener);                 

            //
异步调用类:
package com.search.weather;

import com.search.RequestListener;
import com.search.common.HttpUtils;

import android.os.Bundle;
import android.util.Log;

/**
*
查询类
* @author Administrator
*
*/
public class Search {
       
        private static final String HTTP_URL = "http://sds.XXXXXX.com/getinfo";
        private static final String HTTP_WAP_URL = "http://10.0.0.172/getinfo";
        private static final String METHOD = "GET";
        private static final String LOG_TAG = "XXX";
       
       
        public String request(String strAPN){
                if(woeid != null){
                        Bundle params = new Bundle();
                       
                       
                        if (strAPN.equals("CMWAP"))
                        {
                                return HttpUtils.openUrl1(HTTP_WAP_URL, METHOD, params,null,strAPN);                               
                        }
                        else
                        {
                                return HttpUtils.openUrl(HTTP_URL, METHOD, params,null,strAPN);
                        }                       
                }else{
                        return null;
                }
        }
       
        //
异步封装
        public void asyncRequest(final String strAPN, final RequestListener listener){
               
                new Thread(new Runnable() {
                       
                        @Override
                        public void run() {
                               
                                try {
                                        String response = request(strAPN);
                                        listener.onComplete(response);
                                } catch (Exception e) {
                                        Log.e(LOG_TAG, e.getMessage());
                                        listener.onException(e);
                                }
                               
                        }
                }).start();
        }

}
对于CMWAP的方法需要做以下逻辑处理:

        public static String openUrl(String url, String method, Bundle params, String enc, String strAPN){
               
                String response = null;
               
                if(method.equals("GET")){
                        url = url + "?" + encodeUrl(params);
                }
               
                try {
                        //Log.d(LOG_TAG, "Url:"+url);                       
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                       
                        conn.setRequestProperty("User-Agent", System.getProperties()
                                        .getProperty("http.agent")
                                        );
                        if (strAPN.equals("CMWAP"))
                        {
                                conn.setRequestProperty("X-Online-Host", "sds.XXXXXX.com");//
这里需要换成调用的真正的网址
                                conn.setDoInput(true);
                        }
                       
                        conn.setConnectTimeout(30000);
                        conn.setReadTimeout(30000); //
设置超时时间
                       
                        if(method.equals("POST")){
                                conn.setRequestMethod("POST");
                                conn.setDoOutput(true);
                                conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
                        }
                        response = read(conn.getInputStream(),enc);
                } catch (Exception e) {
                        //Log.e(LOG_TAG, e.getMessage());
                        throw new RuntimeException(e.getMessage(),e);
                }
                return response;
        }

最后还要在AndroidManifest.xml加上以下权限:
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_APN_SETTINGS"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
   
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
   



 

原创粉丝点击