Android Service生命週期及用法

原文:http://blog.csdn.net/android_tutor/article/details/5789203

Service概念及用途:

Android中的服務,它與Activity不同,它是不能與用戶交互的,不能自己啓動的,運行在後臺的程序,如果我們退出應用時,Service進程並沒有結束,它仍然在後臺運行,那我們什麼時候會用到Service呢?比如我們播放音樂的時候,有可能想邊聽音樂邊幹些其他事情,當我們退出播放音樂的應用,如果不用Service,我們就聽不到歌了,所以這時候就得用到Service了,又比如當我們一個應用的數據是通過網絡獲取的,不同時間(一段時間)的數據是不同的這時候我們可以用Service在後臺定時更新,而不用每打開應用的時候在去獲取。Service不是一個線程,更不是一個單獨的進程;但可以用來處理一些耗時的操作,可以使用service來更新contentprovider;發送intent以及啓動系統的通知等。

Service生命週期:

Android Service的生命週期並不像Activity那麼複雜,它只繼承了onCreate(),onStart(),onDestroy()三個方法,當我們第一次啓動Service時,先後調用了onCreate(),onStart()這兩個方法,當停止Service時,則執行onDestroy()方法,這裏需要注意的是,如果Service已經啓動了,當我們再次啓動Service時,不會在執行onCreate()方法,而是直接執行onStart()方法,具體的可以看下面的實例。

Service與Activity通信:

Service後端的數據最終還是要呈現在前端Activity之上的,因爲啓動Service時,系統會重新開啓一個新的進程,這就涉及到不同進程間通信的問題了(AIDL)這一節我不作過多描述,當我們想獲取啓動的Service實例時,我們可以用到bindService和onBindService方法,它們分別執行了Service中IBinder()和onUnbind()方法。

 爲了讓大家 更容易理解,我寫了一個簡單的Demo,大家可以模仿着我,一步一步的來。

 第一步:新建一個Android工程,我這裏命名爲ServiceDemo.

第二步:修改main.xml代碼,我這裏增加了四個按鈕,代碼如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
    <TextView  
        android:id="@+id/text"    
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:text="@string/hello"  
        />  
    <Button  
        android:id="@+id/startservice"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="startService"  
    />  
    <Button  
        android:id="@+id/stopservice"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="stopService"  
    />  
    <Button  
        android:id="@+id/bindservice"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="bindService"  
    />  
    <Button  
        android:id="@+id/unbindservice"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="unbindService"  
    />  
</LinearLayout> 

第三步:新建一個Service,命名爲MyService.java代碼如下:

    package com.tutor.servicedemo;  
    import android.app.Service;  
    import android.content.Intent;  
    import android.os.Binder;  
    import android.os.IBinder;  
    import android.text.format.Time;  
    import android.util.Log;  
    public class MyService extends Service {  
        //定義個一個Tag標籤  
        private static final String TAG = "MyService";  
        //這裏定義吧一個Binder類,用在onBind()有方法裏,這樣Activity那邊可以獲取到  
        private MyBinder mBinder = new MyBinder();  
        @Override  
        public IBinder onBind(Intent intent) {  
            Log.e(TAG, "start IBinder~~~");  
            return mBinder;  
        }  
        @Override  
        public void onCreate() {  
            Log.e(TAG, "start onCreate~~~");  
            super.onCreate();  
        }  
          
        @Override  
        public void onStart(Intent intent, int startId) {  
            Log.e(TAG, "start onStart~~~");  
            super.onStart(intent, startId);   
        }  
          
        @Override  
        public void onDestroy() {  
            Log.e(TAG, "start onDestroy~~~");  
            super.onDestroy();  
        }  
          
          
        @Override  
        public boolean onUnbind(Intent intent) {  
            Log.e(TAG, "start onUnbind~~~");  
            return super.onUnbind(intent);  
        }  
          
        //這裏我寫了一個獲取當前時間的函數,不過沒有格式化就先這麼着吧  
        public String getSystemTime(){  
              
            Time t = new Time();  
            t.setToNow();  
            return t.toString();  
        }  
          
        public class MyBinder extends Binder{  
            MyService getService()  
            {  
                return MyService.this;  
            }  
        }  
    }  

第四步:修改ServiceDemo.java,代碼如下:

    package com.tutor.servicedemo;  
    import android.app.Activity;  
    import android.content.ComponentName;  
    import android.content.Context;  
    import android.content.Intent;  
    import android.content.ServiceConnection;  
    import android.os.Bundle;  
    import android.os.IBinder;  
    import android.view.View;  
    import android.view.View.OnClickListener;  
    import android.widget.Button;  
    import android.widget.TextView;  
    public class ServiceDemo extends Activity implements OnClickListener{  
         
        private MyService  mMyService;  
        private TextView mTextView;  
        private Button startServiceButton;  
        private Button stopServiceButton;  
        private Button bindServiceButton;  
        private Button unbindServiceButton;  
        private Context mContext;  
          
        //這裏需要用到ServiceConnection在Context.bindService和context.unBindService()裏用到  
        private ServiceConnection mServiceConnection = new ServiceConnection() {  
            //當我bindService時,讓TextView顯示MyService裏getSystemTime()方法的返回值   
            public void onServiceConnected(ComponentName name, IBinder service) {  
                // TODO Auto-generated method stub  
                mMyService = ((MyService.MyBinder)service).getService();  
                mTextView.setText("I am frome Service :" + mMyService.getSystemTime());  
            }  
              
            public void onServiceDisconnected(ComponentName name) {  
                // TODO Auto-generated method stub  
                  
            }  
        };  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
            setupViews();  
        }  
          
        public void setupViews(){  
          
            mContext = ServiceDemo.this;  
            mTextView = (TextView)findViewById(R.id.text);  
              
              
              
            startServiceButton = (Button)findViewById(R.id.startservice);  
            stopServiceButton = (Button)findViewById(R.id.stopservice);  
            bindServiceButton = (Button)findViewById(R.id.bindservice);  
            unbindServiceButton = (Button)findViewById(R.id.unbindservice);  
              
            startServiceButton.setOnClickListener(this);  
            stopServiceButton.setOnClickListener(this);  
            bindServiceButton.setOnClickListener(this);  
            unbindServiceButton.setOnClickListener(this);  
        }  
         
        public void onClick(View v) {  
            // TODO Auto-generated method stub  
            if(v == startServiceButton){  
                Intent i  = new Intent();  
                i.setClass(ServiceDemo.this, MyService.class);  
                mContext.startService(i);  
            }else if(v == stopServiceButton){  
                Intent i  = new Intent();  
                i.setClass(ServiceDemo.this, MyService.class);  
                mContext.stopService(i);  
            }else if(v == bindServiceButton){  
                Intent i  = new Intent();  
                i.setClass(ServiceDemo.this, MyService.class);  
                mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);  
            }else{  
                mContext.unbindService(mServiceConnection);  
            }  
        }  
          
          
          
    }  


第五步:修改AndroidManifest.xml代碼(將我們新建的MyService註冊進去如下代碼第14行:)

    <?xml version="1.0" encoding="utf-8"?>  
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
          package="com.tutor.servicedemo"  
          android:versionCode="1"  
          android:versionName="1.0">  
        <application android:icon="@drawable/icon" android:label="@string/app_name">  
            <activity android:name=".ServiceDemo"  
                      android:label="@string/app_name">  
                <intent-filter>  
                    <action android:name="android.intent.action.MAIN" />  
                    <category android:name="android.intent.category.LAUNCHER" />  
                </intent-filter>  
            </activity>  
            <service android:name=".MyService" android:exported="true"></service>  
        </application>  
        <uses-sdk android:minSdkVersion="7" />  
    </manifest>   
 

第六步:執行上述工程,效果圖如下:

點擊startServie按鈕時先後執行了Service中onCreate()->onStart()這兩個方法,打開Logcat視窗效果如下圖:

我們這時可以按HOME鍵進入Settings(設置)->Applications(應用)->Running Services(正在運行的服務)看一下我們新啓動了一個服務,效果如下:

點擊stopService按鈕時,Service則執行了onDestroy()方法,效果圖如下所示:

這時候我們再次點擊startService按鈕,然後點擊bindService按鈕(通常bindService都是bind已經啓動的Service),我們看一下Service執行了IBinder()方法,以及TextView的值也有所變化了,如下兩張圖所示:

 

最後點擊unbindService按鈕,則Service執行了onUnbind()方法,如下圖所示:


發佈了26 篇原創文章 · 獲贊 3 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章