Free Push Notification using onesignal - Android Part 2
Create notification
The Create Notification method is used when you want your server to programmatically send notifications to a segment or individual users. You may target users in one of three ways using this method: by Segment, by Filter, or by Device. At least one targeting parameter must be specified.
You may only use one method of targeting users
If a targeting parameter of one type is used, then targeting parameters from other types may not be used. For instance, you cannot use the
included_segments
parameter (from segments) with the filters
.
Send to Segments
Segments are the most common way developers send notifications via OneSignal. Sending to segments is easy: you simply specify which segments you want to send to, and, optionally, which ones you don't.
Send to a specific segment - Create notification
class PhotoTask extends AsyncTask<String,String,String> {
@Override protected String doInBackground(String... strings) {
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 NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
con.setRequestMethod("POST");
String strJsonBody = "{" + "\"app_id\": \"13b67e0f-9968-4b95-87e9-5340c7c7693e\","
+ "\"big_picture\": \""+img_url+"\","
+ "\"large_icon\": \""+user_photo+"\","
+ "\"include_player_ids\": [\""+Onesignal_id+"\"],"
+ "\"data\": {\"id\": \""+user_id+","+user_name+","+user_photo+"\"},"
+ "\"contents\": {\"en\": \""+user_name+": "+Txt_msg+"\"}" + "}";
System.out.println("strJsonBody:\n" + strJsonBody);
Log.d("strJsonBody",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();
}
return null;
}
}
Note:The one signal id, i stored and retrieve from firebase database.
Results - Create notification:
If your notification successfully created means you get the following response
Comments
Post a Comment