【Android(安卓)开发教程】在服务中执行耗时操作
16lz
2021-01-26
本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/上一节创建的服务实际上并没有做任何有用的事情,这一节将修改一下它,让它去执行一个任务:模拟下载文件。
1. 使用上一节的Services工程,做一点修改。
public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; }@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// We want this service to continue running until it is explicitly// stopped, so return sticky.// Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); try {int result = DownloadFile(new URL("http://www.abcd.com/file.zip"));Toast.makeText(getBaseContext(),"Downloaded " + result + " bytes",Toast.LENGTH_LONG).show(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); }return START_STICKY;} private int DownloadFile(URL url) { try { //---simulate taking some time to download a file--- Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //---return an arbitrary number representing // the size of the file downloaded--- return 100; } @Overridepublic void onDestroy() {super.onDestroy();Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();}}
2. 在模拟器上面进行调试。点击start按钮,开始下载文件。
更多相关文章
- android 从零单排 第一期 按键显示helloworld
- Android(安卓)如何在关于手机界面添加个图片
- git使用小结
- Android第四个功能:文件读取,并且用单元测试进行测试
- Weex系列(序) —— 总要知道原生的一点东东(Android)
- Android中存储目录
- 向sdcard添加文件fail可能的情况
- [2010-12-31 21:33:29 - s] W/ResourceType(27930): Unable to g
- Android(安卓)数据存储之 文件存储