Seraph_浮生

导航

 

Service是四大组件之一:主要用于在后台执行一些比较耗时的操作,如音乐播放,数据下载等...
Service分为两种:startService和bindService
 
下面分别介绍两种Service:
1、Started:
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
 
解释:这种Service通过调用startService()方法启动,一旦启动,调用者和服务之间没有任何关系,即使调用者不存在了,服务仍然会执行
2、Bound:
A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed
 
解释:这种Service通过调用bindService启动,这种Service可以和调用者进行交互,一旦调用者调用unbindService,那么该服务就会停止
 
 
下面简单的介绍第一种Service的使用:
使用第一种Service可以继承IntentService,也可以继承Service,代码如下:

public class MyIntentService extends IntentService 
{ 
    private int count=0; 
 
    public MyIntentService() 
    { 
        super("intentService"); 
        // TODO Auto-generated constructor stub 
    } 
 
    @Override 
    protected void onHandleIntent(Intent intent) 
    { 
        // TODO Auto-generated method stub 
        System.out.println("onHandleIntent 执行"+count++); 
        try 
        { 
            Thread.sleep(1000); 
        } catch (InterruptedException e) 
        { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        System.out.println("Service Thread=====>"+Thread.currentThread().getId()); 
 
    } 
 
} 

 

public class MyService extends Service 
{ 
     
     
    private int count=0; 
 
    @Override 
    public IBinder onBind(Intent intent) 
    { 
        // TODO Auto-generated method stub 
        return null; 
    } 
 
    @Override 
    public void onCreate() 
    { 
        // TODO Auto-generated method stub 
        super.onCreate(); 
        System.out.println("Service Thread=======>"+Thread.currentThread().getId()); 
        System.out.println("onCreate()"); 
    } 
 
    @Override 
    public void onDestroy() 
    { 
        // TODO Auto-generated method stub 
        super.onDestroy(); 
        System.out.println("onDestroy()"); 
    } 
 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
        // TODO Auto-generated method stub 
         
        new Thread() 
        { 
 
            @Override 
            public void run() 
            { 
                // TODO Auto-generated method stub 
                System.out.println("onStartCommand()"+count++); 
                try 
                { 
                    Thread.sleep(2000); 
                } catch (InterruptedException e) 
                { 
                    // TODO Auto-generated catch block 
                    e.printStackTrace(); 
                } 
                System.out.println("Service Thread=========>"+Thread.currentThread().getId()); 
                 
            } 
             
        }.start(); 
         
        return Service.START_STICKY; 
         
    } 
     
     
 
} 

 

当我们使用第一种方式时,只需要改写protected void onHandleIntent(Intent intent),其他的生命周期函数父类已经帮我们完成好了,在这里要说明一点:
Service是和调用者运行在同一个线程里面的,但是IntentService中,已经帮我们创建了一个线程,并且该线程有一个消息队列,当我们多次启动同一个线程时,将这多次启动放入消息队列中,依次执行。
启动第一种Service的运行结果为(启动三次,发现线程id是同一个)
 

如果使用第二种方式,那么最好自己创建一个线程,不然可能会出现ANR异常。(3次启动服务)

仔细观察:OnCreate只执行一次,OnStartCommand执行了3次,
 
下面用普通的Service来模拟IntentService

public class MyService2 extends Service 
{ 
    private Looper looper; 
    private HandlerThread thread; 
    private Handler handle; 
     
 
    @Override 
    public IBinder onBind(Intent intent) 
    { 
        // TODO Auto-generated method stub 
        return null; 
    } 
 
    @Override 
    public void onCreate() 
    { 
        // TODO Auto-generated method stub 
        super.onCreate(); 
        thread=new HandlerThread("handlerthread"); 
        thread.start(); 
        looper=thread.getLooper(); 
        handle=new Handler(looper) 
        { 
            @Override 
            public void handleMessage(Message msg) 
            { 
                // TODO Auto-generated method stub 
                 
                System.out.println("执行。。。"); 
                try 
                { 
                    Thread.sleep(1000); 
                } catch (InterruptedException e) 
                { 
                    // TODO Auto-generated catch block 
                    e.printStackTrace(); 
                } 
                System.out.println("handler Thread====>"+Thread.currentThread().getId()); 
                stopSelf(msg.arg1); 
            } 
        }; 
         
    } 
 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
        // TODO Auto-generated method stub 
        Message msg=handle.obtainMessage(); 
        msg.arg1=startId; 
        msg.sendToTarget(); 
        return super.onStartCommand(intent, flags, startId); 
    } 
 
     
     
 
} 

 总结一下第一种方式Service的生命周期:
1、当服务第一次启动时,首先执行onCreate,然后onStartCommand,如果服务停止 则执行onDestroy
2、当服务多次启动,则只会执行onStartCommand,不会执行onCreate,停止执行onDestroy
 
至于第二种Servive,我就不再详细叙述了,我只把结论拿出来,如果有不懂的,欢迎留言:
1、当第一次启动时,首先执行OnCreate,然后执行onBind,最后执行onDestroy
2、当多次启动服务时,onCreate和onBind都不会执行,最后执行onDestroy

 

原文地址:http://www.2cto.com/kf/201209/154043.html

posted on 2013-04-06 11:26  Seraph_浮生  阅读(124)  评论(0)    收藏  举报