1

Estou usando o seguinte código para enviar notificação a partir do android e não do 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();

    }

Não aparece nenhum erro na aplicação, simplesmente o código é executado e não funciona.

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.Evento.EventosCad.pushFCMNotification(EventosCad.java:188) W/System.err: at com.alpha.tec.agendaonline.Evento.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 Resposta 1

1

O erro ocorre pois você está tentando abrir uma conexão na Thread principal da aplicação ( NetworkOnMainThreadException ).

Neste caso é necessário executar esta operação em uma AsyncTask

Segue um exemplo:

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

Para executar a operação chame da seguinte forma:

new AsyncConnection().execute(userDeviceIdKey);

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .