Problems sending a notification

Asked

Viewed 84 times

1

I’m using the following code to send notification from android and not console

public static void pushFCMNotification(String userDeviceIdKey) throws Exception
{

        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization","key=AIzaSyCEwVIxZv_..._hHEmAO0");
        conn.setRequestProperty("Content-Type","application/json");

        JSONObject json = new JSONObject();
        json.put("to",userDeviceIdKey.trim());
        JSONObject info = new JSONObject();
        info.put("title", "Enviando msg");   // Notification title
        info.put("body", "cadastrou"); // Notification body
        json.put("notification", info);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(json.toString());
        wr.flush();
        conn.getInputStream();

    }

No error appears in the application, simply the code runs and does not work.

W/Egl_emulation: eglSurfaceAttrib not implemented W/Egl_emulation: eglSurfaceAttrib not implemented W/System.err: android.os.Networkonmainthreadexception W/System.err: at android.os.Strictmode$Androidblockguardpolicy.onNetwork(Strictmode.java:1145) W/System.err: at java.net.Inetaddress.lookupHostByName(Inetaddress.java:385) W/System.err: at java.net.Inetaddress.getAllByNameImpl(Inetaddress.java:236) W/System.err: at java.net.Inetaddress.getAllByName(Inetaddress.java:214) W/System.err: at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28) W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(Routeselector.java:216) W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(Routeselector.java:122) W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(Httpengine.java:292) W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(Httpengine.java:255) W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(Httpengine.java:206) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(Httpurlconnectionimpl.java:345) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(Httpurlconnectionimpl.java:89) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(Httpurlconnectionimpl.java:197) W/System.err: at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(Httpsurlconnectionimpl.java:254) W/System.err: at com.alpha.tec.agendaonline.event.EventosCad.pushFCMNotification(Eventoscad.java:188) W/System.err: at com.alpha.tec.agendaonline.Event.Eventoscad$1.onClick(Eventoscad.java:84) W/System.err: at android.view.View.performClick(View.java:4438) W/System.err: at android.view.View$Performclick.run(View.java:18422) W/System.err:
at android.os.Handler.handleCallback(Handler.java:733) W/System.err:
at android.os.Handler.dispatchMessage(Handler.java:95) W/System.err:
at android.os.Looper.loop(Looper.java:136) W/System.err: at android.app.Activitythread.main(Activitythread.java:5045) W/System.err: at java.lang.reflect.Method.invokeNative(Native Method) W/System.err: at java.lang.reflect.Method.invoke(Method.java:515) W/System.err: at com.android.Internal.os.Zygoteinit$Methodandargscaller.run(Zygoteinit.java:779) W/System.err: at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:595) W/System.err: at Dalvik.system.Nativestart.main(Native Method)

1 answer

1

The error occurs because you are trying to open a connection on Thread main of the application ( Networkonmainthreadexception ).

In this case it is necessary to perform this operation in a Asynctask

Follow an example:

  public class AsyncConnection extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... strings) {

        final String userDeviceIdKey = strings[0];
        URL url = null;
        try {
            url = new URL("https://fcm.googleapis.com/fcm/send");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key=AIzaSyCEwVIxZv_..._hHEmAO0");
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            json.put("to",userDeviceIdKey.trim());
            JSONObject info = new JSONObject();
            info.put("title", "Enviando msg");   // Notification title
            info.put("body", "cadastrou"); // Notification body
            json.put("notification", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            conn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
     }
   }

To execute the operation call as follows:

new AsyncConnection().execute(userDeviceIdKey);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.