如何通过广播接收器唤醒网络连接?

时间:2018-07-12 09:04:45

标签: android

我正在制作一个Android应用程序以将SMS转发到Telegram。有一个广播接收器正在监听SMS,然后调用HTTP请求发送到我自己的服务器。工作正常。但是,当屏幕关闭时,wifi也将关闭。出现SMS时,没有网络可以发送HTTP请求。

我搜索了有关Wakelock和Wifilock的信息。这两种情况似乎都不适用。

是否可以在一段时间内唤醒网络连接以完成HTTP调用?

谢谢。

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);
    }
}

}

2 个答案:

答案 0 :(得分:0)

1。在AndroidManifest

中声明接收方
 <receiver android:name=".IncomingSms">   
     <intent-filter>
         <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
 </receiver>

2。授予AndroidManifest中的SMS权限

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

3。IncomingSms.java文件:

public class IncomingSms extends BroadcastReceiver {


// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                String senderNum = phoneNumber;
                String message = currentMessage.getDisplayMessageBody();

               // Write you code here


            } // end for loop
          } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" +e);

    }
}    

}

答案 1 :(得分:0)

注意:请勿在广播接收器onReceive上进行网络请求,因为它将触发并终止一段时间,即仅8至10秒。 如果要在onReceive中强制执行此操作,则意味着应在接收器中使用 goAsync 方法。 或者,您可以致电任何服务或工作经理,例如后台服务。