功能:點擊按鈕,啓動一個Service下載指定地址的內容,並且將內容保存到Sdcard卡,下載時發送一個進度條通知到通知欄。
Activity 類:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private String PATH = "http://e.hiphotos.baidu.com/image/pic/item/63d9f2d3572c11dfbdb69872612762d0f703c27f.jpg";//數據地址,這裏給了一張圖片地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, GetPictures.class);
intent.putExtra("PATH", PATH);//傳遞一個參數
startService(intent);//開啓服務
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Service 繼承類:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class GetPictures extends Service {
private String PATH = "";
private Notification.Builder builder;
private NotificationManager manager;
private Handler handler = new Handler() {// 消息隊列
@Override
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
stopSelf();
Toast.makeText(getApplicationContext(), "下載完成", 1).show();
}
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder = new Notification.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher).setTicker("下載圖片")
.setContentTitle("圖片下載").setContentText("正在下載圖片")
.setAutoCancel(true);// 用戶點擊瀏覽一次後,通知消失;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
PATH = intent.getStringExtra("PATH");// 接受傳遞過來的參數
new myTast().start();// 創建一個新的線程並且啓動
return super.onStartCommand(intent, flags, startId);
}
public class myTast extends Thread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(PATH);
HttpResponse httpResponse;
InputStream inputStream = null;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
int len = 0;
int len_data = 0;
byte[] data = new byte[512];
try {
httpResponse = client.execute(get);
long len_long = httpResponse.getEntity().getContentLength();
if (httpResponse.getStatusLine().getStatusCode() == 200) {
ToSdcard to = new ToSdcard();
inputStream = httpResponse.getEntity().getContent();
while ((len = inputStream.read(data)) != -1) {
arrayOutputStream.write(data, 0, data.length);
len_data += len;
int progress_value = (int) ((len_data / (float) len_long) * 100);//進度條刻度計算
builder.setProgress(100, progress_value, false);
manager.notify(1000, builder.build());
}
boolean flag = to.saver("bb.png",//保存的文件名
arrayOutputStream.toByteArray());// 數據保存到本地Sdcard
builder.setContentText("下載完成!");
manager.notify(1000, builder.build());
if (flag) {
handler.sendEmptyMessage(1);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
佈局文件中只有一個按鈕,就不貼源碼了,記得在清單文件中聲明服務以及獲取連網權限和Sdcard卡讀寫權限
<service android:name=".GetPictures"></service>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>