Android中的Service使用全解析

一、概述

Service是后台服务,没有用户界面,适合用于去执行长期运行的任务。Service不是一个单独的进程,除非单独指定,否则将会应用程序运行在同一个进程当中。Service不是一个线程,需要在Service中开启线程去执行耗时操作。

Service的分类:

  • 启动Service(Service不能够与Activity很好的交互)
  • 绑定Service(Service相对于服务端Activity相对于客户端,通过Binder对象传递数据)
  • IntentService(用于执行短期的耗时操作)

二、启动Service

废话少说,直接上码。

/**
 * Created by magic on 2016年9月26日.启动Service
 */
public class MainActivity extends Activity {
	private Button button;
	private Button button1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.one);
		button = (Button) findViewById(R.id.button1);
		button1 = (Button) this.findViewById(R.id.button2);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent service = new Intent(MainActivity.this,Mainservice.class);
			    //启动service
				//service的执行效果,不利于与activity反馈
				startService(service);
			}
		});
		button1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(MainActivity.this, Mainservice.class);
				//停止service
				stopService(intent);
			}
		});
	}
}
/**
 * Created by magic on 2016年9月26日.Service
 */
public class Mainservice extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	@Override
	public void onCreate() {
		//创建的时候执行
		super.onCreate();
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		//启动的时候执行
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onDestroy() {
		//service停止的时候执行
		super.onDestroy();
	}
}

多次启动Service都会调用onStartCommand()方法,onCreate()方法只会在最初创建Service时调用一次。

 <!--配置文件中进行注册service-->
 <service android:name="com.example.test_service.Mainservice" />

以上就是service的最基本使用,启动service有个缺点,就是service启动后activity无法监听service的执行结果。

三、绑定Service

Service相对于服务端Activity相对于客户端,通过Binder对象传递数据。

/**
 * Created by magic on 2016年9月26日.绑定service并给出反馈
 */ 
public class MainActivity extends Activity {
	Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		button = (Button) findViewById(R.id.button0);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(MainActivity.this, TestService.class);
				//service 绑定
				bindService(intent, conn, BIND_AUTO_CREATE);
			}
		});
	}
	   // 服务连接接口类
	   ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			// 断开连接回调
		}
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder ibinder) {
			// 连接成功回调
			// 向下转型
			FirstBinder binder = (FirstBinder) ibinder;
			String str = binder.getData();
			System.out.println(str);//Hello World!!!
		}
	};
}

绑定Service通过ServiceConnection服务连接类,监听绑定状态,在onServiceConnected(ComponentName arg0, IBinder ibinder)方法中通过参数获取Service给出的反馈。

自定义Service类,添加反馈信息。

/**
 * Created by magic on 2016年9月26日.Service
 */
public class TestService extends Service{

	@Override
	public IBinder onBind(Intent arg0) {
		//Binder是IBinder接口的实现类
	    //向上转型
		IBinder binder=new FirstBinder();
		return binder;
	}
	class FirstBinder extends Binder{
		public String getData(){
			String str="Hello World!!!";
			return str;
		}
	}
}

Service中重写onBind(Intent arg0)方法,在该方法中返回IBinder的实现类对象,从而在该对象上设置需要返回的数据内容。

 <!--配置文件中进行注册service-->
 <service android:name="com.example.test_service.TestService" />

通过Binder向服务端发送数据并得到反馈。

/**
 * Created by magic on 2016年9月26日.Service请求服务和反馈
 */
public class TwoActivity extends Activity {
	Button button0, button1;
	TextView textView;
	Binder binder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.two_activity);
		button0=(Button)findViewById(R.id.button0);
		button1=(Button)findViewById(R.id.button1);
		textView=(TextView)findViewById(R.id.textView0);
		
		button0.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//绑定服务
				Intent intent=new Intent(TwoActivity.this,TwoService.class);
				bindService(intent, connection, BIND_AUTO_CREATE);
			}
		});
		
		button1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//序列化
				Parcel data=Parcel.obtain();
				Parcel reply=Parcel.obtain();
				//写入数据
				data.writeString("Hello MAGCI!");
				//写入数据
				data.writeInt(100);
				try {
					binder.transact(0, data, reply, 0);
					//data 类似于客户端向服务端发送的数据
					//reply 类似服务端向客户端反馈的数据
					//如果 service还未返回 则处于阻塞态
					//读出数据
					System.out.println("repley:"+reply.readString());//repley:MAGCI very cool!
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	ServiceConnection connection=new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			// 断开连接时候
		}
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder  iBinder) {
			// 服务连接的时候
			binder=(Binder) iBinder;
		}
	};
}

自定义Service类,添加反馈信息,并获取客户端传过来的数据。

/**
 * Created by magic on 2016年9月26日.Service
 */
public class TwoService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return new MyBinder();
	}
	class MyBinder extends Binder {

		//接收Activity发送的数据 并反馈
		@Override
		protected boolean onTransact(int code, Parcel data, Parcel reply,
				int flags) throws RemoteException {
			System.out.println("code:"+code);//code:0
			System.out.println("data:"+data.readString()+"---"+data.readInt());//data:Hello MAGCI!---100
			reply.writeString("MAGCI very cool!");
			return super.onTransact(code, data, reply, flags);
		}
	}
}
 <!--配置文件中进行注册service-->
 <service android:name="com.example.test_service.TwoService " />

三、IntentService

IntentService异步处理服务,新开一个线程:handlerThread在线程中发消息,然后接受处理完成后,会清理线程,并且关掉服务。用于执行短期的耗时操作。

	class MyIntentService extends IntentService{

		public MyIntentService(String name) {
			super(name);
		}

		@Override
		protected void onHandleIntent(Intent intent) {
			/**耗时操作**/
		}
		
	}

END!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值