android bindService 来调用服务中的方法

android 服务组件中,可以用bindService来与一个服务相绑定。

下面的demo是一个在Activity界面组件中,调用Service服务组件中的myMethod()自定义的方法。这个demo可以解决在项目开发中。调用service里的数据。

这里在service中使用到了,代理模式。这是为了,给service组件和activity组件中间添加一个中间人。通过代理来传递数据。也就是binder对象。这个代理就是借口myInterface

下面是部分代码。

package com.example.demoservicefuncation;

import android.os.Binder;
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.view.View.OnClickListener;

public class MainActivity extends Activity {

	private View btnCallServiceFunc;
	private Intent mService;
	private MyInterface mBinder;
	private MyServiceConnection conn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		btnCallServiceFunc = this.findViewById(R.id.btn);
		btnCallServiceFunc.setOnClickListener(new MainOnclickListenter());
		mService = new Intent(MainActivity.this, MyService.class);

	}

	private class MainOnclickListenter implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == btnCallServiceFunc) {
				// 调用服务里的方法
				bindService();

			}
		}

	}

	public void bindService() {
		conn = new MyServiceConnection();
		bindService(mService, conn, BIND_AUTO_CREATE); // 1.调用次方法,会调用MyService里的onBind()

	}

	public void unBindService() {
		// 接触绑定
		unbindService(conn);
	}

	private class MyServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			// 3,绑定成功,在此处就可以用服务中的方法
			MainActivity.this.mBinder = (MyInterface) service;
			mBinder.callMethod();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		startService(mService); // Myservice需要在清单文件中配置
	};

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		stopService(mService);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//接触绑定
		unbindService(conn);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

package com.example.demoservicefuncation;

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

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		//2.接受到绑定信息.使用代理模式,将服务中的myMethod()暴露出去给activity中使用
		MyCallMethod mCallMethod=new MyCallMethod();
		return mCallMethod; //返回的mCallmethod对象会在onServiceConnected()中调用
	}
	
	private void myMethod(){
		Toast.makeText(getApplicationContext(), "我是服务里的方法", 0).show();
	}
	private class MyCallMethod extends Binder implements MyInterface{

		@Override
		public void callMethod() {
			// TODO Auto-generated method stub
			//调用myMethod()
			myMethod();
		}
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}
	
	

}

package com.example.demoservicefuncation;

public interface MyInterface {
	public void callMethod();
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demoservicefuncation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.demoservicefuncation.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service 
            android:name=".MyService"
            ></service>
        
    </application>

</manifest>

demo源码:

http://download.csdn.net/detail/pangzaifei/6935855

你可能感兴趣的:(绑定服务,调用服务里的方法)