Android四大組件之服務-Service

來源:互聯網
上載者:User

標籤:

一、Android 服務簡介

Service是android 系統中的四大組件之一(Activity、Service、BroadcastReceiver、ContentProvider),它跟Activity的層級差不多,但不能自己運行只能後台運行,並且可以和其他組件進行互動。service可以在很多場合的應用中使用,比如播放多媒體的時候使用者啟動了其他Activity這個時候程式要在後台繼續播放,比如檢測SD卡上檔案的變化,再或者在後台記錄你地理資訊位置的改變等等,總之服務總是藏在背景。

Service的啟動有兩種方式:context.startService() 和 context.bindService()

二、原理和流程

1.建立前台服務,只需要提供一個通知欄表徵圖並且調用startForeground即可。

2.想讓服務做自己的想做的事情,也比較簡單,只需要在onCreate或者onStartConmand的時候new一個Thread即可

3.如果Activity等UI想要和服務通訊、調用服務提供的方法,怎麼辦呢?這時候就需要用到Binder了:只需要在onBind的時候返回一個IBinder對象,通過該對象可以擷取當前Service的對象引用,這樣就可以操作服務所提供的方法了,那如何在Service操作Acitivty呢?

有了Service引用,這個時候只需要在Service中給Activity開放設定回調介面即可。

4.當然了,服務需要在Manifest.xml中進行配置聲明:

 <service android:name="com.czm.servicetest.MyService" >  </service>

三、執行個體:MyService.java

package com.czm.servicetest;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;/** * The Service Example * @author caizhiming * */public class MyService extends Service{    IBinder mBinder = new MyBinder();    private int mCount = 0;    public boolean mIsStop = false;        // get the instance of MyService    public class MyBinder extends Binder{        MyService getService(){            return MyService.this;        }    }        public void setData(int data){        mCount = data;    }    public int getData(){        return mCount;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();        Thread thread = new Thread(null, new ServiceWorker(), "ServiceWorker");        thread.start();    }    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        Log.v("czm","onBind()-service is started");        return mBinder;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // TODO Auto-generated method stub        Log.v("czm","onStartCommand()-service is started");        return super.onStartCommand(intent, flags, startId);    }    //The Service work‘s thread    class ServiceWorker implements Runnable{        @Override        public void run() {            // TODO Auto-generated method stub            while(!mIsStop){                Log.v("czm","ServiceWorker: mCount="+mCount);                mCount ++;                if(mCount >=  10000){                    mCount  = 0;                }                if(mCount %5 == 0){                    mListener.onCallback();                }                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }                    }    }    //The callback listener to operate UI such as Activity    private OnUICallbackListener mListener;    public void setListener(OnUICallbackListener listener){        mListener = listener;    }    public interface OnUICallbackListener{        void onCallback();    }    }

四、如何使用服務-MyService?

package com.czm.servicetest;import com.czm.servicetest.MyService.MyBinder;import com.czm.servicetest.MyService.OnUICallbackListener;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnUICallbackListener{    private Button mBtnStart;    private Button mBtnChange;    private Button mBtnStop;    private TextView mTvResult;        private MyService mMyService;    Intent serviceIntent;        private Handler mHandler = new Handler(){        public void handleMessage(Message msg) {            mTvResult.setText(String.valueOf(mMyService.getData()));            mHandler.sendEmptyMessageDelayed(0, 1000);        };    };        private ServiceConnection mServiceConnection = new ServiceConnection() {                @Override        public void onServiceDisconnected(ComponentName name) {            // TODO Auto-generated method stub            Log.v("czm","onServiceDisconnected()");        }                @Override        public void onServiceConnected(ComponentName name, IBinder service) {            // TODO Auto-generated method stub            Log.v("czm","onServiceConnected()");            MyBinder binder = (MyBinder) service;            mMyService = binder.getService();            mMyService.setListener(MainActivity.this);            mHandler.sendEmptyMessageDelayed(0, 0);        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mBtnStart = (Button)findViewById(R.id.btn_start);        mBtnChange = (Button)findViewById(R.id.btn_change);        mBtnStop = (Button)findViewById(R.id.btn_stop);        mTvResult = (TextView)findViewById(R.id.tv_result);                mBtnStart.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                //start service                serviceIntent = new Intent(MainActivity.this,MyService.class);                serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                //bind service in order to communicate with service                MainActivity.this.bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);//                startService(serviceIntent);            }        });        mBtnChange.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                mMyService.setData(1000);            }        });        mBtnStop.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                mMyService.mIsStop = true;                MainActivity.this.unbindService(mServiceConnection);                stopService(serviceIntent);            }        });    }        /**     * service callback      * @param serviceConnection     */    @Override    public void onCallback() {        // TODO Auto-generated method stub        runOnUiThread(new Runnable() {                        @Override            public void run() {                // TODO Auto-generated method stub                Toast.makeText(MainActivity.this, "service callback", Toast.LENGTH_SHORT).show();            }        });            }}

 

Android四大組件之服務-Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.