Android利用后臺服務下載網絡數據
/**
service運行在主線程里所以不能使用HTTP協議訪問網絡
try catch的實例盡量在該塊外面定義
*/
public class MyService extends Service {
public MyService() {
// TODO Auto-generated constructor stub
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//獲得圖片地址
final String url=intent.getStringExtra("image_path");
final Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==111)
{
Toast.makeText(MyService.this,"下載完成", Toast.LENGTH_LONG).show();
stopSelf();//startService()啟動后,關閉service
}
}
};//注意分號
//啟動線程訪問網絡
new Thread(new Runnable(){
@Override
public void run() {
//獲得獲取網絡資源的Http客戶端
HttpClient httpClient=new DefaultHttpClient();
//請求方式
HttpPost httpPost=new HttpPost(url);
HttpResponse httpResponse=null;
//網絡資源的字節數組
byte[] data=null;
//文件存儲路徑
File file=new File(Environment.getExternalStorageDirectory(),"圖片后臺下載.jpg");
FileOutputStream fileOutputStream=null;
try {
//執行請求獲得響應
httpResponse=httpClient.execute(httpPost);
//判斷響應是否成功
if(httpResponse.getStatusLine().getStatusCode()==200)
{
//獲得內容的字節數組
data=EntityUtils.toByteArray(httpResponse.getEntity());
//判斷SD卡是否可用
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
fileOutputStream=new FileOutputStream(file);
fileOutputStream.write(data, 0,data.length);
//完成下載發送消息
Message message=Message.obtain();
message.what=111;
handler.sendMessage(message);//向主線程發送消息
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fileOutputStream!=null)
{
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//關閉該進程
if(httpClient!=null)
{
httpClient.getConnectionManager().shutdown();
}
}
}}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
public class MainActivity extends Activity {
private String url="http://p16.qhimg.com/bdr/__85/d/_open360/fengjing0321/9.jpg";
private Button btnDownload=null;
private ImageView image=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDownload=(Button)this.findViewById(R.id.button1);
image=(ImageView)this.findViewById(R.id.imageView1);
btnDownload.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,MyService.class);
intent.putExtra("image_path",url);
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;
}
}
</pre>