1

在我的 Android 应用程序中,我想拨打电话作为对特殊 SMS 的响应。所以我创建了一个应用程序来监听即将到来的消息并因为特定的短信而拨打电话。该应用程序可以按预期在模拟器上运行,但是当我尝试在具有 Android 4.0.3 的选项卡上运行应用程序时,它会在开始调用后立即结束调用。这是我使用的代码。

public class MainActivity extends Activity {
public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
String msgBody;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    IntentFilter filter = new IntentFilter(SMS_RECEIVED);
    registerReceiver(broadcastReceiver, filter);
}

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
         // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){

                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){

                }
            }
        }

        }
        Toast.makeText(getApplicationContext(), msgBody, Toast.LENGTH_LONG).show();

        if(msgBody.equals("CALL")){
            Intent myIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "XXXXXXXXXXX"));;
            myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
            context.startActivity(myIntent);
    }
};


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}    
}

我添加了以下权限:

 READ_SMS
 RECEIVE_SMS
 CALL_PHONE

这里有什么问题?请帮我。

先谢谢了。

4

1 回答 1

1

创建另一个活动,例如 CallActivity,从您的接收器开始此活动,例如

 Intent i=new Intent();
 i.setClass(context,callActivity.class);
 i.putExtra("number","phone_number");
 i.setFlags(Intent.Flag_Activity_newTask);
 context.startActivity(i);

现在在 CallActivity 的 onCreate() 方法中,只需启动呼叫电话意图:

  Intent myIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "XXXXXXXXXXX"));;
  startActivity(myIntent);
于 2013-10-05T14:18:42.983 回答