我在activity中调用后台服务给手机客户端发送一条短信,客户端有一个BroadcastReceive接受短信,并获取短信信息,将获得的信息返回给activity显示,activity的代码省,BroadcastReceive的代码如下:
@Override
public void onReceive(Context context, Intent intent) { String phoneNum = ""; String verifyCode = ""; if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){ //建构一字符串 StringBuilder stringBuilder = new StringBuilder(""); //接收由Intent传来的数据 Bundle bundle = intent.getExtras(); //判断Intent是有数据 if (bundle != null) { //pdus为 android内置短信参数 identifier,通过bundle.get("")返回一包含pdus的对象 Object[] smsObject = (Object[]) bundle.get("pdus"); //构造短信对象 SmsMessage[] messages = new SmsMessage[smsObject.length]; for (int i = 0; i<smsObject.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) smsObject[i]);} for (SmsMessage currentMessage : messages) { //发送人的电话号码 phoneNum = currentMessage.getDisplayOriginatingAddress(); //信息内容 stringBuilder.append(currentMessage.getDisplayMessageBody()); } } if(phoneNum == null || phoneNum.equals("")) return ; String message = stringBuilder.toString(); if(message ==null || message.equals("") ||!message.contains("sgcc.eshop")) return ; verifyCode = message.substring(message.indexOf(":")+1,message.indexOf(":")+5); //返回主Activity Intent myIntent = new Intent(context, SmsCheckActivity.class); //定义一个Bundle Bundle mbundle = new Bundle(); //将短信信息存入自定义的bundle内 mbundle.putString("phoneNum",phoneNum); mbundle.putString("verifyCode",verifyCode); //将自定义bundle写入Intent中 myIntent.putExtras(mbundle); //设置Intent的Flag以一个全新的task来运行 myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //跳转到主界面 context.startActivity(myIntent); } }
上面这种写法的弊端是:他是打开一个新的activity实例,而前面已经启动的实例任然存在,这就导致在一个任务里有多个这个activity的实例,后面那个实例没法取到前面的变量值,所以我们想调用原来的activity实例。
调用已经启动的activity有两种方式:1.修改activity的启动模式为singleTop,2.修改Intent.FLAG_ACTIVITY_NEW_TASK为intent.FLAG_ACTIVITY_CLEAR_TOP
但是上面两种方式都有问题
第一种的问题:当用上面的代码传值时,在activity中没法获得bundle的值。
第二种的问题:在activity外面(BroadcastReceive和service)调用已存在的activity只能用Intent.FLAG_ACTIVITY_NEW_TASK这个标志。
所以为了将BroadcastReceive中的值传到已经存在的activity中,只能换一种方式,中间加一层service层,通过service注册BroadcastReceive,activity与service进行通信,详情请参看下一篇文章
|
|