Android的Service与Activity通信

受益于从图书馆借过来的书,今天再学习了Android的Service与Activity的通信,特列出如下代码:

 

main.xml 文件内容如下:

<?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:id = "@+id/text"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:text="startservice" 
android:id="@+id/Button01" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<Button android:text="stopservice" 
android:id="@+id/Button02" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<Button android:text="bindservice" 
android:id="@+id/Button03" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<Button android:text="unbindservice" 
android:id="@+id/Button04" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
</LinearLayout>

 

AndroidManifest.xml文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.demo.myServiceComm"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".myServiceComm"
                  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:enabled="true" android:name = ".MyService"/>
    </application>


</manifest> 


 

MyService.java文件内容如下:

package com.demo.myServiceComm;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

public class MyService extends Service {

	//定义一个TAG标签
	private static final String TAG = "MyService";
	
	//这里定义一个Binder类,用在onBind()方法里。
	//这样Activity那边可以获取得到
	private MyBinder mBinder = new MyBinder();
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Log.e(TAG,"start IBinder~~~");
		return mBinder;
	}
	
	//当服务第一次创建时调用该方法
	public void onCreate(){
		Log.d(TAG,"onCreate~~~");
		super.onCreate();
	}
	
	//当服务销毁时调用该方法
	public void onDestroy(){
		Log.d(TAG,"onDestroy~~~");
		super.onDestroy();
	}
	
	//当服务开始时调用该方法
	public void onStart(Intent intent,int startId){
		Log.d(TAG,"onStart~~~!");
		super.onStart(intent,startId);
	}
	
	//
	public boolean onUnbind(Intent intent){
		Log.e(TAG, "start onUnbind~~~");
		return super.onUnbind(intent);
	}

	//获取当前系统时间函数
	public String getSystemTime(){
		Time t = new Time();
		t.setToNow();
		t.format3339(true);
		return t.toString();
	}
	
	public class MyBinder extends Binder{
		MyService getService(){
			return MyService.this;
		}
	}
}


 

myServiceComm.java文件内容如下:

package com.demo.myServiceComm;

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.Button;
import android.widget.TextView;

public class myServiceComm extends Activity {
	
	private MyService mMyService;
	private TextView mTextView;
	private Button startserviceBtn;
	private Button stopserviceBtn;
	private Button bindserviceBtn;
	private Button unbindserviceBtn;
	
	//定义上下文对象
	private Context mContext;
	
	private ServiceConnection mServiceConnection = new ServiceConnection()
	{

		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mMyService = ((MyService.MyBinder)service).getService();
			mTextView.setText("I am frome service :"
					+ mMyService.getSystemTime());
		}

		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}
		
	};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupViews();
    }
    
    public void setupViews()
    {
    	mContext = this;
    	
    	//元素绑定
    	mTextView = (TextView)findViewById(R.id.text);
    	startserviceBtn = (Button)findViewById(R.id.Button01);
    	stopserviceBtn = (Button)findViewById(R.id.Button02);
    	bindserviceBtn = (Button)findViewById(R.id.Button03);
    	unbindserviceBtn = (Button)findViewById(R.id.Button04);
    	
    	//新建service意图
    	final Intent serviceIntent = new Intent(this,MyService.class);
    	
    	//添加监听接口以及消息处理函数
    	startserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//打开服务
				mContext.startService(serviceIntent);
			}
    	});
    	
    	stopserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//停止服务
				mContext.stopService(serviceIntent);
			}
    	});
    	
    	bindserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//绑定服务
				mContext.bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
			}
    	});
    	
    	unbindserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//撤销绑定服务
				mContext.unbindService(mServiceConnection);
			}
    		
    	});
    }
}



 

### AndroidService Activity通信机制 在 Android 开发中,`Service` `Activity` 是两个重要的组件。它们可以通过多种方式进行交互通信。以下是几种常见的通信方式及其示例。 #### 1. 使用 `startService()` 启动服务并传递数据 通过调用 `startService()` 方法可以启动一个后台服务,并向其发送消息或指令。这种方式适用于不需要长期绑定的服务场景。 - **Activity 调用代码** ```java Intent intent = new Intent(this, MyService.class); intent.putExtra("key", "value"); startService(intent); // 启动服务并向其传递数据 ``` - **Service 接收代码** ```java @Override public int onStartCommand(Intent intent, int flags, int startId) { String value = intent.getStringExtra("key"); // 获取来自Activity的数据 Log.d("MyService", "Received data from Activity: " + value); return START_STICKY; } ``` 上述方法展示了如何通过 `Intent` 将数据从 `Activity` 发送到 `Service`[^1]。 --- #### 2. 使用 `bindService()` 绑定到服务并通信 当需要更紧密的耦合关系时,可以使用 `bindService()` 来建立连接。这通常用于需要频繁交互的情况。 - **定义接口供回调使用** ```java // 定义AIDL或者Binder对象作为桥梁 public class LocalBinder extends Binder { public MyService getService() { return MyService.this; // 返回当前Service实例 } } private final IBinder binder = new LocalBinder(); ``` - **重写 `onBind()` 方法返回 Binder 对象** ```java @Override public IBinder onBind(Intent intent) { return binder; // 提供给客户端访问 } ``` - **Activity 链接至 Service 并获取实例** ```java private MyService myBoundService; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { LocalBinder localBinder = (LocalBinder) service; myBoundService = localBinder.getService(); // 得到Service实例 } @Override public void onServiceDisconnected(ComponentName name) {} }; Intent bindIntent = new Intent(this, MyService.class); bindService(bindIntent, connection, Context.BIND_AUTO_CREATE); // 建立链接 ``` 此部分描述了如何利用 `bindService()` 实现双向通信以及资源共享的功能[^3]。 --- #### 3. 结合 `Messenger` 或者 AIDL 实现跨进程通信 如果目标是支持多线程操作或者是远程过程调用(RPC),则可以选择基于 `Handler` 的 `Messenger` 类型或是更为复杂的 AIDL 文件来完成 IPC(Inter-process Communication)。这里仅展示简单的 Messenger 方案: - **创建 Handler 处理消息队列** ```java class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SET_VALUE: int newValue = msg.arg1; break; default: super.handleMessage(msg); } } } final Messenger messenger = new Messenger(new IncomingHandler()); ``` - **注册该信使于 Service 内部** ```java @Override public IBinder onBind(Intent intent) { return messenger.getBinder(); // 替代传统binder模式 } ``` 以上片段说明了借助 `Messenger` 可简化某些特定场合下对于复杂同步逻辑的需求[^2]。 --- ### 总结 综上所述,在实际开发过程中可以根据具体需求选取合适的方案来进行 Android 应用内的组件间通讯工作。无论是单次性的任务委派还是持续性的状态共享都可以找到对应的解决办法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值