Android Best Practices 主要内容

本文介绍了Android中使用IntentService进行后台服务操作的最佳实践。通过继承IntentService并重写onHandleIntent方法,开发者可以在单独的工作线程中执行任务。IntentService会自动管理请求队列并逐一处理,任务完成后自动停止服务。同时,文章提到了如何向服务发送工作请求以及如何利用LocalBroadcastManager报告工作状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文用途:搜索、跟踪阅读进度、概括官方文档内容。

忽略介绍、原理、优缺点等内容。

Running in a Background Service

最有用: IntentService

流程:创建IntentService, 发送请求, 接收结果

Creating a Background Service          原文链接

1. 继承 IntentService

2.override onHandleIntent(Intent workIntent), 不用override其他callbacks 。执行任务的代码就在onHandleIntent()中。

3、添加<service>至<application>

IntentService内部有一个线程、IntentService可以相应多个请求(有队列,逐个完成)、执行完后自动停止。

Sending Work Requests to the Background Service       原文链接

1、创建explicit intent    2、startService()

Reporting Work Status

原文链接   涉及LocalBroadcastManager类

1)IntentService发送结果:1、创建Intent(可自行指定action, data uri)   2、用LocalBroadcastManager发送该intent( sendBroadcast() )

public class RSSPullService extends IntentService {
...
    /*
     * Creates a new Intent containing a Uri object
     * BROADCAST_ACTION is a custom Intent action
     */
    Intent localIntent =
            new Intent(Constants.BROADCAST_ACTION)
            // Puts the status into the Intent
            .putExtra(Constants.EXTENDED_DATA_STATUS, status);
    // Broadcasts the Intent to receivers in this app.
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
...
}
2)接收结果:1、继承BroadcastReceiver  2、override onReceive()  3、新建 IntentFilter(可多个,不继承)   4、注册(下面)

// Broadcast receiver for receiving status updates from the IntentService
private class ResponseReceiver extends BroadcastReceiver
{
    // Prevents instantiation
    private DownloadStateReceiver() { }
    // Called when the BroadcastReceiver gets an Intent it's registered to receive
    @Override
    public void onReceive(Context context, Intent intent) {
...
        //Handle Intents here.
...
    }
}
4、注册receiver和intent filter:

        // Instantiates a new DownloadStateReceiver
        DownloadStateReceiver mDownloadStateReceiver =
                new DownloadStateReceiver();
        // Registers the DownloadStateReceiver and its intent filters
        LocalBroadcastManager.getInstance(this).registerReceiver(
                mDownloadStateReceiver,
                mStatusIntentFilter);
        ...
注:receiver和intent filter有多种组合,多次调用 registerReceiver() 即可(每次不同组合)。
接收到intent后,不要start activity。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值