我目前在Android中有一个服务,它是一个示例VOIP客户端,因此它会侦听SIP消息,如果它收到一个,它会启动一个带有UI组件的活动屏幕.
然后,以下SIP消息确定要在屏幕上显示活动的内容.例如,如果它的来电将显示接听或拒绝或拨出电话,它将显示拨号屏幕.
在那一刻,我使用Intents让Activity知道它应该显示的状态.
一个例子如下:
Intent i = new Intent();
i.setAction(SIPEngine.SIP_TRYING_INTENT);
i.putExtra("com.net.INCOMING", true);
sendBroadcast(i);
Intent x = new Intent();
x.setAction(CallManager.SIP_INCOMING_CALL_INTENT);
sendBroadcast(x);
Log.d("INTENT SENT", "INTENT SENT INCOMING CALL AFTER PROCESSINVITE");
Run Code Online (Sandbox Code Playgroud)
因此,活动将为这些意图注册广播接收器,并根据收到的最后意图切换其状态.
示例代码如下:
SipCallListener = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(SIPEngine.SIP_RINGING_INTENT.equals(action)){
Log.d("cda ", "Got RINGING action SIPENGINE");
ringingSetup();
}
if(CallManager.SIP_INCOMING_CALL_INTENT.equals(action)){
Log.d("cda ", "Got PHONE RINGING action");
incomingCallSetup();
}
}
};
IntentFilter filter = new IntentFilter(CallManager.SIP_INCOMING_CALL_INTENT);
filter.addAction(CallManager.SIP_RINGING_CALL_INTENT);
registerReceiver(SipCallListener, filter);
Run Code Online (Sandbox Code Playgroud)
这可行,但它似乎不是非常有效,Intents将获得广播系统范围和Intents必须为不同状态触发似乎它可能变得低效,我必须包括更多,以及增加复杂性.
所以我想知道是否有更高效,更清洁的方法来做到这一点?
有没有办法让Intents只在应用程序内部广播?
回调是一个更好的主意吗?如果是这样,为什么以及以何种方式实施它们?
将服务绑定到vs将其绑定到绑定是否有任何根本区别.我想将服务绑定到a,因为我想在Application中保留一些全局状态/数据,而不是在我的所有活动中复制它.android.app.Activityandroid.app.ApplicationApplication
谢谢.
我有一个服务组件(我所有应用程序的常见任务),可以由任何应用程序调用.我试图从所有活动中访问服务对象,我注意到创建服务的那个[startService(intent)]具有正确的信息.但是休息并不需要信息.我的代码如下:
// Activity.java
public void onCreate(Bundle savedInstanceState) {
...
Intent intent = new Intent (this.context, Service.class) ;
this.context.startService(intent) ;
this.context.bindService(intent, this, Context.BIND_AUTO_CREATE) ;
...
String result = serviceObj.getData() ;
}
public void onServiceConnected(ComponentName name, IBinder service) {
serviceObj = ((Service.LocalBinder)service).getService();
timer.scheduleAtFixedRate(task, 5000, 60000 ) ;
}
// Service.java
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
Service getService() {
return Service.this;
}
}
public void onCreate() {
super.onCreate();
context = getApplicationContext() ;
}
public void …Run Code Online (Sandbox Code Playgroud)