您的位置:首页 > 运维架构 > 网站架构

Android 与web一起工作(Android读取网站特定页面)

2012-02-07 16:39 316 查看
项目设想

网站部分开发一个关于web开发知识的站点,要通过android来阅读这个模块的内容。

实现

通过手机浏览器直接阅读,优点:不用安装单独的客户端。缺点:会存在一些冗余的信息消耗客户的流量。

通过一个自己网站实现的app,优点:可以针对手机客户端单独设计app,将其他图片和无相关的内容过滤掉,节省客户的流量,缺点:开发成本变大。

现在我们通过技术实现第二种实现方式:自己实现Android客户端。

一 建立自己的站点

将自己的站点的内容发布,更新,删除都放到web互联网上维护,相信有很多收费和不收费的,上网找找就能找到自己满意的。我们这次讲得重点是Android app。

二 新建一个view

这个view很简单,就是一个可以下来查看当前全部的文字内容。

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="306px" android:layout_height="410px"
android:layout_x="7px" android:layout_y="61px"
android:scrollbars="vertical" android:fadingEdge="vertical">
<TextView
android:id="@+id/ResultView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="2px"
android:layout_marginBottom="2px"
android:layout_marginLeft="2px"
android:layout_marginRight="2px"
android:text=""
android:layout_x="7px"
android:layout_y="61px"
>
</TextView>
</ScrollView>


三 新建一个app工程(InternetActivity)

这次用到的是HttpGet,类似的还可以使用HttpPost.具体代码如下:

public class InternetActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.rdbox);
TextView rbox=(TextView)findViewById(R.id.ResultView);

HttpGet post=new HttpGet("http://www.demon.com/");
try{
HttpResponse response=new DefaultHttpClient().execute(post);
if(response.getStatusLine().getStatusCode()==200){
String result=EntityUtils.toString(response.getEntity());
result=result.replaceAll("<", "");
result=result.replaceAll(">", "");
rbox.setText(result);
}
else{
rbox.setText("code:"+response.getStatusLine().toString());
}
}
catch(Exception ex){
rbox.setText("error:"+ex.getMessage().toString());
ex.printStackTrace();
}

}

}


运行,发现有错误,不能正常返回内容,查找之后发现,Android的权限很严格,还要在AndroidManifest.xml加入一行代码:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="qiyesite.android.readbox"
android:versionCode="1"
android:versionName="1.0" >

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


记住位置很重要,一定要放到manifest 下的第一级目录。最好上一张运行效果图。



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