Send a message by Onesignal from Android

Asked

Viewed 88 times

0

The code below serves to send a push message via Onesignal, when running in Netbeans everything works perfectly but when trying to run on android did not succeed. I’d like you to help me, so follow the codes:

This code that works in Netbeans: package javaapplication2;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;


public class JavaApplication2 {


    public static void main(String[] args) {

    String titulo = "Esse é um bom título";
    String mensagem = "Uma excelente mensagem para você";

        enviarNotificacao(titulo, mensagem);
    }

    public static void enviarNotificacao(String mTitle, String mMensagem ){

   try {
   String jsonResponse;

   URL url = new URL("https://onesignal.com/api/v1/notifications");
   HttpURLConnection con = (HttpURLConnection)url.openConnection();
   con.setUseCaches(false);
   con.setDoOutput(true);
   con.setDoInput(true);

   con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
   con.setRequestProperty("Authorization", "Basic ZGJjMzI3Z....");
   con.setRequestMethod("POST");

   String strJsonBody = "{"
                      +   "\"app_id\": \"08603795-b086-4d1e-9030-1...\","
                      +   "\"included_segments\": [\"All\"],"
                      +   "\"data\": {\"foo\": \"bar\"},"

                      +   "\"headings\": {\"en\": \""+ mTitle +"\"},"
                      +   "\"contents\": {\"en\": \""+ mMensagem + "\"}"
                      + "}";


   System.out.println("strJsonBody:\n" + strJsonBody);

   byte[] sendBytes = strJsonBody.getBytes("UTF-8");
   con.setFixedLengthStreamingMode(sendBytes.length);

   OutputStream outputStream = con.getOutputStream();
   outputStream.write(sendBytes);

   int httpResponse = con.getResponseCode();
   System.out.println("httpResponse: " + httpResponse);

   if (  httpResponse >= HttpURLConnection.HTTP_OK
      && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
      Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   else {
      Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   System.out.println("jsonResponse:\n" + jsonResponse);

} catch(Throwable t) {
   t.printStackTrace();
}
    }


}

This code is my attempt on android:

import android.os.StrictMode;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Scanner;

public class Notifications {

private String jsonResponse;

public void setNotification(String titulo, String mensagem) {

    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > 8) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        //your codes here

        URL url = null;
        try {
            url = new URL("https://onesignal.com/api/v1/Notifications");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 1");
        }
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 2");
        }
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("Authorization", "Basic ZGJjMzI3ZmMtYzFlMy00YTRjLWEyOTctYTY4YTUyNTE1MTY1");
        try {
            con.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 3");
        }

        String strJsonBody = "{"
                + "\"app_id\": \"08603795-b086-4d1e-9030-122d4270c398\","
                + "\"included_segments\": [\"All\"],"
                + "\"data\": {\"foo\": \"bar\"},"
                + "\"headings\": {\"en\": \"" + titulo + "\"},"
                + "\"contents\": {\"en\": \"" + mensagem + "\"}"
                + "}";


        System.out.println("strJsonBody:\n" + strJsonBody);

        byte[] sendBytes = new byte[0];
        try {
            sendBytes = strJsonBody.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 4");
        }
        con.setFixedLengthStreamingMode(sendBytes.length);

        OutputStream outputStream = null;
        try {
            outputStream = con.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 5");
        }
        try {
            outputStream.write(sendBytes);
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 6");
        }

        int httpResponse = 0;
        try {
            httpResponse = con.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 7");
        }
        System.out.println("httpResponse: " + httpResponse);

        System.out.println("jsonResponse:\n" + jsonResponse);

    }
}
}

1 answer

1


I was also going that way, but that code would be more in the case of a Java server. For Android is much simpler, just do this and more nothing:

try {
    OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + userId + "']}"), null);
} catch (JSONException e) {
    e.printStackTrace();
}

SDK Android Onesignal

Browser other questions tagged

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