Android四大组件之Service(笔记)

什么叫service

android中的service跟windows中的服务很类似,是一种没有用户操作界面,在特定的内运行,而且不容易被用户察觉的程序。

在android中服务可分为两种:

1.本地服务

LocalService

 运行在本应用程序内部的,可以自行通过调用Service.stopSelf()或者Service.stopSelfResult来自动停止。

2.远程服务

RemoteService

可运行在android系统中的应用程序之间,可以定义接口并将接口暴露出来给其他应用程序调用,通过调用bindService进行服务对象的连接

所有的服务必须在配置文件AndroidManifest.xml中定义,通过Context.startService或者Context.bindService来启动服务

Service的生命周期

通过两种方式启动的service的生命周期也会不同

context.startService() ->onCreate()- >onStart()->Service running--调用context.stopService() ->onDestroy()

context.bindService()->onCreate()->onBind()->Service running--调用>onUnbind() -> onDestroy()

上图更能详细说明service生命周期


Activity与服务进行通信,开发人员通常把通信方法定义在接口里,然后让Ibinder对象实现该接口,而Activity通过该接口引用服务onBind()方法返回的Ibinder对象,然后调用Ibinder对象里自定义的通信方法。

下面一个简单的具体实例来说明以上解决方案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/number"
    />
    
    <EditText
     android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/number"
    />
    
    <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/button"
    android:onClick="query"
    />
    
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/resultView"
    />
</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">Local Service Query</string>
    <string name="number">Identification</string>
    <string name="button">Query</string>
</resources>


package com.eric.test
/**
 * 查询接口,服务端和客户端对话的公共标准,方便客户端对服务端方法的使用
 *
 */
public interface QueryService {
    //查询方法
    public String queryPlatform(int id);
}


package com.eric.test;

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

public class PlateformService extends Service {
	private IBinder binder = new StudentBinder();
	private String[] names = {"Android", "iPhone", "Windows Phone"};
	
	/**
	 * 根据Id号,查询信息
	 * @param no
	 * @return
	 */
	private String query(int id){
		if(id > 0 && id <4){
			return names[id - 1];
		}
		return null;
	}  

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	//返回给客户端的实现
	private final class StudentBinder extends Binder implements QueryService{
		public String queryPlatform(int id) {
			return query(id);
		}
	}
}

package com.eric.test;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    private EditText numberText;
    private TextView resultView;
    private PlatformConnection connection = new PlatformConnection();
    private QueryService queryService;
       
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        numberText = (EditText) this.findViewById(R.id.number);
        resultView = (TextView) this.findViewById(R.id.resultView);
        
        //建立一个Intent,指定要绑定的服务
        Intent service = new Intent(this, PlateformService.class);
        //绑定服务 该方法是异步的,会立即返回
        bindService(service, connection, BIND_AUTO_CREATE);
    }
    
    private final class PlatformConnection implements ServiceConnection{
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {//建立连接时的回调方法
			queryService = (QueryService)service;
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {	//意外中断时候的回调方法
			queryService = null;
		}
    }
    
    /**
     * 查询方法
     * @param v 参数必须是View类型
     */
    public void query(View v){
    	String number = numberText.getText().toString();
    	//此处的查询服务是同步的,如果有耗时的工作,需要开辟一条新的线程
    	String name = queryService.queryPlatform(Integer.valueOf(number));
    	resultView.setText(name);
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值