I am making an Android app to forward SMS to Telegram. There is a broadcastReceiver listening to SMS, and then call a HTTP request sending to my own server. It works fine. However, when the screen is off, wifi is off as well. When there is a SMS, there is no network to send the HTTP request.
I have searched about Wakelock and Wifilock. Both of them seems not applicable in this case.
Is there a way to wake up the network connection for a while, to finish the HTTP call?
Thanks.
AndroidManifest.xml
<receiver android:name=".SmsReceiver" android:enabled="true" android:exported="true">
<intent-filter android:priority="500">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
WifiLockManager.acquireWifiLock(context);
RequestQueue queue = Volley.newRequestQueue(context);
String url = "https://smsforwarder.mydomain.xyz/";
Bundle bundle = intent.getExtras();
if (bundle != null) {
String sender = "";
String message = "";
SmsMessage[] sms = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (int i=0; i < sms.length; i++) {
SmsMessage smsMessage = sms[i];
sender = smsMessage.getOriginatingAddress();
message += smsMessage.getMessageBody();
}
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("sender", sender);
postParam.put("message", message);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,
url,
new JSONObject(postParam),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "SMS forwarded", Toast.LENGTH_SHORT).show();
WifiLockManager.releaseWifiLock();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "SMS forward failed", Toast.LENGTH_SHORT).show();
WifiLockManager.releaseWifiLock();
}
}
){
@Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
queue.add(jsonObjReq);
}
}
}