Android One JSON发送Mutilple时间发送到服务器

时间:2016-02-05 09:58:31

标签: java android json service broadcastreceiver

我开发了一个应用程序,每1分钟向服务器发送一次数据。它每隔几分钟检查Internet连接,当互联网可用时,应用程序将数据发送到服务器,并在收到成功标记后删除发送数据的表行。 但问题是它在到达成功标记之前发送了一个JSON Mutliple时间来删除表行 示例:如果我发送json,如 {' amt':100} ,那么服务器会收到 {' amt&#39 ;:100} {' amt':100} {' amt':100} {' amt':100} ...... 多次如果服务器执行特定标签的添加操作,比如amt那么它添加所有标签值比tag的实际值多5倍。如果amt是100则服务器接收500

AlarmReceiver.java

 public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent background = new Intent(context, BackgroundService.class);
        context.startService(background);
    }
}

BackgroundService.java

    public class BackgroundService extends Service {
    int debug = 0;
    private boolean isRunning;
    private Context context;
    private Thread backgroundThread;
    Helper hp = new Helper(BackgroundService.this);
    private ArrayList<NameValuePair> params;
    Connect cn = new Connect();
    DatabaseConnector dbConnector = new DatabaseConnector(BackgroundService.this);
    JSONObject finalObj;
    JSONArray resultSet;
    AQuery aq = new AQuery(this);

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

        this.context = this;
        this.isRunning = false;
        this.backgroundThread = new Thread(myTask);
    }

    private Runnable myTask = new Runnable() {
        public void run() {
            // Do something here
            internet();
            stopSelf();
        }
    };

    @Override
    public void onDestroy() {
        this.isRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!this.isRunning) {
            this.isRunning = true;
            this.backgroundThread.start();
        }
        return START_STICKY;
    }

    private void internet() {
        finalObj = null;
        resultSet = null;
        if (hp.isonline() == true) {
            Log.e("dcn", "net connect");

            if (!dbConnector.isPayTableEmplty()) {
                //  Log.e("syncData", getPaymentJSON());
                hp.generateTxtOnSD(getPaymentJSON());
                Map<String, Object> params = new HashMap<>();
                params.put("bulk_pay_json", getPaymentJSON());
                String url = Urls.sync_url;
                aq.ajax(url, params, JSONObject.class, this, "jsonCallBack");
                Log.e("start", "start");

            } else {
                Log.e("syncData", "table is empty");
            }
        } else {
            Log.e("dcn", "net not connect");
        }
    }

    public void jsonCallBack(String url, JSONObject json, AjaxStatus status) {
        if (json != null) {
            if (debug == 1 || Urls.debug == true) {
                Log.e("result", json.toString());
                Log.e("url", url);
                Log.e("status", String.valueOf(status.toString()));
            }
            try {
                JSONObject jsonObject = new JSONObject(json.toString());
                if ("true".equals(jsonObject.getString("json_integrity"))) {
                    try {

                        String del_pay = dbConnector.deletePayMentTable();
                        hp.generateTxtOnSD(del_pay);
                        Log.d("result", "upload successfully");
                        showNotification();
                    } catch (Exception e) {
                    }
                } else {
                    Log.e("result", "error occured");
                }
            } catch (Exception e) {
                Log.d("Ex", e.getLocalizedMessage());
            }
        } else {
            new Helper(this).showToast(Urls.errors[1]);
        }


    }

    private String getPaymentJSON() {
        //get opid from SharedPrefrences
        ArrayList<String> opLn = hp.getOpId(BackgroundService.this);
        ArrayList<String> op = hp.getSaveOpInfo(BackgroundService.this);
        String opid;
        if (Integer.valueOf(opLn.get(0)) != 0) {
            opid = opLn.get(0);
        } else {
            opid = op.get(0);
        }

        // open DB for operation
        dbConnector.open();
        // get customer Table columns
        Cursor cursor = dbConnector.ListAllPayData();
        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) {
            int totalColumn = cursor.getColumnCount();
            JSONObject rowObject = new JSONObject();
            for (int i = 0; i < totalColumn; i++) {
                if (cursor.getColumnName(i) != null) {
                    try {
                        rowObject.put("conNo", cursor.getString(cursor.getColumnIndex(dbConnector.CONNO)));
                        rowObject.put("amount", cursor.getString(cursor.getColumnIndex(dbConnector.PAIDAMT)));
                        rowObject.put("contact", cursor.getString(cursor.getColumnIndex(dbConnector.CONTACT)));
                        rowObject.put("lineman", cursor.getString(cursor.getColumnIndex(dbConnector.LNID)));
                        rowObject.put("time", cursor.getString(cursor.getColumnIndex(dbConnector.TIME)));
                        rowObject.put("discount", cursor.getString(cursor.getColumnIndex(dbConnector.DISCOUNT)));
                        rowObject.put("rcpt", "");
                        rowObject.put("remark", cursor.getString(cursor.getColumnIndex(dbConnector.REMARK)));
                    } catch (Exception e) {
                        Log.d("TAG_NAME", e.getMessage());
                    }
                }
            }
            resultSet = new JSONArray();
            resultSet.put(rowObject);
            cursor.moveToNext();
        }
        try {
            finalObj = new JSONObject();
            finalObj.put("error", "false");
            finalObj.put("opid", opid);
            finalObj.put("data", resultSet);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        dbConnector.close();
        return finalObj.toString();

    }

}

呼叫广播接收器

private void BrodcastReceiverOn() {
    this.context = this;
    Intent alarm = new Intent(this.context, AlarmReceiver.class);
    boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
    if (alarmRunning == false) {
        pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 3000, pendingIntent);
    }
}

我使用AQuery进行发布和接收,因为不推荐使用http客户端

1 个答案:

答案 0 :(得分:0)

我认为这是因为你的IntervalMillis:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 3000, pendingIntent);

它以3秒为单位重复,单位为毫秒。

使用此

final long INTERVAL = 1 * 60 * 1000; // 1 minute
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), INTERVAL, pendingIntent);

希望这有帮助。