package com.Aina.Android;
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.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
public class Test_Network extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("1>.按下CENTER键发送邮件 2>.按下KEY_DOWN键下载网络上的数据");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_CENTER){
Uri uri = Uri.parse("mailto:xxxx.com");//邮件地址,注意:此处一定要加<mailto:>,否则无法发送.
Intent intent = new Intent(Intent.ACTION_SENDTO,uri);//创建Intent
intent.putExtra(Intent.EXTRA_SUBJECT, "数据备份");//设置邮件主题
intent.putExtra(Intent.EXTRA_TEXT, "100000备份数据");//设置邮件内容
this.startActivity(intent);
// this.finish();
}else if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
TextView tv = (TextView) this.findViewById(R.id.TextView);
String myString = "";
try{
URL url = new URL("http://192.168.1.3:8080/android.txt");//定义访问的地址
URLConnection urlconn = url.openConnection();//打开连接
InputStream input = urlconn.getInputStream();//获得输入流
int count = 0;
// BufferedInputStream bis = new BufferedInputStream(input);
// ByteArrayBuffer baf = new ByteArrayBuffer(100);
// while((count = bis.read())!=-1){
// baf.append((byte)count);
// }
// myString = new String(baf.toByteArray());
StringBuffer sb = new StringBuffer();
while((count = input.read())!=-1){
sb.append((char)count);
}
myString = sb.toString();
}catch(Exception ex){
myString = ex.getMessage();
ex.printStackTrace();
}
tv.setText(myString);
}
return super.onKeyDown(keyCode, event);
}
}
[b]由于在程序中访问了网络,我们需要在AndroidManifest.xml文件中给于权限:
<uses-permission android:name="android.permission.INTERNET" />
[/b]