您的位置:首页 > 移动开发 > Android开发

Android 小项目之--数据存储【Network】(附源码)

2010-06-20 16:06 661 查看
将数据保存发送到电子邮件中备份,首要前提应该先在模拟器中设置好电子邮件帐户,设置如下:

第一步,启动模拟器,打开“菜单”,选择“电子邮件”项,填写相应帐号和密码。
读取XML代码参考

package com.terry;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class readxmlActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.readxml);

TextView tv=(TextView)findViewById(R.id.TextView01);

String msg="";
try {
URL url=new URL("http://www.az1314.com/txt/00.txt"); //要访问的数据文件
URLConnection con=url.openConnection();
InputStream is=con.getInputStream();
BufferedInputStream bis=new BufferedInputStream(is);
ByteArrayBuffer baf=new ByteArrayBuffer(100);
int current=0;
while ((current=bis.read())!= -1) {
baf.append((byte)current);
}
msg=new String(baf.toByteArray());

} catch (Exception e) {
// TODO: handle exception
msg=e.getMessage();
}
tv.setText(msg);
}
}

方法讲解:

URL共有六种构造方法,分别如下:

URL(String spec)
通过传进来的字符串分析,创建一个新的URL实例。
URL(URL context, String spec)
通过传进来的字符串分析,创建一个新的URL实例。需要一个URL的参数
URL(URL context, String spec, URLStreamHandler handler)
通过传进来的字符串分析,创建一个新的URL实例
URL(String protocol, String host, String file)
使用给定的参数创建一个URL实例,需要指定协议,主机文件名
URL(String protocol, String host, int port, String file)
使用给定的参数创建一个URL实例,需要指定协议,主机,端口和文件名
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
使用给定的参数创建一个URL实例,需要指定协议,主机,端口、文件名和处理程序

URLConnection介绍:

用以来实现提供一个具有特定协议类的连接源。
getInputStream 主要用来读取一个URLConnection的资源数据,返回一个InputStream,本文将使用这个方法获取数据

在此不多介绍URLConnection此类,感兴趣的朋友可以查看一下SDK。代码如上,运行效果图:



因为在模拟器运行。 出现乱码了,如果你有真机不妨在真机上试试。

Tip: 访问外部网络需要在配置文件中给予权限,如果你没有权限将会出现如下界面:



权限代码如下:

android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".networkActivity"
android:label="@string/app_name">

</activity>

<activity android:name=".readxmlActivity"><intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter></activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>

至此四种数据存储完结。

源码下载:/Files/TerryBlog/NetworkdDemo.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: