Android Service系列(十八)Background Service Report work status

Report work status

This guide shows you how to report the status of a work request run in a background service to the component that sent the request. This allows you, for example, to report the status of the request in an Activity object's UI. The recommended way to send and receive status is to use a LocalBroadcastManager, which limits broadcast Intentobjects to components in your own app.

翻译:report work status 一般都用LocalBroadcastManager

 

Report status from a JobIntentService

To send the status of a work request in an JobIntentService to other components, first create an Intent that contains the status in its extended data. As an option, you can add an action and data URI to this Intent.

Next, send the Intent by calling LocalBroadcastManager.sendBroadcast(). This sends the Intent to any component in your application that has registered to receive it. To get an instance of LocalBroadcastManager, callgetInstance().

翻译:创建intent,用LocalBroadcastManager来发给应用内的组件

 

public final class Constants {
    ...
    // Defines a custom Intent action
    public static final String BROADCAST_ACTION =
        "com.example.android.threadsample.BROADCAST";
    ...
    // Defines the key for the status "extra" in an Intent
    public static final String EXTENDED_DATA_STATUS =
        "com.example.android.threadsample.STATUS";
    ...
}
public class RSSPullService extends JobIntentService {
...
    /*
     * 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);
...
}

The next step is to handle the incoming broadcast Intent objects in the component that sent the original work request.

翻译:下一步是在组件内处理Intent

 

Receive status broadcasts from a JobIntentService

To receive broadcast Intent objects, use a subclass of BroadcastReceiver. In the subclass, implement theBroadcastReceiver.onReceive() callback method, which LocalBroadcastManager invokes when it receives an IntentLocalBroadcastManager passes the incoming Intent to BroadcastReceiver.onReceive().

// Broadcast receiver for receiving status updates from the IntentService.
private class DownloadStateReceiver extends BroadcastReceiver
{
    // Called when the BroadcastReceiver gets an Intent it's registered to receive
    @Override
    public void onReceive(Context context, Intent intent) {
...
        /*
         * Handle Intents here.
         */
...
    }
}

Once you've defined the BroadcastReceiver, you can define filters for it that match specific actions, categories, and data. To do this, create an IntentFilter. This first snippet shows how to define the filter:

翻译:定义intent filter来匹配action,categories,data

// Class that displays photos
public class DisplayActivity extends FragmentActivity {
    ...
    public void onCreate(Bundle stateBundle) {
        ...
        super.onCreate(stateBundle);
        ...
        // The filter's action is BROADCAST_ACTION
        IntentFilter statusIntentFilter = new IntentFilter(
                Constants.BROADCAST_ACTION);

        // Adds a data filter for the HTTP scheme
        statusIntentFilter.addDataScheme("http");
        ...

To register the BroadcastReceiver and the IntentFilter with the system, get an instance ofLocalBroadcastManager and call its registerReceiver() method. This next snippet shows how to register the BroadcastReceiver and its IntentFilter:

翻译:注册广播以及其IntentFilter

 // Instantiates a new DownloadStateReceiver
        DownloadStateReceiver downloadStateReceiver =
                new DownloadStateReceiver();
        // Registers the DownloadStateReceiver and its intent filters
        LocalBroadcastManager.getInstance(this).registerReceiver(
                downloadStateReceiver,
                statusIntentFilter);

A single BroadcastReceiver can handle more than one type of broadcast Intent object, each with its own action. This feature allows you to run different code for each action, without having to define a separate BroadcastReceiverfor each action. To define another IntentFilter for the same BroadcastReceiver, create the IntentFilter and repeat the call to registerReceiver(). For example:

翻译:一个BroadcastReceiver可以多用

   /*
         * Instantiates a new action filter.
         * No data filter is needed.
         */
        statusIntentFilter = new IntentFilter(Constants.ACTION_ZOOM_IMAGE);
        // Registers the receiver with the new filter
        LocalBroadcastManager.getInstance(this).registerReceiver(
                downloadStateReceiver,
                statusIntentFilter);

 

Sending an broadcast Intent doesn't start or resume an Activity. The BroadcastReceiver for an Activityreceives and processes Intent objects even when your app is in the background, but doesn't force your app to the foreground. If you want to notify the user about an event that happened in the background while your app was not visible, use a NotificationNever start an Activity in response to an incoming broadcast Intent.

翻译:

发广播不会让Activity resume.也不会让app 变成前台应用,如果想提醒用户就发广播吧。

另外,不要在广播里面开启Activity.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,要实现 Service 的后台保活,可以尝试以下几种方法: 1. 使用前台服务(Foreground Service):将 Service 设置为前台服务,给它分配一个与用户正在进行的活动相关联的通知。这样可以提高 Service 的优先级,使其更不容易被系统杀死。示例代码如下: ```java // 在 Service 的 onStartCommand 方法中调用 Notification notification = new Notification.Builder(this, CHANNEL_ID) .setContentTitle("My Service") .setContentText("Running in background") .setSmallIcon(R.drawable.ic_notification) .build(); startForeground(notificationId, notification); ``` 2. 使用 JobScheduler:使用 JobScheduler 调度一个定期执行的任务,确保 Service 定期被唤醒以执行需要的操作。示例代码如下: ```java // 在合适的地方调用 JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); JobInfo jobInfo = new JobInfo.Builder(jobId, new ComponentName(this, MyJobService.class)) .setPeriodic(15 * 60 * 1000) // 每 15 分钟执行一次 .setPersisted(true) // 设备重启后保持任务有效 .build(); jobScheduler.schedule(jobInfo); ``` 3. 使用 AlarmManager:使用 AlarmManager 设置一个定时闹钟,在指定时间间隔内唤醒 Service 执行任务。示例代码如下: ```java // 在合适的地方调用 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, MyService.class); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); long intervalMillis = 15 * 60 * 1000; // 每 15 分钟执行一次 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), intervalMillis, pendingIntent); ``` 请注意,这些方法都不是绝对保证 Service 不会被系统杀死。Android 系统对应用程序的资源使用有一定的限制,以确保设备的性能和电池寿命。使用这些方法可以提高 Service 的存活率,但并不能完全消除被杀死的可能性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值