Android Service


  一.Service

服务是运行在后台的一段代码。它可以运行在它自己的进程,也可以运行在其他应用程序进程的上下文(context)里面,这取决于自身的需要。其它的组件可以绑定到一个服务Service)上面,通过远程过程调用(RPC)来调用这个方法。例如媒体播放器的服务,当用户退出媒体选择用户界面,仍然希望音乐依然可以继续播放,这时就是由服务 service)来保证当用户界面关闭时音乐继续播放的。

 

它跟Activity的级别差不多,但是他不能自己运行,需要通过某一个Activity或者其他Context对象来调用, Context.startService()Context.bindService()

两种启动Service的方式有所不同。这里要说明一下的是如果你在ServiceonCreate或者onStart做一些很耗时间的事情,最好在Service里启动一个线程来完成,因为Service是跑在主线程中,会影响到你的UI操作或者阻塞主线程中的其他事情。

什么时候需要Service呢?比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等。

   二.使用Service

private String MY_ACTION = "com.demo.MyService";
启动Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			startService(intent);

停止Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			stopService(intent);

绑定Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			unbindService(conn);

解除绑定Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			bindService(intent, conn, Service.BIND_AUTO_CREATE);
	private ServiceConnection conn = new ServiceConnection(){
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("连接成功!");
			showMessage("连接成功!");
		}
		public void onServiceDisconnected(ComponentName name) {
			System.out.println("断开连接!");
			showMessage("断开连接!");
		}
	};

Service类代码:

package com.demo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {

	public IBinder onBind(Intent intent) {
		System.out.println("Service onBind");
		return null;
	}
	
	public void onCreate() {
		System.out.println("Service onCreate");
		super.onCreate();
	}
	
	public void onStart(Intent intent, int startId) {
		System.out.println("Service onStart");
		super.onStart(intent, startId);
	}
	
	public void onDestroy() {
		System.out.println("Service onDestory");
		super.onDestroy();
	}
	
}

AndroidManifest.xml

        <service android:name="MyService">
        	<intent-filter>
        		<action android:name="com.demo.MyService"/>
        	</intent-filter>
        </service>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值