短信接收时立即更新我的活动

时间:2014-04-04 03:55:10

标签: android service sms broadcastreceiver

我想在我的主要活动中更新短信计数器,因为我实时收到新的短信。 我怎么能这样做?

代码在这里:

public class SMSBroadcast extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // code...
     }
   }

通过这种方式,我无法在不重新启动的情况下更新主活动的计数器。

感谢,

2 个答案:

答案 0 :(得分:2)

当收到任何新短信时,应用程序将需要在短信BroadcastReceiver和活动之间进行通信。为了通知活动新短信,您可以使用BroadcastReceiver进行自定义操作。

第1步:在活动中添加自定义操作:

public static String SMSRECEVID="custom.action.SMSRECEVEDINFO";

第2步:创建BroadcastReceiver以更新活动:

BroadcastReceiver smsReceived=new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(intent.getAction().equals(Your_Activity_Name.SMSRECEVID)){
                   // update UI of Activity
         }
    }
};

第3步:来自SMSBroadcast班级收到短信后发送广播:

public class SMSBroadcast extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

          Intent intent = new Intent();
          intent.setAction(Your_Activity_Name.SMSRECEVID);
          context.sendBroadcast(intent);
     }
   }

如果单独的类中的SMSBroadcast不是您项目的要求,则无需使用上述步骤,只需在活动中使用SMSBroadcast作为anonymous inner type,您希望在收到新SMS时更新UI元素。也不要忘记在Activity Stop上取消注册BroadcastReceiver或销毁

答案 1 :(得分:0)

可能是这个帮助你...

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    IncomingMessageReceiver.dbServices = new DatabaseServices(context);
    contact = new SaveNewContact(context);

    Bundle bundle = intent.getExtras();
    try {
        if (bundle != null) {
            Object[] objects = (Object[]) bundle.get("pdus");
            for (Object obj : objects) {
                SmsMessage currentMessage = SmsMessage
                        .createFromPdu((byte[]) obj);
                String phoneNumber = currentMessage
                        .getDisplayOriginatingAddress();
                if (contact.getCallerName(phoneNumber) != null)
                    phoneNumber = contact.getCallerName(phoneNumber);
                String msg_content = currentMessage.getDisplayMessageBody();
                // further logic of your application
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } 
}

和manifest.xml中的这个

    <receiver android:name="[your receiver]" >
        <intent-filter android:priority="100" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

   <uses-permission android:name="android.permission.RECEIVE_SMS" />
   <uses-permission android:name="android.permission.READ_SMS" />