我创建了一个服务,该服务在从某些号码接收到SMS后启动Activity。

有2个活动SuccessFailure

两项活动仅成功打开1次,在第二次迭代中,当我再次发送SMS时,它不会影响活动屏幕。

它将保持打开状态,即当前的“活动”屏幕,并且不会根据条件进行更改。

我在网上搜索了此内容,发现了各种解决方案,但是似乎在这里没有任何作用,我尝试更改标志,但是它只允许服务类中的1个标志,如果我选择其他Flags,则会出现以下错误消息。

StartActivity from outsite an activity context requires the FLAG_ACTIVITY_NEW_TASK flag

这是我编写的服务类。请检查并指导我在这里做错了什么。

谢谢

public class IncomingSms extends BroadcastReceiver {

    final SmsManager sms = SmsManager.getDefault();
    int duration = Toast.LENGTH_LONG;

    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();

                    if(senderNum.equals("345"))
                    {
                        Intent successScreen= new Intent(context, SuccessActivity.class);
                        successScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(successScreen);

                    }
                    else if(senderNum.equals("3450") || senderNum.equals("3451") || senderNum.equals("3452")){

                        Intent alertActivity = new Intent(context, FailureActivity.class);
                        alertActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(alertActivity);
                  }

最佳答案

尝试用以下代码替换您的代码:

 if(senderNum.equals("345"))
                    {
                        Intent successScreen= new Intent(context, SuccessActivity.class);
                        successScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        successScreen.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
successScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        context.startActivity(successScreen);

                    }
                    else if(senderNum.equals("3450") || senderNum.equals("3451") || senderNum.equals("3452")){

                        Intent alertActivity = new Intent(context, FailureActivity.class);
                        alertActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  successScreen.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
successScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        context.startActivity(alertActivity);
                  }

10-06 13:03
查看更多