遇到下雨,写个简单例子,用于Activity与Service通信,之前也有一篇Binder的:点击。
例子非常简单:
MainActivity.java
package com.juno.testbind;import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;public class MainActivity extends Activity {public final static String EXTRA_KEY_DATA = "key_data";private TestService mTestService;private ServiceConnection mConnection = new ServiceConnection() {public void onServiceConnected(ComponentName className, IBinder service) {mTestService = ((TestService.TestBinder)service).getService();}public void onServiceDisconnected(ComponentName className) {if(mTestService != null){mTestService = null;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bindService();initView();}private void initView() {findViewById(R.id.button1).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {if (mTestService != null) {mTestService.doSomeThing();((TextView) findViewById(R.id.textView1)).setText(mTestService.getData());}}});}private void bindService() {Intent serviceIntent = new Intent(this, TestService.class);serviceIntent.putExtra(EXTRA_KEY_DATA, "data");bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(mConnection);}}
TestService.java
package com.juno.testbind;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 {private IBinder mBind = new TestBinder();public class TestBinder extends Binder {TestService getService() {return TestService.this;}}@Overridepublic IBinder onBind(Intent intent) {if (intent != null) {//get Extra DataString data = intent.getStringExtra(MainActivity.EXTRA_KEY_DATA);Toast.makeText(this, data, Toast.LENGTH_SHORT).show();}return mBind;}@Overridepublic boolean onUnbind(Intent intent) {return super.onUnbind(intent);}public void doSomeThing() {Toast.makeText(this, "do some thing and set text to TextView", Toast.LENGTH_LONG).show();}public String getData() {return "test";}
}
是Service得
<service android:name="com.juno.testbind.TestService" />