后台Android

时间:2015-12-18 07:47:37

标签: android android-asynctask sms android-sqlite contentobserver

我发现了一个非常奇怪的问题,似乎如下:

问题是,如果我继续与某人发送消息,那么我的应用程序将按顺序正确获取所有消息,但介于两者之间,如果有任何中断,如打开其他应用程序或搞乱设备中的其他东西,那么我的应用程序停止提取消息,在这种情况下,我们需要打开应用程序,它将再次开始提取消息,但跳过我们发送的外发消息,同时搞乱其他东西。

对于此提取短信,我使用自定义 SMSContentObserver 来获取短信。我正在存储最近的SMSID,以便每次都能获取新消息。

请帮助我,因为我无法弄清楚原因。

以下是一些代码段:

public class SMSContentObserver extends ContentObserver
    {
        public SMSContentObserver()
        {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange)
        {
            super.onChange(selfChange);
            Log.e("", "~~~~~~" + selfChange);
            try{

                appContactList = new ArrayList<HashMap<String, String>>();
                appContactList = databaseHandler.getAllappContact();
                if(appContactList.size() != 0){
                    try{
                        for (int i = 0; i < appContactList.size(); i++) {

                            strcontactname = appContactList.get(i).get("app_contact_name");
                            strcontactnumber = appContactList.get(i).get("app_contact_number");
                            strcontactid = appContactList.get(i).get("app_contact_id");
                            strsmsid = appContactList.get(i).get("app_contact_smsid");
                            strsmsdate = appContactList.get(i).get("app_contact_smsdate");
                            jsonArray = new JSONArray();

                            fetchInboxSmsIncoming(1, UserID, strcontactid, strcontactname ,strcontactnumber ,strsmsid ,strsmsdate ,"in");
                            fetchInboxSmsIncoming(2, UserID, strcontactid,strcontactname  , strcontactnumber,strsmsid ,strsmsdate ,"out");

                            if (Constants.isNetworkAvailable(mContext))
                            {
                                new SMSListenerNetwork().execute();
                            }
                            else
                            {
                                Toast.makeText(PhoneContactListActivity.this, Constants.msgNoInternet, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            }catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            }
        @Override
        public boolean deliverSelfNotifications()
        {
            return true;
        }
    }

fetchInboxSmsIncoming方法:

public void fetchInboxSmsIncoming(int type, String userID2, String strcontactid2,
            String strcontactname2, String strcontactnumber2, String strsmsid2,
            String strsmsdate2, String direction) {
        // TODO Auto-generated method stub
        try{
            JSONObject obj = null;
            databaseHandler = new DatabaseHandler(mContext);
            Uri uriSms = Uri.parse("content://sms");
            Cursor cursor = this.getContentResolver()
                    .query(uriSms,
                            new String[] { "_id", "address", "date", "body",
                            "type", "read" }, "type=" + type , null,
                            "date" + " COLLATE LOCALIZED ASC");

            if (cursor != null) {
                cursor.moveToLast();
                int i = 0;
                if (cursor.getCount() > 0) {

                    do {
                        Log.e("message.messageNumber",cursor.getString(cursor
                                .getColumnIndex("address")));

                        String incomingmessagefromSMS = processWord(cursor.getString(cursor.getColumnIndex("address")));
                        String incomingmessagefromPhone = processWord(strcontactnumber2);


                        if((incomingmessagefromSMS.contains(incomingmessagefromPhone)) && Integer.parseInt(cursor.getString(cursor.getColumnIndex("_id"))) > Integer.parseInt(strsmsid2)){
                            obj = new JSONObject();

                            //Toast.makeText(mContext, ""+incomingmessagefromSMS+" = " +incomingmessagefromPhone, Toast.LENGTH_LONG).show();
                            try {
                                String _id = cursor.getString(cursor.getColumnIndex("_id"));
                                String date =  cursor.getString(cursor.getColumnIndex("date"));
                                Long timestamp = Long.parseLong(date);    
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTimeInMillis(timestamp);
                                DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                obj.put("Date", formatter.format(calendar.getTime()));
                                String text = cursor.getString(cursor.getColumnIndexOrThrow("body"));
                                if(text.contains("\""))
                                    text = text.replace("\"", "");

                                obj.put("Text", text);
                                obj.put("UserID", userID2);
                                obj.put("ContactID",strcontactid2);
                                obj.put("Direction",direction);
                                if(i == 0){
                                    databaseHandler.insertappContact(strcontactid2, strcontactname2, strcontactnumber2, _id, formatter.format(calendar.getTime()));
                                    i = 1;
                                }
                                //Toast.makeText(mContext, "SMS"+obj, Toast.LENGTH_LONG).show();
                                jsonArray.put(obj);
                            } catch (IllegalArgumentException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                //Toast.makeText(mContext, "SMS Exception"+e, Toast.LENGTH_LONG).show();
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                //Toast.makeText(mContext, "SMS Exception"+e, Toast.LENGTH_LONG).show();
                            }

                        }
                        if(!cursor.getString(cursor
                                .getColumnIndex("address")).contains(strcontactnumber2)){
                            break;
                        }
                    } while (cursor.moveToPrevious());
                }
            }

            if(type == 1){
                Log.e("jsonArray 1 ",""+jsonArray);
            }else{
                Log.e("jsonArray 2",""+jsonArray);
            }
        }catch(Exception e){
            e.printStackTrace();
            //Toast.makeText(mContext, "SMS Exception"+e, Toast.LENGTH_LONG).show();
        }
    }

SMSListenerNetwork异步任务:

公共类SMSListenerNetwork扩展了AsyncTask {

    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Boolean doInBackground(Void... params) {

        try{

            String url = Constants.API_URL + "MessageConversation";
            List<NameValuePair> Parameters = new ArrayList<NameValuePair>();


            JSONObject obj = new JSONObject();
            String json = null;
            try {
                json = obj.put("users", jsonArray).toString();
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Parameters.add(new BasicNameValuePair("ConversationText",json ));
            Parameters.add(new BasicNameValuePair("DeviceID", androidToken));
            Parameters.add(new BasicNameValuePair("Token", securitytoken));

            ServerResponse response = jsonParser.postData(Parameters, url, Constants.API_RESPONSE_TYPE_JSON_OBJECT);
            Log.e("Parameters",""+Parameters);
            Log.e("url",""+url);
            System.out.println("Responce:"+response);
            Log.e("Responce",""+response);
            if(response.getStatus() == Constants.RESPONSE_STATUS_CODE_SUCCESS){
                JSONObject jsonObj = response.getjObj();

                System.out.println("jsonObjEmp:"+jsonObj);
                try {
                    response_message = jsonObj.getString("msg");
                    String status = jsonObj.getString("status");
                    if(status.equals("Success") || response_message.equals("Data is missing"))
                    {
                        return true;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return false;
    }
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);


        if(result)
        {
            try {
                if(jsonArray.isNull(0)){
                    Log.e("SMSRECEIVER", "SMS response_message "+"Data is missing");                        
                }else{
                    Log.e("SMSRECEIVER", response_message);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            Log.e("SMSRECEIVER", response_message);
        }
    }
}

请在此提供一些建议。

提前致谢。

1 个答案:

答案 0 :(得分:0)

也许您可以使用Service来运行它。或者尝试在Androidmanifest.xml中添加SMS Receiver。并在收到新短信时重新加载所有短信。