The code is as follows:
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";//Download link
@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
You cannot use the network directly using the HTTP protocol, service is in the UI thread, you need to create a thread, separate from the main thread
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 (), "File Download Complete", 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;
Get the SD card directory
File File = Environment.getexternalstoragedirectory ();
FileOutputStream outstream = null;
try {
HttpResponse = Httpclient.execute (HttpPost);
if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {
Byte[] result = Entityutils.tobytearray (HttpResponse
. GetEntity ());
Determine if the SDK card is mounted and can store data
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);
Close 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;
}
}