Android 使用代码发送SMS会发送重复的SMS

Android 使用代码发送SMS会发送重复的SMS,android,Android,我只是从一个小项目开始安卓。我正在努力做到以下几点: STEP 1. get the response from an url [https://client.itscholarbd.com/getsmsdata] STEP 2. send sms based on the data received from step 1 STEP 3. DELETE the data which is processed. i.e. sms is sent. this is done by DELETE

我只是从一个小项目开始安卓。我正在努力做到以下几点:

STEP 1. get the response from an url [https://client.itscholarbd.com/getsmsdata]
STEP 2. send sms based on the data received from step 1 
STEP 3. DELETE the data which is processed. i.e. sms is sent. this is done by DELETE request with ID
STEP 4. REPEAT from STEP 1. 
这是我的密码:

package com.pkappstudio.smsv20;

import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class BackgroundService extends Service {

    private static final String SMS_SENT_ACTION = "com.pkappstudio.smsv20.SMS_SENT";
    private static final String EXTRA_NUMBER = "number";
    private static final String EXTRA_MESSAGE = "message";
    private RequestQueue requestQueue;
    private SmsManager smsManager;
    private BroadcastReceiver resultsReceiver;
    private boolean start = true;
    private String base_url = "https://client.itscholarbd.com";

    @Override
    public void onCreate() {
        super.onCreate();

        smsManager = SmsManager.getDefault();
        resultsReceiver = new SmsResultReceiver();
        IntentFilter intentFilter = new IntentFilter(SMS_SENT_ACTION);
        registerReceiver(resultsReceiver, intentFilter);

        requestQueue = Volley.newRequestQueue(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String macAddress = intent.getStringExtra("MAC");

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_ID)
                .setContentTitle("SMS v2.0-Service Running")
                .setContentText(macAddress)
                .setSmallIcon(R.drawable.ic_message)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1, notification);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                //our action starts here
                if (start) {
                    jsonParse();
                }
                handler.postDelayed(this, 8000);
            }
        }, 8000);
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(resultsReceiver);
    }

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


    private void jsonParse() {
        String url = base_url+"/getsmsdata?mac=" + App.MAC_ADDRESS;
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray array = response.getJSONArray("response");
                    getData(array);
                    Log.i("reposnse", array.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("JSONDATA", error.toString());
            }
        });
        requestQueue.add(request);
    }

    private void getData(JSONArray array) {

        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject object = array.getJSONObject(i);

                String string = object.getString("phone");
                int id = Integer.parseInt(object.getString("id"));
                int user_id = Integer.parseInt(object.getString("user_id"));
                String message = object.getString("message");

                double smsLength = message.length();
                double perSmsLength = 160;
                double FakeQuantity = smsLength / perSmsLength;
                int quantity = (int) Math.ceil(FakeQuantity);
                start = false;
                Log.i("debug", message);
                sendNextMessage(id, string, message, quantity, user_id);
                deleteFromDB(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void deleteFromDB(int id) {
        String url = base_url+"/deletedata?id=" + id + "&mac=" + App.MAC_ADDRESS;
        StringRequest request = new StringRequest(Request.Method.DELETE, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("resonse", response);
                jsonParse();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("resonse", error.toString());
            }
        });
        requestQueue.add(request);
    }

    private void sendStatusToServer(JSONArray array) {
        String url = base_url+"/addsmslog?mac=" + App.MAC_ADDRESS;
        JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, array, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.i("response", response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("response", error.toString());
            }
        });
        requestQueue.add(request);
    }

    private void sendNextMessage(int id, String number, String message, int quantity, int user_id) {

        int requestCode = id + Integer.parseInt(number);
        Intent sentIntent = new Intent(SMS_SENT_ACTION);

        sentIntent.putExtra(EXTRA_NUMBER, number);
        sentIntent.putExtra(EXTRA_MESSAGE, message);
        sentIntent.putExtra("quantity", quantity);
        sentIntent.putExtra("user_id", user_id);
        sentIntent.putExtra("id", id);
        PendingIntent sentPI = PendingIntent.getBroadcast(this,
                requestCode,
                sentIntent,
                PendingIntent.FLAG_ONE_SHOT);

        // Send our message.
        Log.i("dValues", id + " " + number + " " + message);
        smsManager.sendTextMessage(number, null, message, sentPI, null);
    }


    private class SmsResultReceiver extends BroadcastReceiver {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get the result action.
            String action = intent.getAction();

            // Retrieve the recipient's number and message.
            String number = intent.getStringExtra(EXTRA_NUMBER);
            String message = intent.getStringExtra(EXTRA_MESSAGE);
            int user_id = intent.getIntExtra("user_id", 0);
            int quantity = intent.getIntExtra("quantity", 0);
            String sent_result;

            if (SMS_SENT_ACTION.equals(action)) {
                start = true;
                int resultCode = getResultCode();
                sent_result = translateSentResult(resultCode);
                JSONObject object = new JSONObject();
                JSONArray array = new JSONArray();
                try {
                    object.put("phone", number);
                    object.put("message", message);
                    object.put("quantity", quantity);
                    object.put("user_id", user_id);
                    object.put("status", sent_result);
                    object.put("delivered", null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                array.put(object);
                sendStatusToServer(array);
                Log.i("dResponse", array.toString());
            }
        }

        String translateSentResult(int resultCode) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    return "Sent";
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    return "Failed";
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    return "Radio off";
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    return "PDU Error";
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    return "Error Service";
                default:
                    return "Unknown error code";
            }
        }
    }
}

然后id:395被处理两次。我与这样的问题斗争了两天。最后,我在这里发布任何想法。提前感谢。

我想问题在于在
deleteFromDB(…)
方法中再次调用
jsonParse()

private void deleteFromDB(int id) {
.......
.......

            @Override
            public void onResponse(String response) {
                Log.i("resonse", response);

                //here, I guess this is the problem
                jsonParse();
            }
......
......
}
private void deleteFromDB(int id) {
.......
.......

            @Override
            public void onResponse(String response) {
                Log.i("resonse", response);

                //here, I guess this is the problem
                jsonParse();
            }
......
......
}