第一部分 从指定网址下载文件 并读出其内容
==============================================================================
需要在AndroidManifest.xml里加入如下句
<uses-permission android:name="android.permission.INTERNET" />
/*检测是否需要网络升级*/
try{
CheckForSystemNetUpdate();
}catch(IOException e){
}
private void CheckForSystemNetUpdate() throws IOException {
Log.d(TAG, "CheckForSystemNetUpdate...");
if(isNetworkAvailable()){
Log.d(TAG, "NetworkAvailable...");
URL url = null;
try {
url = new URL("http://update.egreatworld.com:8080/software/update/M6/update_signed.ini");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream inputStream = null;
BufferedReader bufferedReader = null;
StringBuffer buffer = new StringBuffer();
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
try{
httpUrlConnection.connect();
} catch(IOException e){
Log.e(TAG, "httpUrlConnection connect error!!!!!");
e.printStackTrace();
}
Log.d(TAG, "response code = " + httpUrlConnection.getResponseCode());
inputStream = httpUrlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
buffer.append("\r\n");
}
httpUrlConnection.disconnect();
Log.d(TAG, "---------ini = "+buffer);
parseIni(buffer.toString());
}
}
/**
* 解析ini文件里的字符串
* @param string 要解析的字符串
*/
private void parseIni(String str) {
String parts[] = str.split("\r\n");
boolean isEnforcement = false;
String version = "";
String updateinfo = "";
int i=0;
for(;i<parts.length;i++){
Log.d(TAG, "==============test = "+parts[i]);
if("updatemode=0".equals(parts[i].trim())){
isEnforcement = false;
}else if("updatemode=1".equals(parts[i].trim())){
isEnforcement = true;
}else if("[version]".equals(parts[i].trim())){
version = parts[i+1].trim();
}else if("[updateinfo]".equals(parts[i].trim())){
i++;
break;
}
}
String temp[] = version.split("=");
version = temp[1].trim();
/*读取当前版本号*/
String tempString = (Build.VERSION.INCREMENTAL.substring(1)).trim();
Log.d(TAG, "-------------system version="+tempString);
if(tempString.equals(version)){
}else{
/*得到升级信息*/
for(;i<parts.length;i++){
updateinfo +=parts[i]+"\r\n";
Log.d(TAG, "==============test = "+parts[i]);
}
showNetUpdateDialog(isEnforcement,version,updateinfo);
}
}
private void showNetUpdateDialog(boolean isEnforcement,String version,String updateinfo){Log.d(TAG, "isEnforcement="+isEnforcement+"\n"+"updateinfo="+updateinfo);/*添加蒙层*/ mHomeActivity.findViewById(R.id.gray_background).setVisibility(View.VISIBLE); final DialogNetUpdate mDialogNetUpdate= new DialogNetUpdate(mContext, isEnforcement, version, updateinfo);mDialogNetUpdate.setOnclickCancel().setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mDialogNetUpdate.dismiss();/*去除蒙层*/ mHomeActivity.findViewById(R.id.gray_background).setVisibility(View.GONE);}});mDialogNetUpdate.setOnclickConfirm().setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent();ComponentName name = null;name = new ComponentName("com.android.settings", "com.android.settings.update.SystemNetUpdateActivity");intent.setComponent(name);mContext.startActivity(intent);//加入转场动画((Activity) mContext).overridePendingTransition(R.anim.zoom_enter,R.anim.zoom_exit);}});mDialogNetUpdate.show();}
Dialog代码如下
package com.egreat.commonComponent;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.egreat.elauncher.HomeActivity;
import com.egreat.elauncher.R;
import com.egreat.elauncher.R.id;
import com.egreat.elauncher.R.layout;
/**
* @author peter.wen
*
*/
public class DialogNetUpdate {
Dialog mDialog;
TextView mTextViewLeftTitle,mTextViewRightTitle,mTextViewContent;
Context mContext;
//要现实的文字
String mVersionString,mInfoString;
//取消按钮
Button mDialog_cancal,mDialog_confirm;
LayoutInflater inflater;
//自定义的dialog布局
View linearlayout;
public DialogNetUpdate(Context mContext,boolean isEnforcement,String version,String updateinfo) {
// TODO Auto-generated constructor stub
this.mContext = mContext;
inflater = LayoutInflater.from(mContext);
linearlayout = inflater.inflate(R.layout.dialog_net_update, null);
//取消按钮
mDialog_cancal = (Button) linearlayout.findViewById(R.id.dl_cancal);
//确认按钮
mDialog_confirm = (Button) linearlayout.findViewById(R.id.dl_confirm);
mTextViewLeftTitle = (TextView) linearlayout.findViewById(R.id.dl_text_left_title);
mTextViewRightTitle = (TextView) linearlayout.findViewById(R.id.dl_text_right_title);
mTextViewContent = (TextView) linearlayout.findViewById(R.id.dl_text_content);
if(isEnforcement){
mDialog_cancal.setVisibility(View.GONE);
}
mTextViewRightTitle.setText(version);
mTextViewContent.setText(updateinfo);
//用Dialog 用R.style.dialog 可以去除白边 不能用 new AlertDialog.Builder(mContext).setView(linearlayout).show();去做
mDialog = new Dialog(mContext,R.style.dialog);
mDialog.setContentView(linearlayout);
mDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
/*屏蔽按键*/
mDialog.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_ENTER:
return false;
default:
break;
}
return true;
}
});
mDialog_confirm.requestFocus();
}
public void show(){
mDialog.show();
}
//关闭对话框
public void dismiss(){
mDialog.dismiss();
}
public Button setOnclickCancel(){
return mDialog_cancal;
}
public Button setOnclickConfirm(){
return mDialog_confirm;
}
public void setCancelName(String cancel) {
mDialog_cancal.setText(cancel);
}
public void setConfirmName(String confirm) {
mDialog_confirm.setText(confirm);
}
}
dialog对应的xml文件如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<FrameLayout
android:id="@+id/dialog"
android:layout_width="454dp"
android:layout_height="500dp"
android:background="@drawable/common_dialog_net_update"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_gravity="top">
<TextView
android:id="@+id/dl_text_left_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="@string/new_software"
android:textSize="25sp" />
<TextView
android:id="@+id/dl_text_right_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="@string/software_version"
android:textSize="25sp" />
</LinearLayout>
<ScrollView
android:id="@+id/ScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:layout_gravity="center_horizontal"
android:scrollbarThumbVertical="@drawable/indicate"
android:scrollbarTrackVertical="@drawable/indicatebg"
android:nextFocusDown="@+id/dl_confirm"
>
<TextView
android:id="@+id/dl_text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:lineSpacingExtra="8dp"
android:text="@string/test"
android:textSize="25sp" />
</ScrollView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="0dp"
android:orientation="horizontal" >
<Button
android:id="@+id/dl_cancal"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:textColor="#FFFFFFFF"
android:background="@drawable/dialog_button_selector"
android:textSize="25dp"
android:layout_gravity="bottom"
android:layout_marginBottom="0dp"
android:nextFocusUp="@+id/ScrollView"
android:text="@string/cancal" />
<Button
android:id="@+id/dl_confirm"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#FFFFFFFF"
android:background="@drawable/dialog_button_selector"
android:textSize="25dp"
android:layout_gravity="bottom"
android:layout_marginBottom="0dp"
android:nextFocusUp="@+id/ScrollView"
android:text="@string/update_now" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
第二部分 从网上下载文件放在本地
==============================================================================
package com.example.hello;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
downloadXml();
}
}).start();
}
protected boolean downloadXml() {
Log.d(TAG, "---------downloadXml");
HttpURLConnection httpConnection = null;
InputStream is = null;
FileOutputStream fos = null;
URL url = null;
String localPath = getCacheDir() + "/wen.txt";
try {
url = new URL("http://192.168.4.4/111111.txt");
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.connect();
is = httpConnection.getInputStream();
fos = new FileOutputStream(new File(localPath));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) > -1) {
fos.write(buffer, 0, len);
fos.flush();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (httpConnection != null) {
httpConnection.disconnect();
}
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, "---------downloadXml finally");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hello"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.hello.MainActivity"
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>
第三部分 从网上获取图片设在imageView里
==============================================================================
对第二部分代码稍加改造即可protected Bitmap downloadXml() {
Log.d(TAG, "---------downloadXml");
Bitmap mBitmap;
HttpURLConnection httpConnection = null;
InputStream is = null;
FileOutputStream fos = null;
URL url = null;
String localPath = getCacheDir() + "/22.jpg";
try {
url = new URL("http://192.168.4.4/11.jpg");
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.connect();
is = httpConnection.getInputStream();
fos = new FileOutputStream(new File(localPath));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) > -1) {
fos.write(buffer, 0, len);
fos.flush();
}
return BitmapFactory.decodeFile(localPath);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (httpConnection != null) {
httpConnection.disconnect();
}
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, "---------downloadXml finally");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView iamge;
iamge = (ImageView) findViewById(R.id.iamge);
new Thread(new Runnable() {
@Override
public void run() {
b = downloadXml();
}
}).start();
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
iamge.setImageBitmap(b);
}