在服务中执行长时间运行的任务

作者:追风剑情 发布于:2015-7-27 22:28 分类:Android

  1. package com.example.androidtest;
  2.  
  3. import java.net.MalformedURLException;
  4. import java.net.URL;
  5.  
  6. import android.app.Service;
  7. import android.content.Intent;
  8. import android.os.IBinder;
  9. import android.util.Log;
  10. import android.widget.Toast;
  11.  
  12. public class MyService extends Service {
  13.  
  14. @Override
  15. public IBinder onBind(Intent intent) {
  16. // TODO Auto-generated method stub
  17. return null;
  18. }
  19. @Override
  20. public int onStartCommand(Intent intent, int flags, int startId){
  21. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
  22. try {
  23. int result = DownLoadFile(new URL("http://www.amazon.com/somefile.pdf"));
  24. Toast.makeText(getBaseContext(), "Downloaded "+result+" bytes", Toast.LENGTH_LONG).show();
  25. }catch(MalformedURLException e){
  26. Log.d("AndroidTest", e.getMessage());
  27. }
  28. return START_STICKY;
  29. }
  30.  
  31. @Override
  32. public void onDestroy(){
  33. super.onDestroy();
  34. Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  35. }
  36. private int DownLoadFile(URL url)
  37. {
  38. try{
  39. Thread.sleep(5000);//模拟文件下载
  40. }catch(InterruptedException e){
  41. Log.d("AndroidTest", e.getMessage());
  42. }
  43. return 100;//文件大小
  44. }
  45. }

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号