安卓经过绑定开启服务 来调用服务里的方法

建立服务

package com.example.studyReturn;

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

public class TestService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		System.out.print("服务onbind");
                //经过绑定服务过来的返回给onServiceConnected方法
		return new MyBinder();
	}
	private class MyBinder extends Binder implements IServer
	{
		@Override
		public void callSer(String name) {
			//这里调用服务里面的方法
			serMethod(name);
		}
		
		public void otherMehod()
		{
			//其余方法;若是须要暴漏给外面就去接口去加方法
		}
	}
	@Override
	public void onCreate() {
		System.out.println("服务被开启了");
		super.onCreate();
	}
	
	@Override
	public void onDestroy() {
		System.out.println("服务销毁了");
		super.onDestroy();
	}
	
	public void serMethod(String name)
	{
		Toast.makeText(getApplicationContext(), "服务里面的方法:"+name, Toast.LENGTH_SHORT).show();;
	}
}

##配置清单 <service android:name=".TestService"></service> ##抽取接口android

package com.example.studyReturn;

public interface IServer {
	public void callSer(String name); //服务中须要暴漏的方法放在接口中
}

绑定服务

public void testBindService(View view)
	{
		Intent intent = new Intent(this, TestService.class);
		MyConn myconn = new MyConn();
		bindService(intent, myconn, BIND_AUTO_CREATE); //服务若是不存在则建立
	}
	private class MyConn implements ServiceConnection
	{
		public void onServiceConnected(ComponentName name, IBinder ibinder) {
			//服务中onBind方法返回
			is = (IServer) ibinder;
		}
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			
		}
	}
	
	public void callSerService(View view)
	{
		//这里就能够经过is调用服务里面的方法了
		is.callSer("hahahah");
	}
相关文章
相关标签/搜索