Android startService和bindService的区别

前言:大家好,我是Clover,从事Android应用开发以来一直自学,身边能请教的牛人很少,遇到问题就泡在CSDN各种学习大神们的经验,真的非常感谢CSDN这个平台。到目前Clover也是积累了一点项目经验,决定写点自己的文,整理一些平时常用的方法、技术点或是典型的小组件,算是对自己平日学习的总结和记录吧,都是基础的东西大神请忽略,有不正确或者可以改进的地方欢迎大家帮忙指点,谢谢☺️


Android四大组件之一的Service提供一个在后台运行的服务,Service的生命周期方法有onCreate、onStart、onDestroy,它不可交互,不能自己运行,需要Activity或其他Context对象来调用,启动方式有startService和bindService两种,

通过startService启动时,Service会经过onCreate——onStart过程,停止时直接执行onDestroy方法。如果调用Service的调用者自己直接退出而没有调用stopService的话,Service就一直在后台运行,知道调用者再次启动并调用stopService。bindService启动Service,执行onCreate——onBind方法,此时Service与其调用者产生绑定关系,如果调用者退出,Service会经过onUnbind——onDestroy后退出,下面举例。

首先,写一个类TestService继承Service,并重写其生命周期方法,在每个生命周期方法里打印日志,并在onCreate方法里显示Notification,代码如下:

public class TestService extends Service{

	private static final String TAG="TestService";
	private NotificationManager _nmManager;
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.e(TAG, "==========>TestService.onBind");
		return null;
	}

	
	public class LocalBinder extends Binder{
		TestService getService(){
			return TestService.this;
		}
	}
	
	@Override
	public boolean onUnbind(Intent i){
		Log.e(TAG, "==========>TestService.onUnbind");
		return false;
	}
	
	@Override
	public void onRebind(Intent i) {
		Log.e(TAG, "==========>TestService.onRebind");
		
	}
	
	@Override
	public void onCreate(){
		Log.e(TAG, "==========>TestService.onCreate");
		_nmManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		showNotification();
	}
	
	@Override
	public void onStart(Intent intent,int startId){
		Log.e(TAG, "==========>TestService.onStart");
	}
	
	@Override
	public void onDestroy() {
		_nmManager.cancel(R.string.Service_started);
		Log.e(TAG, "==========>TestService.onDestroy");
	}
	
	private void showNotification(){
		
		Notification notification=new Notification(R.drawable.ic_launcher,"Service Started",System.currentTimeMillis());
		
		PendingIntent contentIntent=PendingIntent.getActivity(this, 0, new Intent(this,ServiceTestActivity.class), 0);
		notification.setLatestEventInfo(this, "Test   Service", "Service started", contentIntent);
		_nmManager.notify(R.string.Service_started, notification);
	}
}
</span>


然后在Activity中调用这个Service,我这里的界面上分别定义了四个按钮:Start Service,Stop Service,Bind Service和Unbind Service,通过点击它们就可以调用想要方法,注意Service一定要在Manifest.xml中注册好

public class ServiceTestActivity extends Activity {

	private boolean _isBound;
	private TestService _boundService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_service_test);
		initButtons();
	}

	private void initButtons(){
		Button buttonStart=(Button)findViewById(R.id.start_service);
		buttonStart.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startService();
			}
		});
		
		Button buttonStop=(Button)findViewById(R.id.stop_service);
		buttonStop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopService();
			}
		});
		
		Button buttonBind=(Button)findViewById(R.id.bind_service);
		buttonBind.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				bindService();
			}
		});
		
		Button buttonUnbind=(Button)findViewById(R.id.unbind_service);
		buttonUnbind.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				unbindService();
			}
		});
	}
	
	private ServiceConnection _conConnection=new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			_boundService=null;
			Toast.makeText(ServiceTestActivity.this, "Service disconnected", Toast.LENGTH_SHORT).show();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			_boundService=((TestService.LocalBinder)service).getService();
			Toast.makeText(ServiceTestActivity.this, "Service connected", Toast.LENGTH_SHORT).show();
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.service_test, menu);
		return true;
	}

	
	private void startService(){
		Intent intent=new Intent(this,TestService.class);
		this.startService(intent);
	}
	
	private void stopService(){
		Intent intent=new Intent(this,TestService.class);
		this.stopService(intent);
	}
	
	private void bindService(){
		Intent intent=new Intent(this,TestService.class);
		bindService(intent,_conConnection,Context.BIND_AUTO_CREATE);
		_isBound=true;
	}
	
	private void unbindService(){
		if (_isBound) {
			unbindService(_conConnection);
		}
		_isBound=false;
	}
}
</span>

运行后点击Start Service 可以看到通知栏显示了服务已启动,退出程序可以看到通知栏中依然显示服务运行,再启动程序点击Stop Service时,通知栏提示消失,再点击Bind Service试一次,发现程序退出后,通知栏内容已一起退出了,截图太大不放了,总之,这就是startService和bindService的区别,虽然很简单但是应该牢记的一点哦~


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值