- Service download file, add tag:
<service android:name= ". MyService "></service>
To add related permissions:
<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 view) {
TODO auto-generated Method Stub
Intent Intent = new Intent (mainactivity.this,myintentserive.class);
StartService (Intent);
}
});
}
/**
* Use intentserive download picture 1, do not use multithreading 2, automatic stop service
*
* @author LEI
*
*/
public class Myintentserive extends Intentservice {
Private final String Downpath = "Http://www.baidu.com/img/bdlogo.png";
Public myintentserive () {
Super ("Myintentserive");
}
@Override
public void OnCreate () {
TODO auto-generated Method Stub
Super.oncreate ();
}
@Override
protected void Onhandleintent (Intent itent) {
TODO auto-generated Method Stub
HttpClient HttpClient = new Defaulthttpclient ();
HttpPost HttpPost = new HttpPost (Downpath);
HttpResponse HttpResponse = null;
File File = Environment.getexternalstoragedirectory ();
FileOutputStream stream = null;
try {
HttpResponse = Httpclient.execute (HttpPost);
if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {
Byte[] result = Entityutils.tobytearray (HttpResponse
. GetEntity ());
if (Environment.getexternalstoragestate (). Equals (
environment.media_mounted)) {
File NewFile = new file (file, "Abc.png");
stream = new FileOutputStream (newFile);
Stream.Write (result, 0, result.length);
Toast.maketext (myintentserive.this, "Download file complete",
Toast.length_long). Show ();
}
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
if (stream! = null)
try {
Stream.Close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Httpclient.getconnectionmanager (). Shutdown ();
}
}
}
}
intentserive download files (2)