你所不知道的IntentService

来源:互联网 发布:淘宝一千零一夜在哪 编辑:程序博客网 时间:2024/05/22 03:06

 

  今天无意中接触到IntenService。不知其意,于是,百度之。

  IntentService 和Service是经常作为比较的对象,不只是是因为有公共的名字“Service”,而且还因为IntentService是继承自Service的。那么,两者究竟有什么样的区别和联系呢。

  Service的话,作为android开发者都比较熟悉,它主要用在后台运行。例如:使用UC浏览器上网的时候,天天动听播放着音乐。那么IntentService继承自Service的话,这一作用  也是具备的。

  Service 的话在主线程中,所以它不能处理耗时太多的操作,如果需要处理耗时太多的操作的话,那么则需要另外开发线程进行处理;比如说操作数据库、连接网络等。

 而IntentService的话,它本身对于数据的处理另外开辟了线程进行处理,所以我的理解是它对Service做了一个很好的封装。它的实现机制是首先,创建一个消息队列,如果有任务需要进行处理的话,那么首先将任务加载到消息队列中,而真正处理消息的则在WrokThread线程中。通过先来先服务的方式对消息进行处理。

以下是两者关系示意图:

 

                                                                      


两者的实现方式大体差不多,细节上有所不同,先来看看IntentService

我们需要进行耗时操作处理的话。继承IntentService。然后重写onHandleIntent 方法。我们的耗时处理实现写于此方法即可。

public class MyIntentService extends IntentService {public MyIntentService() {super("android");}@Overrideprotected void onHandleIntent(Intent intent) {System.out.println("begin");try {Thread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end");}}

接着我们再来看Servie

public class MyService extends Service {public void onCreate() {super.onCreate();System.out.println("create");}public void onStart(Intent intent, int startId) {super.onStart(intent, startId);System.out.println("begin");try {Thread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end");}@Overridepublic IBinder onBind(Intent intent) {return null;}}

我们在onStart方法中进行处理。但是我们不能处理耗时比较长的操作。如果需要的话,我们必须另起线程进行处理。

再说一句,上述两者都是通过startService方式启动的。

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startService(new Intent(this, MyService.class));startService(new Intent(this, MyIntentService.class));startService(new Intent(this, MyIntentService.class));}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.// getMenuInflater().inflate(R.menu.main, menu);return true;}}


好了,现在我们就知道了IntentService的作用了,它用于后台处理耗时的操作,诸如联网,操作数据库等。





原创粉丝点击