Android 关于Service 的使用

来源:互联网 发布:淘宝售后退款在哪里 编辑:程序博客网 时间:2024/05/19 14:35

看了官方的文档之后还是一头雾水,一筹莫展,一声长叹~然后做了一些搜索,总结如下:宏观来说,Service 是为了某种需求,而提出来的一种解决模式,一种机制,或者说哲学思想;微观来说,和Thread一样,在后台跑,但Service里也可以是用Thread;Service 地位略高于Activity,因为service 可以独立于Activity使用。推荐阅读:http://android.blog.51cto.com/268543/527314

SendSosService 继承 Service 重写四个方法:onCreate(),onStartCommand(),onDestroy() 最主要这三个,onBind() 当需要与Activity通讯时才用到。
   

public class SendSosService extends Service {private final String TAG = "SendSosService";SharedPreferencesUtil spu;private final IBinder mBinder = new SendSosBinder();public class SendSosBinder extends Binder {public SendSosService getService() {return SendSosService.this;}public void setSosId(String sosId) {spu.putValue(STR_ID, sosId);}}@Overridepublic void onCreate() {initBaiduTools();spu = new SharedPreferencesUtil(SendSosService.this, SharedPreferencesUtil.STR_XMLFILE);super.onCreate();Log.d(TAG, "Service Create");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d(TAG, "Service Start");return super.onStartCommand(intent, flags, startId);//返回Service的模式,可查阅文档}/** * 销毁 */@Overridepublic void onDestroy() {super.onDestroy();Log.d(TAG, "Service Destroy");}@Overridepublic IBinder onBind(Intent intent) {return mBinder;}}

Activity: ServiceConnection 属性

sosServiceConn = new ServiceConnection() {                        @Override            public void onServiceDisconnected(ComponentName name) {             Log.v("TAG", "解除绑定 service");             isBind = false;            }                         @Override            public void onServiceConnected(ComponentName name, IBinder service) {            SendSosService.SendSosBinder sBinder = (SendSosService.SendSosBinder)service;            isBind = true;                Log.v("TAG", "绑定 service" + id);            }        };
通过startService()启动服务,bindService()绑定服务,unBindService(),解绑服务,stopService()停止服务
startService(new Intent(SosSendActivity.this,SendSosService.class));//后台启动地图定位服务并发送到服务器bindService(new Intent(SosSendActivity.this, SendSosService.class), sosServiceConn, Context.BIND_AUTO_CREATE);//绑定