当前位置: 代码迷 >> Android >> android数据通信形式
  详细解决方案

android数据通信形式

热度:9   发布时间:2016-05-01 10:06:21.0
android数据通信方式

?http://www.itkee.com/developer/detail-339e.html

?

?

? Register

主要用于service之间的通信;如底层有事件通知上层,一般用这个消息机制;

?

android数据通信方式(原创?禁止私自)

?

? ? Broadcast

主要用于APP层数据的通信,比如广播电量低,有耳机插入,进入/退出飞行模式等等事件; ??

? ?在应用程序代码中进行注册

?

android数据通信方式(原创?禁止私自)

?

特点:?在oncreat函数中进行广播机制的注册,当这个activity/service/application生命周期结束时,应该去注册unregisterReceiver;即响应这个广播action必须这个activity/service/application正处于活动状态中;

? ? ? ?在AndroidManifest.xml中进行注册

在packages包的AndroidManifest.xml中定义接受器,过滤挑选广播中的Action是否匹配,如下例:

<receiver android:name="SipBroadcastReceiver"><intent-filter><action android:name="com.android.phone.SIP_INCOMING_CALL" /><action android:name="com.android.phone.SIP_ADD_PHONE" /><action android:name="com.android.phone.SIP_REMOVE_PHONE" /><action android:name="android.net.sip.SIP_SERVICE_UP" /></intent-filter></receiver>

接收器为SipBroadcastReceiver,在类SipBroadcastReceiver中继承了Broadcast实现了onRecieve()方法;对广播的事件进行处理;
特点:应用程序结束了之后,该BroadcastReceiver同样会接受到广播,一直处于活动状态,

? ? Intent

主要用于activity之间消息的传递和activity与service之间消息的传递;不适合service于service之间消息的传递;?

? ? 显示intent

在构造intent时,就已经指定接收者是谁; 构造intent用的方法是:

  • public Intent()
  • public Intent(Context packageContext, Class<?> cls)
  • public Intent(String action, Uri uri,Context packageContext, Class<?> cls)

以OutgoingCallBroadcaster为例;OutgoingCallBroadcaster启动后;若是拨打电话且拨打的号码是紧急号码,则启动DialtactsActivity页面;

if (Intent.ACTION_CALL.equals(action)) {if (isPotentialEmergencyNumber) {......Intent invokeFrameworkDialer = new Intent();invokeFrameworkDialer.setClassName("com.android.contacts","com.android.contacts.DialtactsActivity");invokeFrameworkDialer.setAction(Intent.ACTION_DIAL);invokeFrameworkDialer.setData(intent.getData());invokeFrameworkDialer.putExtra(SUBSCRIPTION_KEY, mSubscription);startActivity(invokeFrameworkDialer);finish();return;}

? ? 隐式intent

在构造intent时,intent发送者不指定接收者,不关心接受者是谁;接收者在AndroidManifest.xml文件中通过intent fliter中声明自己可以接受哪些intent; 构造intent用的方法是:

  • public Intent(String action)
  • public Intent(String action, Uri uri)

以拨打一路电话为例:incallscreen中有个添加一路通话的按钮;按下这个按钮就会调用phoneutils中下面这个函数;并发出隐式的intent;

static void startNewCall(final CallManager cm) {......Intent intent = new Intent(Intent.ACTION_DIAL);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);......app.mContext.startActivity(intent);}

packages包下的androidmanifest.xml部分对应内容如下,因此启动了OutgoingCallBroadcaster这个activity;

<activity android:name="OutgoingCallBroadcaster"......<intent-filter><action android:name="android.intent.action.CALL" /><category android:name="android.intent.category.DEFAULT" /><data android:scheme="tel" /></intent-filter>......

? ? AIDL

AIDL应用于不同进程之间的通信,可以满足多线程的处理,因此可以同时接受并处理多个client端的请求;

?

android数据通信方式(原创?禁止私自)

?

服务器端继承了Ixxx.stub;Ixxx.stub: 实现的比较复杂,主要使用了IPC的机制给client端提供server端的实例,好供client端调用server端的函数;
以下为phone状态变化通过aidl方式传递消息的机制:

?

?

android数据通信方式(原创?禁止私自)
  相关解决方案