package com.example.androidtest; import java.net.MalformedURLException; import java.net.URL; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId){ Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); try { int result = DownLoadFile(new URL("http://www.amazon.com/somefile.pdf")); Toast.makeText(getBaseContext(), "Downloaded "+result+" bytes", Toast.LENGTH_LONG).show(); }catch(MalformedURLException e){ Log.d("AndroidTest", e.getMessage()); } return START_STICKY; } @Override public void onDestroy(){ super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } private int DownLoadFile(URL url) { try{ Thread.sleep(5000);//模拟文件下载 }catch(InterruptedException e){ Log.d("AndroidTest", e.getMessage()); } return 100;//文件大小 } }