Android 关于Service 的使用

看了官方的文档之后还是一头雾水,一筹莫展,一声长叹~然后做了一些搜索,总结如下:宏观来说,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);
		}

	}

	@Override
	public void onCreate() {
		initBaiduTools();
		spu = new SharedPreferencesUtil(SendSosService.this, SharedPreferencesUtil.STR_XMLFILE);
		super.onCreate();
		Log.d(TAG, "Service Create");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "Service Start");
		return super.onStartCommand(intent, flags, startId);//返回Service的模式,可查阅文档
	}

	/**
	 * 销毁
	 */
	@Override
	public void onDestroy() {

		super.onDestroy();
		Log.d(TAG, "Service Destroy");
	}
	

	@Override
	public 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);//绑定

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值