BroadcastReceiver无法正常工作,错误的Context(接听电话)?

时间:2013-01-04 15:49:26

标签: android broadcastreceiver sip

这是SipDemo的一部分(voip接听电话):

public class WalkieTalkieActivity extends Activity {
...
public IncomingCallReceiver callReceiver;
public SipManager manager = null;

@Override
public void onCreate(Bundle savedInstanceState) {

...

     IntentFilter filter = new IntentFilter();
    filter.addAction("android.SipDemo.INCOMING_CALL");
    callReceiver = new IncomingCallReceiver();
    this.registerReceiver(callReceiver, filter);


    initializeManager();
}

public void initializeManager() {
    initializeLocalProfile();
}

public void initializeLocalProfile() {

        SipProfile.Builder builder = new SipProfile.Builder(username, domain);
        builder.setPassword(password);
        me = builder.build();

        Intent i = new Intent();
        i.setAction("android.SipDemo.INCOMING_CALL");
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
        manager.open(me, pi, null);

和BroadCastReceiver

public class IncomingCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SipAudioCall incomingCall = null;
    try {

        SipAudioCall.Listener listener = new SipAudioCall.Listener() {
        };

        WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
        incomingCall = wtActivity.manager.takeAudioCall(intent, listener);

        incomingCall.answerCall(30);
    ...

        wtActivity.call = incomingCall;

它运行良好,但即使App在后台运行,我也需要能够接听电话。所以我尝试以其他方式实现广播接收器(不是在Activity中,而是在Manifest中)。删除了:

     IntentFilter filter = new IntentFilter();
    filter.addAction("android.SipDemo.INCOMING_CALL");
    callReceiver = new IncomingCallReceiver();
    this.registerReceiver(callReceiver, filter);

并在Manifest中添加

          <intent-filter>
             <action android:name="android.SipDemo.INCOMING_CALL"/>
        </intent-filter>

但是现在它不起作用,incomingCall总是为空。

在更改之前,BroadcastReceiver得到了

context ==  com.example.android.sip.WalkieTalkieActivity@4051c5e8

并在更改后

context == android.app.ReceiverRestrictedContext@4058ac48

也许这是问题所在,但是有人知道如何修复它吗?

1 个答案:

答案 0 :(得分:0)

您应该将SipProfile内容从您的活动中移出并转移到服务中。然后,您的BroadcastReceiver onReceive()可以启动该服务并让它处理该呼叫。 context onReceive()进入{{1}}是短暂的,你只能用它来做某些事情。