在一个后台服务中运行

原文地址:http://developer.android.com/training/run-background-service/create-service.html

创建一个后台服务

IntentService类提供了一个直接的结构在一个单一的后台线程中执行操作。这使得它能够处理一些耗时的操作而不影响用户体验。此外,IntentService不会影响大多数用户界面的声明周期事件,所以它继续运行的情况下,将关闭一个AsyncTask。

一个IntentService也有一些限制:
1.它不能直接与你的用户界面交互。要把它的执行结果显示在UI界面上们需要把结果发送给Activity。
2.请求会排队。如果当前在IntentService正有一个操作在执行,而你又给他发送了另一个请求,则该请求将会等待,直到第一个请求执行完成。
3.在IntentService执行的操作不能被中断。

然而,在大多数情况下,IntentService是一个较好的运行简单后台操作的方式。

创建一个IntentService

为了给你的应用创建一个IntentService组件,你需要定义一个继承于IntentService的类,并且要覆盖onHandleIntent()方法:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
public class RSSPullService extends IntentService {
    @Override
    protected void onHandleIntent(Intent workIntent) {
         // Gets data from the incoming Intent
         String dataString = workIntent.getDataString();
         ...
         // Do work here, based on the contents of dataString
         ...
    }
}

注意在该组件中的其他回调函数,例如onStartCommand()会自动被IntentService调用。在一个IntentService钟,应该避免覆盖这些回调函数。

在Manifest中定义IntentService

一个IntentService也需要在manifest中定义,例如:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
< application
         android:icon = "@drawable/icon"
         android:label = "@string/app_name" >
         ...
         <!--
             Because android:exported is set to "false",
             the service is only available to this app.
         -->
         < service
             android:name = ".RSSPullService"
             android:exported = "false" />
         ...
    < application />

android:name属性指明了IntentService的名称。


注意<service>元素没有包含一个intent filter。如果Activity向IntentService发送任务请求会使用一个特定的Intent,所以不需要filter。这意味着只有在该应用和其他具有相同用户名的程序能够访问该service。

原文地址:http://developer.android.com/training/run-background-service/send-request.html

向后台服务发送任务请求

向IntentService创建并发送任务请求

为了向一个Intentservice创建并发送任务请求,需要创建一个明确的Intent,并添加处理数据,通过调用startService()函数来向Intentservice发送任务。
1.创建Intent

?
代码片段,双击复制
01
02
03
04
05
06
07
/*
  * Creates a new Intent to start the RSSPullService
  * IntentService. Passes a URI in the
  * Intent's "data" field.
  */
mServiceIntent = new Intent(getActivity(), RSSPullService. class );
mServiceIntent.setData(Uri.parse(dataUrl));

2.调用startService()
?
代码片段,双击复制
01
02
// Starts the IntentService
getActivity().startService(mServiceIntent);


注意你能够从一个Activity或是Fragment发送任务请求。一旦你调用了startservice(),IntentService将会执行在onHandleIntent中定义的工作,完成后会自己停止。

原文地址:http://developer.android.com/training/run-background-service/report-status.html

报告任务状态

从一个IntentService中报告状态

为了在一个Intentservice中向其他组件发送任务请求的状态,首先要创建一个包含数据的Intent。作为一个选择,你可以把action和数据的URI添加到Intent。
接下来,通过调用LocalBroadcastManager.sendBroadcast()来发送Intent。

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 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);
...
}


接受从IntentService中发出的状态数据

可以定义一个BroadcastReceiver的子类来接受数据。
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
// 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
    @
    public void onReceive(Context context, Intent intent) {
...
         /*
          * Handle Intents here.
          */
...
    }
}

也可以给该BroadcastReceiver添加filters:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
// 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 mStatusIntentFilter = new IntentFilter(
                Constants.BROADCAST_ACTION);
     
         // Adds a data filter for the HTTP scheme
         mStatusIntentFilter.addDataScheme( "http" );
         ...

接下来要在系统中注册该BroadcastReceiver:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
// Instantiates a new DownloadStateReceiver
         DownloadStateReceiver mDownloadStateReceiver =
                new DownloadStateReceiver();
         // Registers the DownloadStateReceiver and its intent filters
         LocalBroadcastManager.getInstance( this ).registerReceiver(
                mDownloadStateReceiver,
                mStatusIntentFilter);
         ...

一个BroadcastReceiver能够处理不同类型的广播Intent,每一个Intent对应其自己的action。这样可以在一个BroadcastReceiver中处理不同action的Intent。添加其他的IntentFilter:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
/*
          * 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(getActivity()).registerReceiver(
                mDownloadStateReceiver,
statusIntentFilter);

一个Activity的BroadcastReceiver能够接受处理Intent,即使你的应用在后台。当后台发生一个事件你想要通知用户是,不要调出app,用Notification代替。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值