如何使用传入短信刷新前台活动?

时间:2014-03-26 06:24:34

标签: android listview sms broadcastreceiver

我正在开发短信应用程序。我在清单中声明了接收者如下:

<receiver android:name="com.android.discrete.main.IncomingSMS" >
        <intent-filter android:priority="1000" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
broadcastReceiver的

类如下:

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();

        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();
    }    
}

这很好,因为我可以接收短信并将其保存在SQLite数据库中。 现在我有另一个活动有ListView,我想在收到新短信并且活动在前台时立即更新。代码如下:

public class ChatActivity extends Activity {

Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
//String msg="";
Cursor cursor;
String display_name;
//String flag;
static MyListAdapter adapter;
static ArrayList<String> item_id;
static ArrayList<String> item_phone_num;
static ArrayList<String> item_msg_body;
static ArrayList<String> item_time;
static ArrayList<String> item_flag;
static ArrayList<String> items;
private Button btn_send;
DbManager manager;
Cursor Cursor,cursor_new;
//ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";
ListView lv_chat;
int position;
String[] from = new String[]{"Message_body","Time"};
int[] toIDs = new int[]{R.id.msg_body,R.id.time};
BroadcastReceiver IncomingSMS =  new BroadcastReceiver() {

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Bundle bundle = getIntent().getExtras();
        contact_for_chat = bundle.getString("contact_name");
        contact_for_chat = contact_for_chat.replace(" ", "");
        contact_no = Util.getContactNumber(contact_for_chat, ChatActivity.this);


        Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
        manager = new DbManager(this);
        Cursor = manager.Return_SMS(contact_for_chat);

        c = Calendar.getInstance();
        sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
        time = sdf.format(c.getTime());


        item_id = new ArrayList<String>(Cursor.getCount());
        item_phone_num = new ArrayList<String>(Cursor.getCount());
        item_msg_body = new ArrayList<String>(Cursor.getCount());
        item_time = new ArrayList<String>(Cursor.getCount());
        item_flag = new ArrayList<String>(Cursor.getCount());
        findViews();
        showList();
        //setActionBar();

        btn_send.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                SendSMS();
                showList();
                //updateList() ;

            }
        });

        lv_chat.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,
                    long arg3) {
                Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
                int itemId = Integer.valueOf(String.valueOf(position));
                Cursor.moveToPosition(itemId);
                int messageId = Cursor.getInt(0);
                deleteMessage(messageId);
            }});
    }

    private void showList() {

        showEvents(Cursor);
        adapter = new MyListAdapter(this,R.layout.activity_chat, Cursor, from, 
                toIDs);

        lv_chat.setAdapter(adapter);
        //updateList() ;


    }

    private void findViews() {
        et_chat = (EditText)findViewById(R.id.et_chat);
        btn_send = (Button)findViewById(R.id.button1);
        lv_chat = (ListView)findViewById(R.id.list);
        lv_chat.setDivider(this.getResources().getDrawable(android.R.color.transparent));

    }

    protected void SendSMS() {

        SmsManager sms_manager = SmsManager.getDefault();
        message_body = et_chat.getText().toString();
        ArrayList<String> parts = sms_manager.divideMessage(message_body);
        sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
        flag = "1";
        manager.Insert_sms_data(time, contact_for_chat, message_body,flag);

        if(message_body.length()>0)
        {
            et_chat.setText("");
        }
        updateList() ;
}
private void showEvents(Cursor cursor) {

        int i=0;
        while (cursor.moveToNext()) {
            item_id.add(i+"");
            item_time.add(cursor.getString(1));
            item_msg_body.add(cursor.getString(3));
            item_phone_num.add(cursor.getString(2));
            item_flag.add(cursor.getString(4));
            i++;
        }

    }
    public class MyListAdapter extends SimpleCursorAdapter {

        Cursor myCursor;
        Context myContext;

        public MyListAdapter(Context context, int layout,
                Cursor c, String[] from, int[] to) {
            super(context, layout, c, from, to);
            myCursor = c;
            myContext = context;
        }

        public int getCount() {
            return item_msg_body.size();
        }

        public Object getItem(int position) {
            return item_msg_body.get(position);
        }

        public long getItemId(int position) {
            return item_msg_body.get(position).hashCode();
        }

        public View getView(final int position, View arg1, ViewGroup arg2) {

            View v = arg1;
            ViewHolder holder = null;
            if (v == null) {

                LayoutInflater layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = layoutinf.inflate(R.layout.row_chat, null);
                holder = new ViewHolder();

                //  holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
                holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
                holder.tv_time = (TextView) v.findViewById(R.id.time);

                v.setTag(holder);
            } else {
                holder = (ViewHolder) v.getTag();
            }

            if(item_flag.get(position).equals("1"))
            {
                RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);

                RelativeLayout.LayoutParams dateparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                dateparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                dateparams.addRule(RelativeLayout.BELOW, R.id.msg_body);

                holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
                holder.tv_sms_body.setLayoutParams(params);
                holder.tv_time.setLayoutParams(dateparams);
            }
            else if(item_flag.get(position).equals("0"))
            {
                holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);

            }

            //holder.tv_contact.setText("" + item_phone_num.get(position));
            holder.tv_sms_body.setText(item_msg_body.get(position));
            holder.tv_time.setText(item_time.get(position));

            return v;
        }
    }

    public class ViewHolder {

        private TextView tv_contact;
        private TextView tv_sms_body;
        private TextView tv_time;

    }

    public void updateList() 
    {
        item_id.clear();
        item_time.clear();
        item_msg_body.clear();
        item_phone_num.clear();
        item_flag.clear();
        Cursor = manager.Return_SMS(contact_for_chat);
        showEvents(Cursor);
        adapter = new MyListAdapter(this,R.layout.activity_chat, Cursor, from, 
                toIDs);
        lv_chat.setAdapter(adapter);

    }

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

    @Override
    protected void onResume() {
        //registerReceiver(IncomingSMS, null);

        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(IncomingSMS, filter);
        updateList();
        super.onResume();
    }

问题是,当我收到短信时,ListView会自动更新,但结果不符合预期。当收到短信时,它会将之前的短信与新短信相结合,即在此图片中查看fisrt短信是“嗨”第二短信是“如何你是“但它将短信合并为”你好,你好吗?是什么原因 ?如何修复???? 任何帮助将不胜感激 。 enter image description here

1 个答案:

答案 0 :(得分:1)

我建议您使用 Cursor Loader这里有一些教程: - http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html
http://www.vogella.com/tutorials/AndroidSQLite/article.html

所以你的应用程序设计是这样的: -

(新短信)----&gt; (广播接收器插入db)-----&gt; (游标加载器将刷新您的前台活动)