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;}}


另一种实现接口的service

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();}}


和service建立连接

 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或是数值来代表要执行的不同命令,从而实现其之间

的通信,这也是种不错的方法,值得学习,呵呵!


ok,以上是自己的工作总结,如有不足还请指出。




更多相关文章

  1. Android(安卓)蓝牙自动连接实现
  2. Android实现推送方式解决方案
  3. #Android(安卓)Day2
  4. android粗略获得程序运行时间的方法
  5. Android(安卓)源码分析 —— 从 Toast 出发
  6. Android(安卓)屏幕实现上下翻转
  7. Android局部布局替换实现
  8. Android消息机制Message消息池
  9. [转]Eclipse 查看Android(安卓)SDK源码

随机推荐

  1. 豆瓣FM(离线播放):旅途听音乐必备的Androi
  2. Android如何在字符串资源文件strings.xml
  3. 2D平面中关于矩阵(Matrix)跟图形变换的讲解
  4. Android自定义View(五)——带扫描线的View
  5. 推演鸿蒙、Android、iOS“三国杀”:谷歌无
  6. Android之“观察者模式”解析及实际应用:"
  7. State 状态模式在 Android(安卓)多弹窗的
  8. 关于android各种双卡手机获取imei,imsi的
  9. 2016年末,Android岗位BAT等大厂面试题知识
  10. Android(安卓)Studio不识别新安装的字体