您的位置:首页 > 其它

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

2011-10-19 08:47 295 查看
1.由于开发过程当中,由于需要调用第三方的HTTP服务,而在正式上线的时候碰到了调用HTTP不通,经过网络这个学习工具,学到了一点点,原来在家里我一直都用的WIFI来测试,在没有WIFI的情况下,移动分CMWAP和CMNET两种访问方式网络,

简单一点来说,就是WIFT和CMNET就是直连网络,而CMWAP需要多了一个代理,现在我就简单处理了一下,如果有什么不对的地方,希望大家提出来,共同进步,

我是菜鸟我怕谁!哈!

智能进行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(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(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>

报文的返回解析这里就不写了,上面只是我在开发过程中的碰到问题以及解决方法,如果大家有更好的方法,请指导一下,共同学习....

有部分坛友对这一块还是比较有兴趣的,上面写得还是有点乱,以下部分代码作为以上思路的实战,个人感觉清晰一点:

我就以一个android应用当中都要实现的在线更新APK模块的实例对它来一次总结:

updatepro.xml的代码:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<!-- content栏 -->

<ProgressBar android:id="@+id/progressBar"

style="?android:attr/progressBarStyleHorizontal"

android:layout_width="200dip"

android:layout_height="wrap_content"

android:max="100"

android:progress="50"

android:layout_marginTop="20dp"

android:secondaryProgress="75" />

</LinearLayout>

//-------------------------------------------------------------------------

package com.search.update;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

import com.search.R;

import android.app.Activity;

import android.app.ActivityManager;

import android.app.AlertDialog;

import android.app.ActivityManager.RunningAppProcessInfo;

import android.content.ComponentName;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.pm.ResolveInfo;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ProgressBar;

import android.widget.TextView;

import android.widget.Toast;

import android.app.AlertDialog;

import android.content.BroadcastReceiver;

import android.content.ContentResolver;

import android.content.ContentValues;

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;

/**

* @author tuoer123

*

*

*/

public class UpdateApplication extends Activity {

Cursor cursor_current,cursor_need;

Uri PREFERRED_APN_URI, APN_TABLE_URI;

int newCreateAPN_Id;

String APN_Id;

TelephonyManager tm;

WifiManager wifi;

private String strAPN;

//版本标识

private String strFlag ="";

private String APKNAME = "XX.apk";

private String apkUrl="http://XX.XX.XX.XX:802/XX.apk";

private String apkUrl1="http://10.0.0.172/XX.apk";

private ProgressBar progressBar;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Bundle bundle = this.getIntent().getExtras();

strFlag = bundle.getString("strFlag");

strAPN = "WIFI";

if (strFlag.equals("1"))

{

new AlertDialog.Builder(UpdateApplication.this).setTitle("提示").setMessage("发现新版本,是否更新?")

.setPositiveButton("确定",

new DialogInterface.OnClickListener(){

public void onClick(DialogInterface dialoginterface, int i){

setContentView(R.layout.updatepro);

new Thread(){

public void run(){

// do something

progressBar = (ProgressBar) findViewById(R.id.progressBar);

progressBar.setIndeterminate(false);

progressBar.setVisibility(View.VISIBLE);

progressBar.setMax(100);

progressBar.setProgress(0);

downloadAPK(apkUrl);

progressBar.setProgress(30);

invokeAPK();

progressBar.setProgress(60);

installAPK();

progressBar.setProgress(100);

}

}.start();

}

}

).setNegativeButton("退出", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

finish();

}

}).show();

}

else

{

new AlertDialog.Builder(UpdateApplication.this).setTitle("提示").setMessage("已经是最新版本!")

.setPositiveButton("确定",

new DialogInterface.OnClickListener(){

public void onClick(DialogInterface dialoginterface, int i){

finish();

}

}

).show();

}

}

private void downloadAPK(String apkUrl) {

String filePath = getSDPath() +"/"+ APKNAME;

URL url = null;

//网络判断

//如果wifi是打开的,则直接调用就可以了

wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);

if(wifi.isWifiEnabled()){

strAPN = "WIFI";

try {

url = new URL(apkUrl);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

InputStream in = con.getInputStream();

File fileOut = new File(filePath);

FileOutputStream out = new FileOutputStream(fileOut);

byte[] bytes = new byte[1024];

int c;

while ((c = in.read(bytes)) != -1) {

out.write(bytes, 0, c);

}

in.close();

out.close();

} catch (Exception e) {

e.printStackTrace();

}

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";

}

try {

if (strAPN.equals("CMWAP"))

{

url = new URL(apkUrl1);

}

else

{

url = new URL(apkUrl);

}

HttpURLConnection con = (HttpURLConnection) url.openConnection();

if (strAPN.equals("CMWAP"))

{

con.setRequestProperty("X-Online-Host", "XX.XX.XX.XX:802");

con.setDoInput(true);

}

InputStream in = con.getInputStream();

File fileOut = new File(filePath);

FileOutputStream out = new FileOutputStream(fileOut);

byte[] bytes = new byte[1024];

int c;

while ((c = in.read(bytes)) != -1) {

out.write(bytes, 0, c);

}

in.close();

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

private void installAPK() {

String fileName = getSDPath() + "/" + APKNAME;

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");

startActivity(intent);

}

private void invokeAPK() {

Uri packageURI = Uri.parse("package:com.search.MainActivity");

Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);

startActivity(uninstallIntent);

}

private String getSDPath() {

File sdDir = null;

boolean sdCardExist = Environment.getExternalStorageState().equals(

android.os.Environment.MEDIA_MOUNTED); // determine whether sd card is exist

if (sdCardExist) {

sdDir = Environment.getExternalStorageDirectory();// get the root directory

}

return sdDir.toString();

}

//------------------------------------------网络部分--------------------------------------------

//获取当前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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐