package com.example.androidtest; import java.net.MalformedURLException; import java.net.URL; import android.app.IntentService; import android.content.Intent; import android.util.Log; import android.widget.Toast; /** * 继承IntentService的服务,在任务执行完成后会自行终止。 * 无需手动调用stopSelf()、stopService() * * @author Administrator * */ public class MyIntentService extends IntentService { public MyIntentService() { //必需实现这个类的构造函数 super("MyIntentServiceName"); } // 此方法在工作者线程上执行 @Override protected void onHandleIntent(Intent intent) { try { int result = DownLoadFile(new URL("http://www.amazon.com/somefile.pdf")); Log.d("AndroidTest", "Downloaded " + result + " bytes"); } catch (MalformedURLException e) { Log.d("AndroidTest", e.getMessage()); } } @Override public void onDestroy(){ super.onDestroy(); Toast.makeText(this, "MyIntentService Destroyed", Toast.LENGTH_LONG).show(); } private int DownLoadFile(URL url) { try{ Thread.sleep(5000);//模拟文件下载 }catch(InterruptedException e){ Log.d("AndroidTest", e.getMessage()); } return 100;//文件大小 } }