android 中的网络问题

来源:互联网 发布:仓储软件有哪些 编辑:程序博客网 时间:2024/05/29 19:56

转自:http://blog.sina.com.cn/s/blog_8a86f4dd0101ak7g.html

我们都知道,要打开网络连接是要有相应的权限的,但是目前Android中并没有直接打开和关闭网络连接的权限,因此我们只能通过APN来实现:

由于Android对于APN的网络API没有公开,不过我们可以阅读源代码,然后进行数据库操作,系统会自动监听数据库的变化,从而实现开启或者关闭APN。

 

其实原理很简单 :
1 、 当开启APN的时候,设置一个正确的移动或者联通的APN
2、 关闭的时候设置一个错误APN就会自动关闭网络

下面是源代码:

package com.mandr.network.demo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class OpenNetworkActivity extends Activity {
 private Button open, close;
 Uri uri =Uri.parse("content://telephony/carriers");

 @Override
 public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  open = (Button)findViewById(R.id.open);
  close = (Button)findViewById(R.id.close);
  open.setOnClickListener(newView.OnClickListener() {

   publicvoid onClick(View v) {
    openAPN();
   }
  });
  close.setOnClickListener(newView.OnClickListener() {

   publicvoid onClick(View v) {
    closeAPN();
   }
  });
 }

 public void openAPN() {
  List list = getAPNList();
  for (APN apn : list) {
   ContentValuescv = new ContentValues();
   cv.put("apn",APNMatchTools.matchAPN(apn.apn));
   cv.put("type",APNMatchTools.matchAPN(apn.type));
   getContentResolver().update(uri,cv, "_id=?",
     newString[] { apn.id });
  }
 }

 public void closeAPN() {
  List list = getAPNList();
  for (APN apn : list) {
   ContentValuescv = new ContentValues();
   cv.put("apn",APNMatchTools.matchAPN(apn.apn) + "mdev");
   cv.put("type",APNMatchTools.matchAPN(apn.type) + "mdev");
   getContentResolver().update(uri,cv, "_id=?",
     newString[] { apn.id });
  }
 }

 private List getAPNList() {
  String tag ="Main.getAPNList()";
  // current不为空表示可以使用的APN
  String projection[] = {"_id,apn,type,current" };
  //查询数据库
  Cursor cr =this.getContentResolver().query(uri, projection, null,
    null,null);
  List list = newArrayList();
  while (cr != null &&cr.moveToNext()) {
   Log.d(tag,
     cr.getString(cr.getColumnIndex("_id"))+ "  "
       +cr.getString(cr.getColumnIndex("apn")) + " "
       +cr.getString(cr.getColumnIndex("type")) + " "
       +cr.getString(cr.getColumnIndex("current")));
   APN a = newAPN();
   a.id =cr.getString(cr.getColumnIndex("_id"));
   a.apn =cr.getString(cr.getColumnIndex("apn"));
   a.type =cr.getString(cr.getColumnIndex("type"));
   list.add(a);
  }
  if (cr != null)
   cr.close();
  return list;
 }

 public static class APN {
  String id;
  String apn;
  String type;
 }

}

APNMatchTools.java
package com.mandr.network.demo;

public class APNMatchTools {
 public static class APNNet {

  public static String CMWAP ="cmwap";

  public static String CMNET ="cmnet";
  // 中国联通3GWAP设置 中国联通3G因特网设置中国联通WAP设置 中国联通因特网设置
  // 3gwap 3gnet uniwapuninet

  public static String GWAP_3= "3gwap";  public static String GNET_3= "3gnet";  public static String UNIWAP= "uniwap";  public static String UNINET= "uninet"; } public static String matchAPN(StringcurrentName) {  if ("".equals(currentName) ||null == currentName) {   return"";  }  currentName =currentName.toLowerCase();  if(currentName.startsWith(APNNet.CMNET))   returnAPNNet.CMNET;  else if(currentName.startsWith(APNNet.CMWAP))   returnAPNNet.CMWAP;  else if(currentName.startsWith(APNNet.GNET_3))   returnAPNNet.GNET_3;  else if(currentName.startsWith(APNNet.GWAP_3))   returnAPNNet.GWAP_3;  else if(currentName.startsWith(APNNet.UNINET))   returnAPNNet.UNINET;  else if(currentName.startsWith(APNNet.UNIWAP))   returnAPNNet.UNIWAP;  else if(currentName.startsWith("default"))   return"default";  else   return"";  // returncurrentName.substring(0, currentName.length() -  // SUFFIX.length()); }}


最后别忘了加入修改APN的权限:


转自:http://www.csdn.net/article/a/2011-07-03/300974

本文简介

本文综述了Android应用程序开发可用的联网选项以及有关Android基本联网技巧等内容。

本文提供学习如何针对应用程序开发利用Android的联网选项。当与环境监测系统一起使用时,探索一个要求联网的真实世界的应用程序。本文中提供了可供实践用的示例代码片段。

范围:

本文旨在为希望简单了解Android编程的初学者而设计。本文逐步指导初学者来开发Android中基于网络的应用程序。本文假定用户已经安装了可开发应用程序的Android和必要的工具,同样假定用户已熟悉Java或熟悉基于对象的编程概念。

简介

网络编程在无线应用程序开发过程中起到了重要的作用。Android包括Apache HttpClient库,此库为执行Android中的网络操作之首选方法。Android还可允许通过标准的Java联网API(java.net包)来访问网络。即便使用Java.net包,也是在内部使用该Apache库。

为了访问互联网,你的应用程序需要获取“android.permission.INTERNET”许可

Android中与网络相关的包

以下内容为Android SDK中与网络相关的部分包

• java.net

提供联网相关的类,包括流和数据报套接字、互联网协议以及通用的HTTP处理。此为多用途的联网资源。经验丰富的Java开发人员可立即使用此惯用的包来创建应用程序。

• java.io

 尽管未明确联网,但其仍然非常重要。此包中的各种类通过其他Java包中提供的套接字和链接来使用。它们也可用来与本地文件进行交互(与网络进行交互时经常发生)。

• java.nio

 包含表示具体数据类型的缓冲的各种类。便于基于Java语言的两个端点之间的网络通信。

• org.apache.*

 表示可为进行HTTP通信提供精细控制和功能的各种包。你可将Apache识别为普通的开源Web服务器。

• android.net

 包括核心java.net.*类之外的各种附加的网络接入套接字。此包包括URL类,其通常在传统联网之外的Android应用程序开发中使用。

• android.net.http

 包含可操作SSL证书的各种类。

• android.net.wifi

 包含可管理Android平台中WiFi(802.11无线以太网)所有方面的各种类。并非所有的设备均配备有WiFi能力,尤其随着Android在对制造商(如诺基亚和LG)手机的翻盖手机研发方面取得了进展。

• android.telephony.gsm

 包含管理和发送短信(文本)消息所要求的各种类。随着时间的推移,可能将引入一种附加的包,以提供有关非GSM网络(如CDMA或类似android.telephony.cdma)的类似功能。

Android联网

使用Apache HttpClient库

在Apache HttpClient库中,以下内容为对网络连接有用的各种包。

  • org.apache.http.HttpResponse

  • org.apache.http.client.HttpClient

  • org.apache.http.client.methods.HttpGet

  • org.apache.http.impl.client.DefaultHttpClient
     

HttpClient httpclient=new DefaultHttpClient();

如欲从服务器检索此信息,使用HttpGet类构造器

HttpGet request=new HttpGet(“http://innovator.samsungmobile.com”);

然后通过HttpClient类的execute()方法中的HttpGet对象来检索HttpResponse对象

HttpResponse response = client.execute(request);

接着读取已检索的响应

BufferedReader rd = new BufferedReader

                                    (new InputStreamReader(response.getEntity().getContent()));

    String line = "";

    while ((line = rd.readLine()) != null) {

        Log.d(“output: ”,line);

    }

示例

以下提供内容为可使用Apache HttpClient库来进行网络连接的示例代码片段。添加许可“android.permission.INTERNET”至"AndroidManifest.xml"中,从而可允许你的应用程序访问网络。

AndroidManifest.xml

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

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

      package="com.apache"

      android:versionCode="1"

      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <activity android:name=".ApacheConnection"

                  android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

使用activity“ApacheConnection”来创建项目“com.apache”。将布局“main.xml”更改为如下。

Main.xml 

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

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

    <TextView

        android:text="Enter URL"

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content">

    </TextView>

   

    <EditText

        android:id="@+id/editText1"

        android:layout_width="match_parent"

        android:text="http://innovator.samsungmobile.com"

        android:layout_height="wrap_content">

    </EditText>

    <Button

        android:text="Click Here"

        android:id="@+id/button1" 

        android:layout_width="wrap_content" 

        android:layout_height="wrap_content">

     </Button>

    <EditText

        android:id="@+id/editText2"

        android:layout_width="match_parent" 

        android:layout_height="fill_parent">

     </EditText>

</LinearLayout>

 

此刻在java中创建一个代码,此代码将可允许查看HTML代码。

ApacheConnection.java

 

package com.apache;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class ApacheConnection extends Activity {

 

Button bt;

 TextView textView1;

 TextView textView2;

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

 @Override

 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  bt = (Button) findViewById(R.id.button1);

  textView1 = (TextView) findViewById(R.id.editText1);

  textView2 = (TextView) findViewById(R.id.editText2);

    

bt.setOnClickListener(new OnClickListener() {

              

@Override

  public void onClick(View v) {

      // TODO Auto-generated method stub   

      textView2.setText("");

    

     try {

          /*Apache HttpClient Library*/

      HttpClient client = new DefaultHttpClient();

  HttpGet request = new HttpGet(textView1.getText().toString());

       HttpResponse response = client.execute(request);

      /* response code*/

      BufferedReader rd = new BufferedReader(

      new InputStreamReader(response.getEntity().getContent()));

     String line = "";

      while ((line = rd.readLine()) != null) {

            textView2.append(line);

     }

    } catch (Exception exe) {

         exe.printStackTrace();

                          }

  }

          });

 }

}

使用Java Networking API

在Java联网API中,以下内容为对网络连接有用的各种包。

  • java.net.URL

  • java.net.URLConnection

    通过创建URL实例,指定互联网中资源的位置

URL url=new URL(“http://innovator.samsungmobile.com”);

然后使用URLConnection类进行读取或写入

URLConnection conn = url.openConnection();

接着读取已检索的响应

BufferedReader rd = new BufferedReader

                                    (new InputStreamReader(response.getEntity().getContent()));

    String line = "";

    while ((line = rd.readLine()) != null) {

        System.out.println(line);

    }

示例

以下提供内容为可使用Java.net包来进行网络连接的示例代码片段。

添加许可“android.permission.INTERNET”至"AndroidManifest.xml"中,从而可允许你的应用程序访问网络。

 AndroidManifest.xml

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

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

   package="com.net"

   android:versionCode="1"

   android:versionName="1.0">

  <uses-sdk android:minSdkVersion="8" />

  <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">

     <activity android:name=".NetworkingProject" android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

借助 "NetworkingProject"活动创建"com.net"项目, 改变布局"main.xml",如下所示

Main.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"

    >

    <TextView

        android:text="Enter URL"

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content">

    </TextView>

   

    <EditText

        android:id="@+id/editText1"

        android:layout_width="match_parent"

        android:text="http://innovator.samsungmobile.com"

        android:layout_height="wrap_content">

    </EditText>

   

    <Button

        android:text="Click Here"

        android:id="@+id/button1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content">

     </Button>

    

    <EditText

        android:id="@+id/editText2"

        android:layout_width="match_parent"

        android:layout_height="fill_parent">

    </EditText>

</LinearLayout>

现在创建可实现查看HTML代码的java程序。

NetworkingProject.java

 

 

package com.net;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class NetworkingProject extends Activity {

 

Button bt;

 TextView textView1;

 TextView textView2;

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

 @Override

 public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.main);

   bt = (Button) findViewById(R.id.button1);

   textView1 = (TextView) findViewById(R.id.editText1);

   textView2 = (TextView) findViewById(R.id.editText2);

    bt.setOnClickListener(new OnClickListener() {

       @Override

        public void onClick(View v) {

                 // TODO Auto-generated method stub    

   textView2.setText("");

          try {

   /*Java Networking API*/

                 URL url = new URL(textView1.getText().toString());

          URLConnection conn = url.openConnection();

          /*Read the Response*/

          BufferedReader rd = new BufferedReader(new 

                     InputStreamReader(conn.getInputStream()));

   String line = "";

   while ((line = rd.readLine()) != null) {

     textView2.append(line);

   }

          } catch (Exception exe) {

   exe.printStackTrace();

          }

    }

 });

  }

}

0 0
原创粉丝点击