Android(安卓)service通信
16lz
2021-12-04
Android中的service通信可以通过context.bildService()方法,获取service实例来对其进行访问,具体做法如下;
新建一个Activity,命名ServiceDeamoActivity类;
package com.service.connect;import com.service.connect2.ConActivity;import com.service.simple.R;import android.app.Activity;import android.app.Service;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.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class ServiceDeamoActivity extends Activity {private MyService mservice=null; /** Called when the activity is first created. */private Button startService,stopService,bindService,unbindService;final String StartAction="com.service.action.MYSERVICE"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startService=(Button)findViewById(R.id.startButton); stopService=(Button)findViewById(R.id.stopButton); bindService=(Button)findViewById(R.id.bindButton); unbindService=(Button)findViewById(R.id.unbindButton); startService.setOnClickListener(startListener); stopService.setOnClickListener(stopListener); bindService.setOnClickListener(bindListener); unbindService.setOnClickListener(unbindListener); } private OnClickListener startListener=new OnClickListener(){@Overridepublic void onClick(View v) {Intent intent=new Intent();intent.setAction(StartAction);startService(intent);} }; private OnClickListener stopListener=new OnClickListener(){@Overridepublic void onClick(View v) {Intent intent=new Intent();intent.setAction(StartAction);stopService(intent);} }; private OnClickListener bindListener=new OnClickListener(){@Overridepublic void onClick(View v) {Intent intent=new Intent();intent.setAction(StartAction);bindService(intent,conn,Context.BIND_AUTO_CREATE);} }; private OnClickListener unbindListener=new OnClickListener(){@Overridepublic void onClick(View v) {Intent intent=new Intent();intent.setAction(StartAction);unbindService(conn);} }; protected void onDestroy() { unbindService(conn); }; private ServiceConnection conn=new ServiceConnection(){@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {mservice = ((MyService.MyBinder)service).getService();//得到了服务类对象就可以使用服务对象提供的方法了。但不可以在onCreate()方法里使用此对象,因为还没有初始化。mservice.dealData();Log.e("SERVICE", "connection success");Toast.makeText(ServiceDeamoActivity.this, "connection success", Toast.LENGTH_LONG).show();}@Overridepublic void onServiceDisconnected(ComponentName name) {mservice=null;Log.e("SERVICE", "discon");Toast.makeText(ServiceDeamoActivity.this, "connection failure", Toast.LENGTH_LONG).show();} }; }
服务类MyService类;
package com.service.connect;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 {private Binder mbinder = new MyBinder();@Overridepublic IBinder onBind(Intent intent) {Toast.makeText(MyService.this, "onBind......", Toast.LENGTH_LONG).show();return mbinder;}class MyBinder extends Binder{ public MyService getService(){ return MyService.this; }}void dealData(){Log.e("msg", "service deal");}public void onCreate(){Toast.makeText(MyService.this, "onCreate..", Toast.LENGTH_LONG).show();}public void onStart(Intent intent,int startId){Toast.makeText(MyService.this, "onStart....", Toast.LENGTH_LONG).show();}public void onDestroy(){Toast.makeText(MyService.this, "onDestroy...", Toast.LENGTH_LONG).show();}}
androidmainfest.xml
<service android:name="com.service.connect.MyService"><intent-filter><action android:name="com.service.action.MYSERVICE"/></intent-filter></service>
这样就可以建立起来与service之间的通信了,在建立绑定时还可以通过service实现接口去实现
例如;和service建立连接
class StudentConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {istudent=(IStudent)service;Log.e("msg", istudent.queryStudent());}@Overridepublic void onServiceDisconnected(ComponentName name) {istudent=null;}}
package com.service.connect2;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class StudentService extends Service {private IBinder buider=new MyBinder();@Overridepublic IBinder onBind(Intent intent) {return buider;}public String query(){return "hello connection";}private class MyBinder extends Binder implements IStudent{@Overridepublic String queryStudent() {return query();}}}
接口IStudent类
public interface IStudent {String queryStudent();}
这是通过实现接口建立连接的另一种方式。
以上可以算为一种通信方法,第二种方法通过Messenger发送消息实现
方法二;
新建ServiceMessage类
package com.service.connect;import android.app.Service;import android.content.Intent;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.os.Messenger;import android.widget.Toast;public class ServiceMessage extends Service{public final static int MSG_HELLO=1;// 建立Handler类继承来实现消息的处理 class MyHandler extends Handler{public void handleMessage(Message msg) {switch(msg.what){case MSG_HELLO:Toast.makeText(getApplicationContext(), "get the messag", 1000).show();break;default:Toast.makeText(getApplicationContext(), "default messag", 1000).show();break;}} } //创建一个Messenger类,并且将该类和内部类绑定 private final Messenger myMessager=new Messenger (new MyHandler());//绑定public IBinder onBind(Intent arg0) {Toast.makeText(getApplicationContext(), "onBind", Toast.LENGTH_SHORT).show();return myMessager.getBinder();}}
private ServiceConnection connection=new ServiceConnection(){ public void onServiceConnected(ComponentName name, IBinder service) {Toast.makeText(mContext, "onServiceConnected ", 1000).show();messenger=new Messenger(service);}public void onServiceDisconnected(ComponentName name) {messenger=null;} };创建以及发送消息
Message msg=Message.obtain(null, ServiceMessage.MSG_HELLO, 0, 0);try {messenger.send(msg);} catch (RemoteException e) {e.printStackTrace();}这是一种通过发送不同的消息来对事件进行相应的处理。
方法三,比较简单利用service生命周期,context.startService();intent.setAction(a1);既是只要service创建就会执行一次oncreate()但是会多次调用onStar()方法,
在此方法内可以通过获取不同的action来执行不同的方法,
@Overridepublic void onStart(Intent intent, int startId) {if(intent!=null){if("action1".equals(intent.getAction())){}else if("action2".equals(intent.getAction())){}else{}}super.onStart(intent, startId);}
方法四;使用内部广播机制。例如Activity与service之间通信,可以分别使用两个内部类广播相互发送不同的action或是数值来代表要执行的不同命令,从而实现其之间
的通信,这也是种不错的方法,值得学习,呵呵!
更多相关文章
- Android(安卓)蓝牙自动连接实现
- Android实现推送方式解决方案
- #Android(安卓)Day2
- android粗略获得程序运行时间的方法
- Android(安卓)源码分析 —— 从 Toast 出发
- Android(安卓)屏幕实现上下翻转
- Android局部布局替换实现
- Android消息机制Message消息池
- [转]Eclipse 查看Android(安卓)SDK源码