如何在Android前台活动和后台接收短信?

时间:2014-03-25 06:35:21

标签: android sms broadcastreceiver

我正在收到短信。我希望收到短信后立即更新ListView或活动位于前台。我已成功完成此操作,因为我已分别在OnResume和OnPause中注册和取消注册接收器,如代码所示:

BroadcastReceiver IncomingSMS =  new BroadcastReceiver() {

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

            final Bundle bundle = intent.getExtras();


            if (bundle != null) {

                //—retrieve the SMS message received—
                Object messages[] = (Object[]) bundle.get("pdus");
                SmsMessage smsMessage[] = new SmsMessage[messages.length];

                for (int n = 0; n < messages.length; n++) {
                    smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
                    timestamp = smsMessage[n].getTimestampMillis();

                    number = smsMessage[n].getOriginatingAddress();
                    body += smsMessage[n].getDisplayMessageBody();
                    display_name = Util.getContactName(context, number);
                    DBmanager = new DbManager(context);
                    cursor = DBmanager.Return_All_Contacts();
                    String [] contactArr = showcontactsInfo(cursor);
                    Toast.makeText(context, contactArr[0]+"", 3000).show();
                    if(contactArr.length==0)
                    {}
                    else{
                        for(int i= 0;i<=contactArr.length;i++)
                        {

                            abortBroadcast();

                        }
                        blockMessage(context);

                    }
                }
            }

        }
        catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }
    }};

@Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(IncomingSMS);
    }

    @Override
    protected void onResume() {
        //registerReceiver(IncomingSMS, null);
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(IncomingSMS, filter);
        updateList();

    }

我还在Manifest文件中注册了Receiver,当Activity在后台时接收短信。如果Activity在后台,我切换到该Activity,然后ListView正常更新,但如果Activity在前台,则ListView已更新数据两次。最有可能的是,当Activity在前景中时,触发两个Receiver,即前景中的一个和清单中的第二个。我该怎么办呢????我希望前台活动更新只接收一次短信。 这就是我在清单中注册Receiver并在java类中使用的方法:

public class IncomingSMS extends BroadcastReceiver {

Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
String msg="";
Cursor cursor;
String display_name;
String flag;
ChatActivity obj_chat;

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

        final Bundle bundle = intent.getExtras();


            if (bundle != null) {

                //—retrieve the SMS message received—
                Object messages[] = (Object[]) bundle.get("pdus");
                SmsMessage smsMessage[] = new SmsMessage[messages.length];

                for (int n = 0; n < messages.length; n++) {
                    smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
                    timestamp = smsMessage[n].getTimestampMillis();
                    number = smsMessage[n].getOriginatingAddress();
                    body += smsMessage[n].getDisplayMessageBody();
                    display_name = Util.getContactName(context, number);
                    DBmanager = new DbManager(context);
                    cursor = DBmanager.Return_All_Contacts();
                    String [] contactArr = showcontactsInfo(cursor);
                Toast.makeText(context, contactArr[0]+"", 3000).show();
                    if(contactArr.length==0)
                    {}
                    else{
                    for(int i= 0;i<=contactArr.length;i++)
                    {

                        abortBroadcast();

                            }
                    blockMessage(context);

                    }
                        }
                    }

                }
        catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }

            } // end for loop
        // bundle is null




    private String[] showcontactsInfo(Cursor cursor) {
        String[] contact = new String [cursor.getCount()];
        int i= 0;
        while(cursor.moveToNext()){
            contact[i] = cursor.getString(1);
            i++;
        }
        return contact;
    }
    private void blockMessage(Context context) {

        // instantiate DbMNager object to insert sms in database
        //formating receiving time:
        //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");

        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d  HH:mm:ss a");
        String formatedTime = formatter.format(timestamp);
        flag = "0";
        DBmanager= new DbManager(context);
        DBmanager.open();
        DBmanager.Insert_sms_data(formatedTime ,display_name,body,flag);
        DBmanager.close();
        obj_chat = new ChatActivity();
        obj_chat.updateList();
        msg+= "SMS from " + number + " \n";
        msg += body + " \n";
        msg += formatedTime + " \n";
        msg += flag + " \n";
        Log.i("SmsReceiver", "senderNum: "+ display_name + "; message: " + body);
        Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
        //Toast.makeText(context, "New message received in Discrete", Toast.LENGTH_LONG).show();
    }    
}

enter image description here

0 个答案:

没有答案