android基础IntentService的使用

移动开发 Android
前台服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收。我们通过一个具体的案例来说明start与bind方式的service服务的生命周期的介绍。

服务的简单说明

一、 前台服务与IntentService:

前台服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收
 

service服务测试的准备代码

我们通过一个具体的案例来说明start与bind方式的service服务的生命周期的介绍。项目结果如下:

一、 在MainActivity.java中做一些初始化工作,如下代码:

  1. private final static String TAG = "MyIntentService";  
  2. private MyIntentService.MyBinder binder;  
  3.  
  4. private ServiceConnection connection = new ServiceConnection() {  
  5.     @Override  
  6.     public void onServiceConnected(ComponentName name, IBinder service) {  
  7.         binder = (MyIntentService.MyBinder) service;  
  8.         binder.sayHello(name.getClassName());  
  9.     }  
  10.  
  11.     @Override  
  12.     public void onServiceDisconnected(ComponentName name) {  
  13.         Log.i(TAG, "service disconnect: " + name.getClassName());  
  14.     }  
  15. };  
  16.  
  17. @Override  
  18. protected void onCreate(Bundle savedInstanceState) {  
  19.     super.onCreate(savedInstanceState);  
  20.     setContentView(R.layout.activity_main);  

二、 创建一个简单的IntentService服务类:MyIntentService

  1. package com.example.linux.intentservicetest;  
  2.  
  3. import android.app.IntentService;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.util.Log;  
  8.  
  9. public class MyIntentService extends IntentService {  
  10.     private final static String TAG = "MyIntentService";  
  11.     private MyBinder myBinder = new MyBinder();  
  12.  
  13.     class MyBinder extends Binder {  
  14.         public void sayHello(String name) {  
  15.             Log.i(TAG, "say hello method: " + name);  
  16.         }  
  17.  
  18.         public void sayWorld(String name) {  
  19.             Log.i(TAG, "say world method: " + name);  
  20.         }  
  21.     }  
  22.  
  23.     @Override  
  24.     public IBinder onBind(Intent intent) {  
  25.         return myBinder;  
  26.     }  
  27.  
  28.     public MyIntentService() {  
  29.         super("MyIntentService");  
  30.         Log.i(TAG, "myintent service constructor.");  
  31.     }  
  32.  
  33.     @Override  
  34.     public void onCreate() {  
  35.         Log.i(TAG, "on create.");  
  36.         super.onCreate();  
  37.     }  
  38.  
  39.     @Override  
  40.     protected void onHandleIntent(Intent intent) {  
  41.         Log.i(TAG, "handle intent: " + intent.getStringExtra("username") + ", thread: " + Thread.currentThread());  
  42.     }  
  43.  
  44.     @Override  
  45.     public void onDestroy() {  
  46.         super.onDestroy();  
  47.         Log.i(TAG, "on destroy.");  
  48.     }  
  49.  
  50.     @Override  
  51.     public int onStartCommand(Intent intent, int flags, int startId) {  
  52.         Log.i(TAG, "on start command.");  
  53.         return super.onStartCommand(intent, flags, startId);  
  54.     }  
  55.  
  56.     @Override  
  57.     public boolean onUnbind(Intent intent) {  
  58.         //默认返回false  
  59.         String username = intent.getStringExtra("username");  
  60.         Log.i(TAG, "on unbind: " + super.onUnbind(intent) + ", username: " + username);  
  61.         return true;  
  62.     }  
  63.  
  64.     @Override  
  65.     public void onRebind(Intent intent) {  
  66.         Log.i(TAG, "on rebind");  
  67.         super.onRebind(intent);  
  68.     }  

三、 创建一个简单的前台服务类:FrontService

  1. package com.example.linux.intentservicetest;  
  2.  
  3. import android.app.Notification;  
  4. import android.app.PendingIntent;  
  5. import android.app.Service;  
  6. import android.content.Intent;  
  7. import android.os.IBinder;  
  8. import android.util.Log;  
  9.  
  10. public class FrontService extends Service {  
  11.     private final static String TAG = "MyIntentService";  
  12.     public FrontService() {  
  13.         Log.i(TAG, "front service constructor");  
  14.     }  
  15.  
  16.     @Override  
  17.     public IBinder onBind(Intent intent) {  
  18.         return null;  
  19.     }  
  20.  
  21.     @Override  
  22.     public void onCreate() {  
  23.         super.onCreate();  
  24.         Notification.Builder builder = new Notification.Builder(this);  
  25.         Intent intent = new Intent(this, MainActivity.class);  
  26.         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,  
  27.                 PendingIntent.FLAG_CANCEL_CURRENT);  
  28.  
  29.         builder.setSmallIcon(R.mipmap.ic_launcher).setTicker("ticker");  
  30.         builder.setWhen(System.currentTimeMillis()).setAutoCancel(true);  
  31.         builder.setContentTitle("content title").setContentText("content text");  
  32.         builder.setContentIntent(pendingIntent);  
  33.  
  34.         Notification notify = builder.getNotification();  
  35.  
  36.         notify.defaults = Notification.DEFAULT_ALL;  
  37.         startForeground(10, notify);  
  38.     }  

四、 在AndroidManifest.xml中注册服务与活动

  1. <activity android:name=".MainActivity">  
  2.     <intent-filter>  
  3.         <action android:name="android.intent.action.MAIN" />  
  4.         <category android:name="android.intent.category.LAUNCHER" />  
  5.     </intent-filter>  
  6. </activity>  
  7.  
  8. <service  
  9.     android:name=".MyIntentService" 
  10.     android:exported="false">  
  11. </service>  
  12. <service  
  13.     android:name=".FrontService" 
  14.     android:enabled="true" 
  15.     android:exported="true">  
  16. </service> 

Intent服务的使用

一、 在MainActivity中创建方法,启动停止服务:

  1. // 开启服务  
  2. public void startService(View view) {  
  3.     Intent intent = new Intent();  
  4.     intent.putExtra("username""linux");  
  5.     intent.setClass(MainActivity.this, MyIntentService.class);  
  6.     startService(intent);  
  7. }  
  8.  
  9. // 停止服务  
  10. public void stopService(View view) {  
  11.     Intent intent = new Intent();  
  12.     intent.setClass(MainActivity.this, MyIntentService.class);  
  13.     stopService(intent);  

二、 在MainActivity中创建方法,绑定解绑服务:

  1. // 绑定服务  
  2. public void bindService(View view) {  
  3.     Intent intent = new Intent();  
  4.     intent.setClass(MainActivity.this, MyIntentService.class);  
  5.     intent.putExtra("username""linux");  
  6.     boolean isBind = bindService(intent, connection, Context.BIND_AUTO_CREATE);  
  7.     Log.i(TAG, "bind service: " + isBind);  
  8. }  
  9.  
  10. // 解绑服务  
  11. public void unbindService(View view) {  
  12.     Intent intent = new Intent();  
  13.     intent.setClass(MainActivity.this, MyIntentService.class);  
  14.     unbindService(connection);  

三、 运行结果

点击start:
 

  1. 03-25 08:01:53.460 8389-8389/? I/MyIntentService: myintent service constructor.  
  2. 03-25 08:01:53.460 8389-8389/? I/MyIntentService: on create.  
  3. 03-25 08:01:53.475 8389-8389/? I/MyIntentService: on start command.  
  4. 03-25 08:01:53.477 8389-8727/? I/MyIntentService: handle intent: linux, thread: Thread[IntentService[MyIntentService],5,main]  
  5. 03-25 08:01:53.478 8389-8389/? I/MyIntentService: on destroy. 


点击stop:无输出
点击bind:
 

  1. 03-25 08:02:25.421 8389-8389/? I/MyIntentService: bind service: true 
  2. 03-25 08:02:25.422 8389-8389/? I/MyIntentService: myintent service constructor.  
  3. 03-25 08:02:25.422 8389-8389/? I/MyIntentService: on create.  
  4. 03-25 08:02:25.432 8389-8389/? I/MyIntentService: say hello method: com.example.linux.intentservicetest.MyIntentService 

点击unbind:

  1. 03-25 08:02:28.486 8389-8389/? I/MyIntentService: on unbind: false, username: linux  
  2. 03-25 08:02:28.490 8389-8389/? I/MyIntentService: on destroy. 

前台服务的使用

一、 在MainActivity中创建方法,启动前台服务:

  1. // 前台服务的使用  
  2. public void frontService(View view) {  
  3.     Intent intent = new Intent();  
  4.     intent.setClass(MainActivity.this, FrontService.class);  
  5.     startService(intent);  

二、 运行结果: 在手机的通知栏中

 

IntentService的原理分析

一、 intentService是继承Service的抽象方法

  1. public abstract class IntentService extends Service  

二、 intentService包含的一些字段引用如下

  1. private volatile Looper mServiceLooper;  
  2. private volatile ServiceHandler mServiceHandler;  
  3. private String mName;  
  4. private boolean mRedelivery;  
  5.  
  6. private final class ServiceHandler extends Handler {  
  7.     public ServiceHandler(Looper looper) {  
  8.         super(looper);  
  9.     }  
  10.  
  11.     @Override  
  12.     public void handleMessage(Message msg) {  
  13.         onHandleIntent((Intent)msg.obj);  
  14.         stopSelf(msg.arg1);  
  15.     }  

二、 和service一样在启动的时候,首先是执行构造方法,接着是onCreate方法,然后是onStartCommand方法,在onStartCommand中执行了onStart方法(执行流程在android基础---->service的生命周期讲过):

onCreate方法,开启了一个线程,并且得到Looper与初始化了一个Handler
 

  1. @Override  
  2. public void onCreate() {  
  3.     // TODO: It would be nice to have an option to hold a partial wakelock  
  4.     // during processing, and to have a static startService(Context, Intent)  
  5.     // method that would launch the service & hand off a wakelock.  
  6.  
  7.     super.onCreate();  
  8.     HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");  
  9.     thread.start();  
  10.  
  11.     mServiceLooper = thread.getLooper();  
  12.     mServiceHandler = new ServiceHandler(mServiceLooper);  

onStart方法,用上述的Handler发送信息

  1. @Override  
  2. public void onStart(Intent intent, int startId) {  
  3.     Message msg = mServiceHandler.obtainMessage();  
  4.     msg.arg1 = startId;  
  5.     msg.obj = intent;  
  6.     mServiceHandler.sendMessage(msg);  

onStartCommand方法,调用onStart方法,发送信息

  1. @Override  
  2. public int onStartCommand(Intent intent, int flags, int startId) {  
  3.     onStart(intent, startId);  
  4.     return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;  
  5. }  
  6.  


***上述的Handler得到信息,调用handleMessage方法,其中有stopSelf(msg.arg1)方法,停止了服务:

 

三、 这里附上service类的两个方法,源代码是android6.0的

在Service中的onStart方法已经被废弃了:
 

  1. /**  
  2.  * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.  
  3. */ 
  4. @Deprecated  
  5. public void onStart(Intent intent, int startId) {  

在onStartCommand的方法中

  1. public int onStartCommand(Intent intent, int flags, int startId) {  
  2.     onStart(intent, startId);  
  3.     return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;  
  4. }  
  5.  

 

责任编辑:陈琳 来源: huhx的博客
相关推荐

2016-11-14 19:15:37

Android

2023-12-06 08:26:19

Service数据库

2011-06-02 10:24:48

Android SQLite

2009-06-30 11:33:55

脚本JSP教程

2010-06-28 15:31:22

2016-01-26 10:51:50

2016-05-10 11:22:13

软件定义IT基础

2011-06-01 13:22:25

Android Alarm

2011-05-27 11:34:53

Android preference

2010-02-03 15:59:08

Android组件

2014-07-28 14:43:14

git开源

2023-07-04 08:28:27

2011-06-16 11:01:56

PHP继承

2015-01-12 13:48:55

Android应用组件

2010-01-26 17:42:14

Android浮点

2011-05-04 10:29:30

投影机

2014-07-17 11:36:27

Android Stu使用教程

2017-06-12 18:48:00

Android性能分析工具

2013-03-28 16:31:48

AIDL的简单使用Android中AID

2014-12-31 14:27:19

ToastLogLSharePrefe
点赞
收藏

51CTO技术栈公众号