- service下载文件,加入标签:
<service android:name=".MyService"></service>
添加相关权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- 代码如下:
public class MainActivity extends Activity {
private Button button;@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
});
}
}public class MyService extends Service {
private final String DOWNPATH = "http://www.baidu.com/img/bdlogo.png";//下载链接@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// 不能直接使用Http协议使用网络,service在UI线程当中,需要创建线程,与主线程分离
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 1) {
stopSelf();
Toast.makeText(getApplicationContext(), "文件下载完毕", 1).show();
}
}
};Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DOWNPATH);
HttpResponse httpResponse = null;
// 获得SD卡的目录
File file = Environment.getExternalStorageDirectory();
FileOutputStream outStream = null;
try {
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
byte[] result = EntityUtils.toByteArray(httpResponse
.getEntity());
// 判断SDK卡是否挂载,并且可以存储数据
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File new_file = new File(file, "bdlogo.png");
outStream = new FileOutputStream(new_file);
outStream.write(result, 0, result.length);
Message message = Message.obtain();
message.what = 1;
handler.sendMessage(message);
// 关闭service}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
outStream.close();
httpClient.getConnectionManager().shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
});
thread.start();
return super.onStartCommand(intent, flags, startId);
}@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}}