四大组件中的Service学习

Service的启动:

1. startService(Intent service)

    在应用中调用startService(Intent service)来启动Service,如果该Service还未启动,则系统会依次回调Service类的onCreate()、onStartCommand()、onStart()方法;启动的服务会一直运行在后台,即便是应用已经退出,除非该Service的stopSelf()被调用或者外界通过stopService(Intent service)中止服务,这时候系统会回调Service类的onDestory()方法。

如果该Service已经启动,则调用startService(Intent service)只会回调onStartCommand()和onStart()方法;

2. bindService(Intent service, ServiceConnection conn, int flags)

    在应用中调用bindService()来绑定一个的服务,如果要绑定的Service还未启动,则依次会回调系统的onCreate()、onBind()方法,同时去连接ServiceConnection,连接成功则回调onServiceConnected()方法,调用unbindSevice()则会执行onUnbind()、onDestory()销毁服务。如果要绑定的Service已经启动,则会回调系统的onBind()方法,并尝试建立于ServiceConnection对象的连接,连接成功回调onServiceConnected(),调用unbindService()则会执行onUnbind()但是不会将服务销毁,这可能是因为该服务不是自己创建的,所以不做销毁处理,而且下一次还可以继续通过bindService()重新绑定。

一个简单的例子如下:

MainActivity.java

package com.example.servicedemos;

import java.sql.Connection;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
	protected static final String TAG = "yxf";
	private Button mStartButton;
	private Button mStopButton;
	private Button mBindButton;
	private Button mUnbindButton;
	private SimpleService.MyBinder mBinder;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    mStartButton = (Button)findViewById(R.id.start);
	    mStopButton = (Button)findViewById(R.id.stop);
	    mBindButton = (Button)findViewById(R.id.bind);
	    mUnbindButton = (Button)findViewById(R.id.unbind);
	    mStartButton.setOnClickListener(new View.OnClickListener() {
	        @Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MainActivity.this,SimpleService.class);
			startService(intent);
		}
	    });
		
	    mStopButton.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
		    // TODO Auto-generated method stub
		    Intent intent = new Intent(MainActivity.this,SimpleService.class);
		    stopService(intent);
		}
	    });
		
            mBindButton.setOnClickListener(new View.OnClickListener() {	
		@Override
		public void onClick(View arg0) {
		    // TODO Auto-generated method stub
		    Intent intent = new Intent(MainActivity.this,SimpleService.class);
		    bindService(intent, connection, BIND_AUTO_CREATE);
		}
	    });
		
	    mUnbindButton.setOnClickListener(new View.OnClickListener() {
	        @Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MainActivity.this,SimpleService.class);
			unbindService(connection);
		}
	    });
	}

	private ServiceConnection connection = new ServiceConnection() {  
            @Override  
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d(TAG,"onServiceConnected");
                mBinder = (SimpleService.MyBinder) service;  
                mBinder.startDownload();  
            }

	    @Override
	    public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		Log.d(TAG,"onServiceDisConnected");
	    }  
        };  
 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}

SimpleService.java

package com.example.servicedemos;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class SimpleService extends Service{
	private static final String TAG = "yxf";
	private MyBinder mBinder = new MyBinder(); 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onCreate()");
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onDestory()");
		super.onDestroy();
	}
	/*当客户端调用调用unBind()断开Service后,试图重新调用bindService()连接服务,
	 * 只有当onUnbind()方法被重写为返回true时才会回调onRebind()
	 * **/
	@Override
	public void onRebind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onRebind()");
		super.onRebind(intent);
	}
       @Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onStart()");
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onStartCommand()");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onUnbind()");
		//return super.onUnbind(intent);
		return true;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Log.d(TAG,"SimpleService,onBind()");
		return mBinder;
	}
	
	class MyBinder extends Binder {  		  
            public void startDownload() {  
                Log.d(TAG, "startDownload() executed");  
                // 执行具体的下载任务  
            }  
    }  
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值