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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值