通过网络来获取和保存数据资源,这个方法需要设备保持网络连接状态,所以相对存在一些限制。将数据存储到网络上的方法很多,比如将要保存的数据以文件的方式上传到服务器、发送邮件等等。代码示例如下:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private TextView textView;
private int miCount = 0;
private Context mContext;
private OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Uri uri = Uri.parse("www.baidu.com");
Intent intent = new Intent(Intent.ACTION_SEND,uri);
intent .putExtra(Intent.EXTRA_SUBJECT, "数据备份");
intent .putExtra(Intent.EXTRA_TEXT, "本次计数:"+(miCount++));
mContext.startActivity(intent);
textView.setText("send sucess");
break;
case R.id.button2:
String myString = null;
try {
//定义我们要访问的地址
URL url = new URL("http://192.168.1.110:8080/android.txt");
//打开这个url链接
URLConnection conn = url.openConnection();
//从上面的链接中获得输入流
InputStream inputStream = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayBuffer bab = new ByteArrayBuffer(100);
int current = 0;
//一直读到最后
while((current = bis.read()) != -1){
bab.append((byte)current);
}
myString = new String(bab.toByteArray());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
myString = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
myString = e.getMessage();
}
textView.setText(myString);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init(this);
setButtonClickListener();
}
private void setButtonClickListener() {
// TODO Auto-generated method stub
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
}
private void init(Context context) {
// TODO Auto-generated method stub
mContext = context;
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.text_view);
}
}