Service结合通知下载图片
这里我按照mars老师的视频写了一个关于Service下载图片到SD卡根目录,并且在通知栏中显示下载的进度条。
具体的代码基本我都注释意思了,一般都是能看懂的。
下面我说下主Activity
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,DownloadPicture.class);
startService(intent);
}
});
}
}
然后是Service
public class DownloadPicture extends Service {
private String path = "http://www.baidu.com/img/bdlogo.png";
private NotificationManager manager;
private Builder builder;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 2) {
Toast.makeText(getApplicationContext(), "下载完成",
Toast.LENGTH_LONG).show();
Log.e("dd", "makeText");
stopSelf();
}
builder.setProgress(100, msg.arg1, false);
// 发送通知
manager.notify(1001, builder.build());
};
};
@Override
public void onCreate() {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("down load file");
builder.setContentText("down load ..");
new Thread(new DownLoadThread()).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public class DownLoadThread implements Runnable {
@Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
InputStream input = null;
// 字节输出流
ByteArrayOutputStream out = null;
// 获取文件总长度
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
long total_Length = response.getEntity().getContentLength();
int sum_Length = 0;
int leng = 0;
// 这里byte里面可以写1024或者其它数字,写的小主要是让我们看清下载的线条
byte[] data = new byte[6];
// 通过response.getEntity()方法得到httpEntity对象这个对象包装了服务器响应的内容
input = response.getEntity().getContent();
out = new ByteArrayOutputStream();
while ((leng = input.read(data)) != -1) {
sum_Length += leng;
// 换算每次下载的文件刻度参数
int value = (int) (sum_Length / (float) total_Length * 100);
Message msg = Message.obtain();
msg.what = 1;
msg.arg1 = value;
handler.sendMessage(msg);
// 用字节数组输出流把byte数组写入 下载图片用
out.write(data, 0, leng);
}
// out.toByteArray()获取字节数组里面的数据
if (CdDownload.DownloadSd("百度.png", out.toByteArray())) {
handler.sendEmptyMessage(2);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本来可以读取数据这样写byte[] byte=EntityUtils.toByteArray(response.getEntity()); 但是上面已经用read了 就不能在此读取故用字节数组流来获取字节数组。
public class CdDownload {
public static boolean DownloadSd(String filename, byte[] date) {
boolean flag = false;
// 获取sd卡的根目录
File file = Environment.getExternalStorageDirectory();
// 判断sd卡是否可挂载
if (Environment.getExternalStorageDirectory().equals(
Environment.MEDIA_MOUNTED)) {
FileOutputStream output = null;
try {
output = new FileOutputStream(new File(file, filename));
output.write(date, 0, date.length);
flag = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return flag;
}
}
布局的话 我只设定了一个Button用来做下载按钮,这里就不写了。当然这里还需要在配置文件中加上上网与sd卡写入的权限
不懂得可以去这里下载http://download.csdn.net/detail/kluing/7877545