Android Service学习

部分内容参考于

http://liangruijun.blog.51cto.com/3061169/647804

http://android.blog.51cto.com/268543/527314

一.Service的简介

Service是Android系统中的四大组件之一,不和用户交互应用组件。每个Service必须在manifest中 通过<service>来声明。可以通过context.startservice和context.bindserverice来启动。

Service和其他的应用组件一样,运行在进程的主线程中。这就是说如果service需要很 耗时或者阻塞的操作,需要另外开线程来执行耗时的操作,例如:我们不能去执行下载的任务。


二、生命周期
    Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。


三.Service 的启动方式

   而启动service,根据onStartCommand的返回值不同,有两个附加的模式:
    1. START_STICKY 用于显示启动和停止service。
    2. START_NOT_STICKY或START_REDELIVER_INTENT用于有命令需要处理时才运行的模式。

Context.startService()方式: 
启动时,startService –> onCreate() –> onStart()
停止时,stopService –> onDestroy()
如果调用者直接退出而没有停止Service,则Service 会一直在后台运行
 
使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。
 如果打算采用Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。
 如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。
 采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。

bindService()方式
使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止,大有“不求同时生,必须同时死”的特点。
  onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者与服务解除,服务结束时会调用onDestroy()方法。


拥有service的进程具有较高的优先级

    官方文档告诉我们,Android系统会尽量保持拥有service的进程运行,只要在该service已经被启动(start)或者客户端连接(bindService)到它。当内存不足时,需要保持,拥有service的进程具有较高的优先级。

本地service

1.不需和Activity交互的本地服务

public class LocalService extends Service { 

        private static final String TAG = "LocalService"; 

        @Override 

        public IBinder onBind(Intent intent) { 

                Log.i(TAG, "onBind"); 

                return null; 

        } 

        @Override 

        public void onCreate() { 

                Log.i(TAG, "onCreate"); 

                super.onCreate(); 

        } 

        @Override 

        public void onDestroy() { 

                Log.i(TAG, "onDestroy"); 

                super.onDestroy(); 

        } 

        @Override 

        public void onStart(Intent intent, int startId) { 

                Log.i(TAG, "onStart"); 

                super.onStart(intent, startId); 

        } 

}



public class ServiceActivity extends Activity { 
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
                super.onCreate(savedInstanceState); 
                setContentView(R.layout.servicedemo); 
                ((Button) findViewById(R.id.startLocalService)).setOnClickListener( 
                                new View.OnClickListener(){ 
                                        @Override 
                                        public void onClick(View view) { 
                                                // TODO Auto-generated method stub 
                                               startService(new Intent("com.demo.SERVICE_DEMO")); 
                                        }  
                                }); 

                ((Button) findViewById(R.id.stopLocalService)).setOnClickListener( 
                                new View.OnClickListener(){ 
                                        @Override 
                                        public void onClick(View view) { 
                                                // TODO Auto-generated method stub 
                                                stopService(new Intent("com.demo.SERVICE_DEMO")); 
                                        } 
                                }); 
        } 

}

在AndroidManifest.xml添加:

<service android:name=".LocalService"> 
        <intent-filter> 
                <action android:name="com.demo.SERVICE_DEMO" /> 
                <category android:name="android.intent.category.default" /> 
        </intent-filter> 
</service>


对于这类不需和Activity交互的本地服务,是使用startService/stopService的最好例子。
    运行时可以发现第一次startService时,会调用onCreate和onStart,在没有stopService前,无论点击多少次startService,都只会调用onStart。而stopService时调用onDestroy。再次点击stopService,会发现不会进入service的生命周期的,即不会再调用onCreate,onStart和onDestroy。 而onBind在startService/stopService中没有调用。

2.本地服务和Activity交互

对于这种case,官方的sample(APIDemo\app.LocalService)是最好的例子:
/** 
* This is an example of implementing an application service that runs locally 
* in the same process as the application.    The {@link LocalServiceController} 
* and {@link LocalServiceBinding} classes show how to interact with the 
* service. 

* <p>Notice the use of the {@link NotificationManager} when interesting things 
* happen in the service.    This is generally how background services should 
* interact with the user, rather than doing something more disruptive such as 
* calling startActivity(). 
*/
 
public  class LocalService  extends Service { 
         private NotificationManager mNM; 

         /** 
         * Class for clients to access.    Because we know this service always 
         * runs in the same process as its clients, we don't need to deal with 
         * IPC. 
         */
 
        public class LocalBinder extends Binder { 
                LocalService getService() { 
                        return LocalService.this; 
                } 
        } 
         
        @Override 
         public  void onCreate() { 
                mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 

                 // Display a notification about us starting.    We put an icon in the status bar. 
                showNotification(); 
        } 

        @Override 
         public  int onStartCommand(Intent intent,  int flags,  int startId) { 
                Log.i( "LocalService""Received start id " + startId +  ": " + intent); 
                 // We want this service to continue running until it is explicitly 
                 // stopped, so return sticky. 
                 return START_STICKY; 
        } 

        @Override 
         public  void onDestroy() { 
                 // Cancel the persistent notification. 
                mNM.cancel(R.string.local_service_started); 

                 // Tell the user we stopped. 
                Toast.makeText( this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show(); 
        } 

        @Override 
        public IBinder onBind(Intent intent) { 
             return mBinder;
        } 

         // This is the object that receives interactions from clients.    See 
         // RemoteService for a more complete example. 
        private final IBinder mBinder = new LocalBinder(); 

         /** 
         * Show a notification while this service is running. 
         */
 
         private  void showNotification() { 
                 // In this sample, we'll use the same text for the ticker and the expanded notification 
                CharSequence text = getText(R.string.local_service_started); 

                 // Set the icon, scrolling text and timestamp 
                Notification notification =  new Notification(R.drawable.stat_sample, text, 
                                System.currentTimeMillis()); 

                 // The PendingIntent to launch our activity if the user selects this notification 
                PendingIntent contentIntent = PendingIntent.getActivity( this, 0, 
                                 new Intent( this, LocalServiceController. class), 0); 

                 // Set the info for the views that show in the notification panel. 
                notification.setLatestEventInfo( this, getText(R.string.local_service_label), 
                                             text, contentIntent); 

                 // Send the notification. 
                 // We use a layout id because it is a unique number.    We use it later to cancel. 
                mNM.notify(R.string.local_service_started, notification); 
        } 
}
   这里可以发现onBind需要返回一个IBinder对象。也就是说和上一例子LocalService不同的是,
1. 添加了一个public内部类继承Binder,并添加getService方法来返回当前的Service对象;
2. 新建一个IBinder对象——new那个Binder内部类;
3. onBind方法返还那个IBinder对象。

Activity:
/** 
* <p>Example of binding and unbinding to the {@link LocalService}. 
* This demonstrates the implementation of a service which the client will 
* bind to, receiving an object through which it can communicate with the service.</p> 
*/
 
public  class LocalServiceBinding  extends Activity { 
         private  boolean mIsBound; 
         private LocalService mBoundService; 

        @Override 
         protected  void onCreate(Bundle savedInstanceState) { 
                 super.onCreate(savedInstanceState); 

                setContentView(R.layout.local_service_binding); 

                 // Watch for button clicks. 
                Button button = (Button)findViewById(R.id.bind); 
                button.setOnClickListener(mBindListener); 
                button = (Button)findViewById(R.id.unbind); 
                button.setOnClickListener(mUnbindListener); 
        } 

        private ServiceConnection mConnection = new ServiceConnection() { 
                public void onServiceConnected(ComponentName className, IBinder service) { 
                         // This is called when the connection with the service has been 
                         // established, giving us the service object we can use to 
                         // interact with the service.    Because we have bound to a explicit 
                         // service that we know is running in our own process, we can 
                         // cast its IBinder to a concrete class and directly access it. 
                        mBoundService = ((LocalService.LocalBinder)service).getService();  
                         
                         // Tell the user about this for our demo. 
                        Toast.makeText(LocalServiceBinding. this, R.string.local_service_connected, 
                                        Toast.LENGTH_SHORT).show(); 
                } 

                public void onServiceDisconnected(ComponentName className) { 
                         // This is called when the connection with the service has been 
                         // unexpectedly disconnected -- that is, its process crashed. 
                         // Because it is running in our same process, we should never 
                         // see this happen. 
                        mBoundService =  null
                        Toast.makeText(LocalServiceBinding. this, R.string.local_service_disconnected, 
                                        Toast.LENGTH_SHORT).show(); 
                } 
        }; 

         private OnClickListener mBindListener =  new OnClickListener() { 
                 public  void onClick(View v) { 
                         // Establish a connection with the service.    We use an explicit 
                         // class name because we want a specific service implementation that 
                         // we know will be running in our own process (and thus won't be 
                         // supporting component replacement by other applications). 
                         bindService( new Intent(LocalServiceBinding. this,    
                                        LocalService. class),  mConnection, Context.BIND_AUTO_CREATE); 
                        mIsBound =  true
                } 
        }; 

         private OnClickListener mUnbindListener =  new OnClickListener() { 
                 public  void onClick(View v) { 
                         if (mIsBound) { 
                                 // Detach our existing connection. 
                                 unbindService( mConnection); 
                                mIsBound =  false
                        } 
                } 
        }; 
}
    明显看出这里面添加了一个名为ServiceConnection类,并实现了onServiceConnected(从IBinder获取Service对象)和onServiceDisconnected(set Service to null)。
    而bindService和unbindService方法都是操作这个ServiceConnection对象的。

AndroidManifest.xml里添加:
< service  android:name =".app.LocalService"  /> 

< activity  android:name =".app.LocalServiceBinding"  android:label ="@string/activity_local_service_binding" > 
      < intent-filter > 
           < action  android:name ="android.intent.action.MAIN"  /> 
           < category  android:name ="android.intent.category.SAMPLE_CODE"  /> 
      </ intent-filter > 
</ activity >
这里没什么特别的,因为service没有需要什么特别的action,所以只是声明service而已,而activity和普通的没差别。

运行时,发现调用次序是这样的:
bindService:
1.LocalService : onCreate
2.LocalService : onBind
3.Activity: onServiceConnected

unbindService: 只是调用onDestroy

可见,onStart是不会被调用的,而onServiceDisconnected没有调用的原因在上面代码的注释有说明。
 总结:

      1. startService()的目的是回调onStart()方法,onCreate() 方法是在Service不存在的时候调用的,如果Service存在(例如之前调用了bindService,那么Service的onCreate方法已经调用了)那么startService()将跳过onCreate() 方法。

      2.  bindService()目的是回调onBind()方法,它的作用是在Service和调用者之间建立一个桥梁,并不负责更多的工作(例如一个Service需要连接服务器的操作),一般使用bindService来绑定到一个现有的Service(即通过StartService启动的服务)。

      由于Service 的onStart()方法只有在startService()启动Service的情况下才调用,故使用onStart()的时候要注意这点。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值