【Android 开发教程】使用IntentService执行异步操作

本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


之前的几章,我们已经了解了使用startService()去开启一个service,用stopService()去停止一个service。有一点很重要,就是一旦service结束了它要执行的任务,那么,就应该立即关闭service,同事清理一些资源。这就是为什么在任务结束的时候,使用stopSelf()方法。很不幸,大部分开发者经常忘记停止service。这时,IntentService就派用场了,它可以异步地执行任务,当任务结束的时候它自己也会停止。

IntentService的开启和普通的service类似,它能在一个工作线程里面去执行任务,任务结束的时候,IntentService自己停止。

1. 使用之前的工程Services,新建一个类,MyIntentService.java。

2. MyIntentService.java中的代码。

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("IntentService", "Downloaded " + result + " bytes");
            
            //---send a broadcast to inform the activity
            // that the file has been downloaded---
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
            getBaseContext().sendBroadcast(broadcastIntent);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private int DownloadFile(URL url) {
        try {
            //---simulate taking some time to download a file---
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 100;
    }
}
2. 在AndroidManifest.xml中声明。

<service android:name=".MyIntentService" />

3. 修改ServicesActivity.java中的方法。
    public void startService(View view) {
        startService(new Intent(getBaseContext(), MyIntentService.class));
    }
4. 在模拟器上面调试。

5. 5秒后,查看logcat。


首先,新建一个类MyIntentService,继承自IntentService而不是Service。

public class MyIntentService extends IntentService

然后,实现构造器,调用超类的构造器,传入字符串。

    public MyIntentService() {
        super("MyIntentServiceName");
    }

接下来,实现onHandleIntent()方法,这里面的代码在工作线程中执行。

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            int result =
                DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));
            Log.d("IntentService", "Downloaded " + result + " bytes");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
当onHandleIntent()方法里面的代码执行完毕的时候,这个IntentService也同时自动停止。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值