显示如图:
清单文件中加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
主逻辑代码文件:
package com.example.day22_service_download;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private static final String path ="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clickbt(View v)
{
switch(v.getId())
{
case R.id.bt:
Intent intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
break;
case R.id.bt2:
Intent intent2=new Intent(MainActivity.this,Second.class);
intent2.putExtra("path", path);
startActivity(intent2);
}
}
}
主布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="服务下载图片"
android:onClick="clickbt" />
<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从SD卡读出图片"
android:onClick="clickbt"
android:layout_below="@+id/bt"/>
</RelativeLayout>
继承service的类文件:
package com.example.day22_service_download;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service{
private static final String path ="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(){
public void run() {
if(MyAsyncTask.isNetwork(MyService.this))
{
byte data[]=MyAsyncTask.request(path);
if(WriteFile.isSDcard())
{
if(WriteFile.write(data, path))
{
Intent intent=new Intent(MyService.this,MyBroad.class);
sendBroadcast(intent);
}
else
{
System.out.println("写入到SD卡失败");
}
}
else
{
System.out.println("SD卡不可用");
}
}
else
{
Toast.makeText(getApplicationContext(), "网络异常,请检查", 0).show();
}
};
}.start();
return START_NOT_STICKY;
}
}
访问网络工具类:
package com.example.day22_service_download;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class MyAsyncTask {
public static boolean isNetwork(Context context){
//得到网络的管理者
ConnectivityManager manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info!=null){
return true;
}else{
return false;
}
}
public static byte[] request(String path)
{
ByteArrayOutputStream bo=new ByteArrayOutputStream();
try
{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setDoInput(true);
con.connect();
if(con.getResponseCode()==200)
{
InputStream in = con.getInputStream();
int count=0;
byte b[]=new byte[1024];
while((count=in.read(b))!=-1)
{
bo.write(b, 0, count);
bo.flush();
}
}
return bo.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
保存到SD卡工具类:
package com.example.day22_service_download;
import java.io.File;
import java.io.FileOutputStream;
import android.os.Environment;
public class WriteFile {
public static boolean isSDcard()
{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
public static boolean write(byte data[],String path)
{
boolean flag=false;
try
{
String fileName=path.substring(path.lastIndexOf("/")+1);
File file=new File(Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
FileOutputStream fo=new FileOutputStream(file);
fo.write(data);
flag=true;
fo.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return flag;
}
}
广播类:
package com.example.day22_service_download;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.widget.Toast;
public class MyBroad extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "写入到SD卡成功",0).show();
}
}
第二个Activity逻辑代码文件:
package com.example.day22_service_download;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;
public class Second extends Activity{
ImageView iv;
ByteArrayOutputStream bo=new ByteArrayOutputStream();
String path;
Bitmap bm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
iv=(ImageView) findViewById(R.id.iv);
Intent in=getIntent();
path=in.getStringExtra("path");
read();
}
public void read()
{
String fileName=path.substring(path.lastIndexOf("/")+1);
File file=new File(Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
String filePath = file.getAbsolutePath();
Bitmap bm = BitmapFactory.decodeFile(filePath);
iv.setImageBitmap(bm);
}
}
第二个Activity布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ff00">
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>