Send pussh crossplatform, hub Azure - java

I have an application that is now being developed for IOS. I need them pushed between the platforms. As it is written today, in the backend, it works from Android for Android, but I changed the registration of the devices, so that they were registered with the respective templates (of each platform).
More, it stopped working obviously because it is written from Android to Android.
The record in the hub is correct. What should I change for push to be sent?
Backend code:
public static async void enviarPushNotification(ApiController controller, DataObjects.Notification notification)
{
// Get the settings for the server project.
HttpConfiguration config = controller.Configuration;
MobileAppSettingsDictionary settings =
controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
// Get the Notification Hubs credentials for the Mobile App.
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings
.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
// Create a new Notification Hub client.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
data.Add("Tipo", notification.Tipo);
data.Add("Id_usuario", notification.Id_usuario);
//data.Add("Informacao", notification.Informacao);
data.Add("Informacao", notification.Informacao);
data.Add("Status", notification.Status);
//alteração com a colocação da tag priority em caso de erro teste sem \"priority\": \"high\"
var androidNotificationPayload = "{ \"priority\": \"high\", \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
// var androidNotificationPayload = "{ \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:" + notification.Id_usuario;
//var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload, tag);
// Write the success result to the logs.
config.Services.GetTraceWriter().Info(result.State.ToString());
}
catch (System.Exception ex)
{
// Write the failure result to the logs.
config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
}
}
Device code:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private NotificationHub hub;
public RegistrationIntentService() {
super(TAG);
}
public ApplicationUtils getApplicationUtils() {
return (ApplicationUtils) getApplication();
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
if (FirebaseInstanceId.getInstance() == null) {
FirebaseApp.initializeApp(this);
}
String FCM_token = FirebaseInstanceId.getInstance().getToken();
SaveSharedPreferences.setFCM(getApplicationContext(), FCM_token);
String registrationID = sharedPreferences.getString("registrationID", null);
if (registrationID == null) {
registerDevice(sharedPreferences, FCM_token);
} else {
String fcMtoken = sharedPreferences.getString("FCMtoken", "");
if (!fcMtoken.equals(FCM_token)) {
registerDevice(sharedPreferences, FCM_token);
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to complete registration", e);
}
}
private void registerDevice(SharedPreferences sharedPreferences, String FCM_token) throws Exception {
String tag = "_UserId:" + getApplicationUtils().getUsuario().Id;
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
String templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";
TemplateRegistration registration = hub.registerTemplate(FCM_token, "simpleGCMTemplate", templateBodyGCM, tag);
String regID = registration.getRegistrationId();
sharedPreferences.edit().putString("registrationID", regID).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token).apply();
}
}

Related

Setting up AWS IOT Core JITR process on Android

I need to set up a JITR (Just in time registration) process to AWS IOT core for my Android Application using Android AWS IOT SDK. My implementation is done referring this . However, When trying to create a thing after creating a fresh X.509 certificate (On the first connection attempt), Even though the certificate is created on the server, the Server returns errors regarding "unmatched signatures and an empty template body".
This is my current sample implementation,
public class MainActivity extends AppCompatActivity {
private boolean thingExist;
private String certificateARN;
// IoT endpoint
// AWS Iot CLI describe-endpoint call returns: XXXXXXXXXX.iot.<region>.amazonaws.com
private static final String CUSTOMER_SPECIFIC_ENDPOINT = "";
// Cognito pool ID. For this app, pool needs to be unauthenticated pool with
// AWS IoT permissions.
private static final String COGNITO_POOL_ID = "";
// Name of the AWS IoT policy to attach to a newly created certificate
private static final String AWS_IOT_POLICY_NAME = "";
// Region of AWS IoT
private static final Regions MY_REGION = Regions.US_EAST_2;
// Filename of KeyStore file on the filesystem
private static final String KEYSTORE_NAME = "iot_keystore";
// Password for the private key in the KeyStore
private static final String KEYSTORE_PASSWORD = "password";
// Certificate and key aliases in the KeyStore
private static final String CERTIFICATE_ID = "default";
AWSIotClient mIotAndroidClient;
AWSIotMqttManager mqttManager;
String clientId;
String keystorePath;
String keystoreName;
String keystorePassword;
private boolean isAWSConnected;
private listThings mTask;
private boolean certificateExist;
private final String LOG_TAG = "AWS";
private final String serialId = "1110";
KeyStore clientKeyStore = null;
String certificateId;
CognitoCachingCredentialsProvider credentialsProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientId = Settings.Global.getString(getApplicationContext().getContentResolver(), "device_name");
// Initialize the AWS Cognito credentials provider
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), // context
COGNITO_POOL_ID, // Identity Pool ID
MY_REGION // Region
);
Region region = Region.getRegion(MY_REGION);
// MQTT Client
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
// Set keepalive to 10 seconds. Will recognize disconnects more quickly but will also send
// MQTT pings every 10 seconds.
mqttManager.setKeepAlive(10);
// Set Last Will and Testament for MQTT. On an unclean disconnect (loss of connection)
// AWS IoT will publish this message to alert other clients.
AWSIotMqttLastWillAndTestament lwt = new AWSIotMqttLastWillAndTestament("Last will",
new Gson().toJson("Android client lost connection"), AWSIotMqttQos.QOS0);
mqttManager.setMqttLastWillAndTestament(lwt);
mIotAndroidClient = new AWSIotClient(credentialsProvider);
mIotAndroidClient.setRegion(region);
keystorePath = getFilesDir().getPath();
keystoreName = KEYSTORE_NAME;
keystorePassword = KEYSTORE_PASSWORD;
certificateId = CERTIFICATE_ID;
// To load cert/key from keystore on filesystem
try {
if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) {
if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath,
keystoreName, keystorePassword)) {
Log.i(LOG_TAG, "Certificate " + certificateId
+ " found in keystore - using for MQTT.");
// load keystore from file into memory to pass on connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
certificateExist = true;
mTask = (listThings) new listThings().execute();
} else {
Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
}
} else {
Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e);
}
if (clientKeyStore == null) {
certificateExist = false;
Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
new Thread(new Runnable() {
#Override
public void run() {
try {
// Create a new private key and certificate. This call
// creates both on the server and returns them to the
// device.
CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
new CreateKeysAndCertificateRequest();
createKeysAndCertificateRequest.setSetAsActive(true);
final CreateKeysAndCertificateResult createKeysAndCertificateResult;
createKeysAndCertificateResult =
mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);
Log.i(LOG_TAG,
"Cert ID: " +
createKeysAndCertificateResult.getCertificateId() +
" created.");
// store in keystore for use in MQTT client
// saved as alias "default" so a new certificate isn't
// generated each run of this application
AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
createKeysAndCertificateResult.getCertificatePem(),
createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
keystorePath, keystoreName, keystorePassword);
certificateARN = createKeysAndCertificateResult.getCertificateArn();
// load keystore from file into memory to pass on
// connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
// Attach a policy to the newly created certificate.
// This flow assumes the policy was already created in
// AWS IoT and we are now just attaching it to the
// certificate.
AttachPrincipalPolicyRequest policyAttachRequest =
new AttachPrincipalPolicyRequest();
policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
policyAttachRequest.setPrincipal(createKeysAndCertificateResult
.getCertificateArn());
mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
mTask = (listThings) new listThings().execute();
} catch (Exception e) {
Log.e(LOG_TAG,
"Exception occurred when generating new private key and certificate.",
e);
}
}
}).start();
}
}
private class listThings extends AsyncTask<Void, Void, Boolean> {
// Listing registered things to verify whether a thing already exist under the same device ID.
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(LOG_TAG, "Listing Things");
final ListThingsRequest request = new ListThingsRequest().withAttributeName("Device_ID")
.withAttributeValue(serialId).withMaxResults(1);
final ListThingsResult result = mIotAndroidClient.listThings(request);
if (!result.getThings().isEmpty()) {
thingExist = true;
return true;
} else {
thingExist = false;
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
Log.d(LOG_TAG, "onPostExecute: " + aBoolean.toString());
if (certificateExist) {
new createThing().execute();
} else {
new awsAsync().execute();
}
mTask.cancel(true);
}
}
private class awsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
if (thingExist) {
//Thing Exist, certificate doesn't exist
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(certificateARN);
Log.d(LOG_TAG, "certificateARN " + certificateARN);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
/*check if previous certificates are available and delete them*/
} else {
//Thing Doesn't Exist, certificate doesn't exist
try {
Log.d(LOG_TAG, "Thing does not Exist, certificate doesn't exist");
Map<String, String> attributes = new HashMap<String, String>() {{
put("Device_ID", serialId);
put("Android_version", Build.VERSION.RELEASE);
}};
CreateThingRequest createThingRequest = new CreateThingRequest();
createThingRequest.setThingName(serialId);
AttributePayload attributePayload = new AttributePayload();
attributePayload.setAttributes(attributes);
createThingRequest.setThingTypeName("Consenz_search");
createThingRequest.setAttributePayload(attributePayload);
mIotAndroidClient.createThing(createThingRequest);
AddThingToThingGroupRequest addThingToThingGroupRequest = new AddThingToThingGroupRequest();
addThingToThingGroupRequest.setThingName(serialId);
addThingToThingGroupRequest.setThingGroupName("Consenz_Group");
mIotAndroidClient.addThingToThingGroup(addThingToThingGroupRequest);
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(certificateARN);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
} catch (Exception e) {
Log.e(LOG_TAG,
"Excepetion occured when creating thing",
e);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
connectToAWS();
}
}
private class createThing extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
if (!thingExist) {
try {
//Thing doesn't exist, Certificate exist
Log.d(LOG_TAG, "Thing does not Exist. Creating a thing");
Map<String, String> attributes = new HashMap<String, String>() {{
put("Device_ID", serialId);
put("Android_version", Build.VERSION.RELEASE);
}};
CreateThingRequest createThingRequest = new CreateThingRequest();
createThingRequest.setThingName(serialId);
AttributePayload attributePayload = new AttributePayload();
attributePayload.setAttributes(attributes);
createThingRequest.setThingTypeName("Consenz_search");
createThingRequest.setAttributePayload(attributePayload);
mIotAndroidClient.createThing(createThingRequest);
AddThingToThingGroupRequest addThingToThingGroupRequest = new AddThingToThingGroupRequest();
addThingToThingGroupRequest.setThingName(serialId);
addThingToThingGroupRequest.setThingGroupName("Consenz_Group");
mIotAndroidClient.addThingToThingGroup(addThingToThingGroupRequest);
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(AWSIotKeystoreHelper.AWS_IOT_INTERNAL_KEYSTORE_PASSWORD);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
//need to attach the current thing to existing certificate.
} catch (Exception e) {
Log.e(LOG_TAG,
"Excepetion occured when creating thing",
e);
}
} else {
//Thing exist, Certificate exist
//need to attach the current thing to existing certificate.
Log.d(LOG_TAG, "We here");
final ListThingPrincipalsRequest request = new ListThingPrincipalsRequest().withThingName(serialId);
final ListThingPrincipalsResult result = mIotAndroidClient.listThingPrincipals(request);
DescribeCertificateRequest request1 = new DescribeCertificateRequest().withCertificateId("default");
DescribeCertificateResult result1 = mIotAndroidClient.describeCertificate(request1);
String arn = result1.getCertificateDescription().getCertificateArn();
result.toString();
Log.d(LOG_TAG, "arn " + arn);
Log.d(LOG_TAG, "certificates " + result);
//Log.d(LOG_TAG, "Thing Exists. Attaching thing to certificate");
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
//String arn = thingPrincipalRequest.getPrincipal(c);
//Log.d(LOG_TAG, "arn "+arn);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Log.d(LOG_TAG, "Done creating thing");
connectToAWS();
}
}
private void connectToAWS() {
try {
Log.d(LOG_TAG, "Client ID: " + clientId);
mqttManager.connect(clientKeyStore, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
Log.d(LOG_TAG, "Connecting...");
isAWSConnected = false;
} else if (status == Connected) {
Log.d(LOG_TAG, "Connected");
isAWSConnected = true;
//creatething
publishToAWS();
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
isAWSConnected = false;
}
isAWSConnected = false;
Log.d(LOG_TAG, "Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
isAWSConnected = false;
}
isAWSConnected = false;
Log.d(LOG_TAG, "Disconnected");
} else {
isAWSConnected = false;
Log.d(LOG_TAG, "Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.d(LOG_TAG, "Error! " + e.getMessage());
}
}
private void publishToAWS() {
//publishing MQQT messages to AWS
String version = "";
String versionRelease = Build.VERSION.RELEASE;
try {
version = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
try {
mqttManager.publishString(new Gson().toJson(serialId), "Device_ID", AWSIotMqttQos.QOS0);
mqttManager.publishString(new Gson().toJson(version), "APK_Version", AWSIotMqttQos.QOS0);
mqttManager.publishString(new Gson().toJson(versionRelease), "Android_Version", AWSIotMqttQos.QOS0);
} catch (Exception e) {
Log.e(LOG_TAG, "Publish error.", e);
}
}
}
what am I doing wrong here? thanks in advance.

How I can replay to WhatsApp notification from java code in android studio

Hello guys I'm using NotificationListenerService to get WhatsApp messages
But now I have a problem that I don't know how to replay to WhatsApp notifications
So here is the code and how I'm getting WhatsApp notifications but my problem is in how actually to replay on them
public class NotificationListener extends NotificationListenerService {
// StaticFields:
public static final String WHATSAPP_PACKAGE_NAME = "com.whatsapp";
// TAGS:
private static final String TAG = "NotificationListener";
private static final String NP_FIELD = "onNotificationPosted: ";
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
// Fields:
ARPreferencesManager manager = new ARPreferencesManager(getApplicationContext());
String currentPackages = manager.getStringPreferences(ARPreferencesManager.PACKAGE_APP_NAME);
List<Chat.Messages> messages = new ArrayList<>();
// CheckingStatusBarNotification:
if (sbn.getPackageName().equals(WHATSAPP_PACKAGE_NAME)) {
// Initializing(DateTime):
String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date());
List<Chat> chats;
// Initializing(Data):
String sender = sbn.getNotification().extras.getString(Notification.EXTRA_TITLE);
String msg = sbn.getNotification().extras.getString(Notification.EXTRA_TEXT);
String currentSenders = manager.getStringPreferences(ARPreferencesManager.SENDER_NAME);
// AddingData:
messages.add(new Chat.Messages(msg));
// Developing:
if (manager.getPreferences().contains(ARPreferencesManager.WHATSAPP_CHATS)) {
// Initializing:
chats = ARUtils.fromJsonToChats(manager.getStringPreferences(ARPreferencesManager.WHATSAPP_CHATS));
// Developing:
for (Chat chat : chats) {
if (chat.getSender().equals(sender)) {
// AddingTheNewMessage:
chat.getMessages().addAll(messages);
// AddingSender($Preferences):
if (!currentSenders.contains(sender)) {
// Initializing:
manager.setStringPreferences(ARPreferencesManager.SENDER_NAME, sender + ",");
// Refreshing:
currentSenders = manager.getStringPreferences(ARPreferencesManager.SENDER_NAME);
}
}
}
// CheckingSenders:
if (!currentSenders.contains(sender)) {
// Initializing:
Chat chat = new Chat(sender, "", date, null, messages);
// AddingTheNewChat:
chats.add(chat);
}
} else {
// Initializing:
chats = new ArrayList<>();
// Developing:
chats.add(new Chat(sender, "", date, null, messages));
}
// SettingPreferences:
manager.setStringPreferences(ARPreferencesManager.WHATSAPP_CHATS, ARUtils.fromChatsToJson(chats));
// Debugging:
ARUtils.debug(TAG, NP_FIELD, manager.getStringPreferences(ARPreferencesManager.WHATSAPP_CHATS));
}
// Debugging:
ARUtils.debug(TAG, NP_FIELD, "Whatsapp Package Was Founded In Preferences");
// Debugging:
ARUtils.debug(TAG, NP_FIELD, "Start");
}
}
Did you try using this function?
fun reply(action: Notification.Action, message: String, exception: Exception.() -> Unit = {}) {
try {
val sendIntent = Intent()
val msg = Bundle()
for (inputable in action.remoteInputs) {
msg.putCharSequence(inputable.resultKey, message)
}
RemoteInput.addResultsToIntent(action.remoteInputs, sendIntent, msg)
action.actionIntent.send(applicationContext, 0, sendIntent)
} catch (exception: Exception) {
exception(exception)
}
}
You can get Notification.Action for this way:
override fun onNotificationPosted(sbn: StatusBarNotification) {
super.onNotificationPosted(sbn)
val wExt = Notification.WearableExtender(sbn.notification)
for (action in wExt.actions) {
...

How to Retrieve Data from Node Server With Socket?

i've got problem getting data from Node server, i've searching many reference from internet, but i haven't found one yet that can solve my problem.
this is my node server
var socket = require('socket.io');
var express = require('express');
var app = express();
/*
var options = {
key: fs.readFileSync('cert/file.key'),
cert: fs.readFileSync('cert/file.crt')
};
var server = require('https').createServer(options, app);
*/
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
//server.listen(port, '103.126.57.4', function () {
server.listen(port, function () {
console.log('Server listening at port %d', port);
//console.log('Server listening at port %d', port, server.address());
});
io.on('connection', function (socket) {
console.log( "New client connected !" );
//console.log(socket.handshake.headers.host);
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'new_chat_kelas', function( data ) {
io.sockets.emit( data.tabelchat, {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'change_chat_status', function( data ) {
io.sockets.emit( 'change_status'+data.tabelchat, {
status: data.status
});
});
/*
socket.on('disconnect', function () {
console.log( "Client disconnected !" );
});
*/});
And this is my Android code
try {
//if you are using a phone device you should connect to same local network as your laptop and disable your pubic firewall as well
socket = IO.socket("http://192.168.100.13:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
refreshChat(url);
getTabelKelas();
getDiskusiChat(sharedDiskusi.getSpdiskusi());
private void getDiskusiChat(String tabelChat) {
socket.on(tabelChat, new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String jsonStr = data.toString();
Log.d("cek", "cek data : "+data);
Toast.makeText(mContext, (CharSequence) data, Toast.LENGTH_LONG).show();
try {
//extract data from fired event
String cek = String.valueOf(data.getJSONArray("idleveluser"));
// String nickname = data.getString("senderNickname");
// String message = data.getString("message");
// make instance of message
//
// Message m = new Message(nickname,message);
// Message m = new Message(nickname,message);
//
//
// //add the message to the messageList
//
// MessageList.add(m);
//
// // add the new updated list to the dapter
// chatBoxAdapter = new ChatBoxAdapter(MessageList);
//
// // notify the adapter to update the recycler view
//
// chatBoxAdapter.notifyDataSetChanged();
//
// //set the adapter for the recycler view
//
// myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
i have try to Toast and log it but did not appear.
Can anyone help me to retrieve data ?I confuse how to get data if the data in the form of an array. I'm helped if someone helps me.
Sry for my bad english brother.
This is my log
Change this code line
String cek = String.valueOf(data.getJSONArray("idleveluser"));
to
String cek = String.valueOf(data.getString("idleveluser"));
as each item in the data object is a string.

How to pass two different JSON Objects to processFinish at two different times

I have this MainActivity which does two HTTP calls and return the JSON object back to the MainActivity class. I have seperately implemented the AsyncTask class and used the AsyncResponse interface to get the JSON object to the MainActivity by using the processFinish function call.
At first I came up with one HTTP call which worked perfectly.
Secondly I wanted to do another HTTP call in the same activity class. So I edit the code to cater the second HTTP call.
When I run the application, only the first HTTP call is working. When I call the second HTTP call it throws an exception saying reference to a null object
Then I checked by logging the onPostExecute method which calls the processFinish function. There I could see the JSON Object. So, that means the second JSON object doesn't get to the processFinish
How do I manage the second HTTP call? Please help me! I am new to Android.
Following is my AsyncTask class...
public class ServiceHandler extends AsyncTask<String, Void, JSONObject> {
String startStationID;
String endStationID;
String searchDate;
String startTime;
String endTime;
public ServiceHandler(String startStationID, String endStationID, String searchDate, String startTime, String endTime) {
this.startStationID = startStationID;
this.endStationID = endStationID;
this.searchDate = searchDate;
this.startTime = startTime;
this.endTime = endTime;
}
public interface AsyncResponse {
void processFinish(JSONObject output);
}
public AsyncResponse delegate=null;
public ServiceHandler(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected JSONObject doInBackground(String... params) {
String method = params[0];
JSONObject JSON_Object = null;
if (method.equals("getStations")) {
JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/station/getAll?lang=en");
} else if (method.equals("searchTrains")) {
JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/train/searchTrain?" +
"startStationID="+this.startStationID+"&" +
"endStationID="+this.endStationID+"&" +
"searchDate="+this.searchDate+"&" +
"startTime="+this.startTime+"&" +
"endTime="+this.endTime+"&" +
"lang=en");
}
return JSON_Object;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(JSONObject obj) {
try{
Log.d("onPostExecute",obj.toString());
delegate.processFinish(obj);
}catch (Exception e){
Log.e("onPostExecute",e.getMessage());
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Following is my processFinish function...
#Override
public void processFinish(JSONObject output) {
Log.d("processFinish",output.toString());
if(!isSearchClicked) {
//Get all the stations...
if (output != null) {
Toast.makeText(MainActivity.this, "Successfully Connected!", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = output.getJSONObject("RESULTS");
output = null;
JSONArray dataArray = obj.getJSONArray("stationList");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject object1 = dataArray.getJSONObject(i);
String stationID = object1.getString("stationID");
String stationName = object1.getString("stationName");
stationNames.add(stationName);
stationIDs.add(stationID);
// stations.put(stationID,stationName);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
}
}else {
//search click action...
if (output != null) {
Toast.makeText(MainActivity.this, "Successfully Searched!", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = output.getJSONObject("RESULTS");
JSONArray directTrains = obj.getJSONArray("directTrains");
// Log.d("array size",String.valueOf(directTrains.length()));
// for (int i = 0; i < directTrains.length(); i++) {
// JSONObject object1 = directTrains.getJSONObject(i);
//
// String stationID = object1.getString("stationID");
// String stationName = object1.getString("stationName");
// Log.d("JArr", stationID + " : " + stationName);
//
// stationNames.add(stationName);
// stationIDs.add(stationID);
//// stations.put(stationID,stationName);
// }
// Log.d("stationNames", stationNames.toString());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
Log.d("output",output.toString());
}
}
}
Following is my first HTTP call...
ServiceHandler sh = new ServiceHandler(this);
String method = "getStations";
sh.execute(method);
Following is my second HTTP call...
String method = "searchTrains"
ServiceHandler sh = new ServiceHandler(startStationID,endStationID,searchDate,startTime,endTime);
sh.execute(method);
Although I don't understand exactly what your problem is. There are few things I suggest you to do.
Here I go.
Don't use AsyncTask to make your http calls , use an intent services instead.
Use a OkHTTP library for your networking source
On your intent service send local broadcast with LocalBroadcastManager to broadcast your results from the http call.
Register broadcastsReceivers within your activities or fragments that will listen for those broadcasts that comes from the intent service
Why not to use AsyncTask: Because of configuration change - if you rotate your device you will lose that network calls-
Read about intent services here

Iphone emoji Unicode decode issue for push notification dispatch by APNs

My web service publish push notification to APNs and APNs send to destination IOS device.
When apns contain Unicode emoji on alert body push notification and Iphone os can't decode my Unicode emoji '\uD83D\uDE0A' app already kill.
Push notification show same '\uD83D\uDE0A', No emoji shown on banner notification bar on top.
Android application works fine by GCM dispatches push notification But IOS not support.
Iphone-Ios supports only this format '\ue415'
Here code that from ActiveMQ subscribe chat payload get into web-service
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
try {
String body = msg.utf8().toString();
if (logger.isInfoEnabled()) {
logger.info("MQTT connection.listener.onPublish(), msg Received ["
+ body + "]");
}
if (body.contains("\"cmd\":\"chat\"")
&& body.contains("\"is_sender_msg\":true")) {
QueueMgr.addToChatQueue(body); //Changed true to false
}
else if(body.contains("\"cmd\":\"msg_seen\"")){
QueueMgr.addToChatReadSeenQueue(body);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ack.run();
}
}
My code for create push notification on java
public static JSONObject constructePushJson(JSONObject jsonObject,String[] cloudkeyWithDevice) throws JSONException {
if(cloudkeyWithDevice[0] != null){
JSONObject pnAPIdata = new JSONObject();
if(cloudkeyWithDevice[1].equals("a") || cloudkeyWithDevice[1].equals("d")){
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_ANDROID_PUSH);
}
else{
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_IOS_PUSH);
}
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_APP_TOKEN, com.anyorg.constants.AppConstants.DEFAULT_APP_TOKEN);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_TOKEN, cloudkeyWithDevice[0]);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_USER_ID, jsonObject.getInt(com.anyorg.constants.AppConstants.FLD_TO_USER_ID));
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_ID, 0);
String alertMsg=StringEscapeUtils.unescapeJava(jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY));
jsonObject.put(com.anyorg.constants.AppConstants.FLD_BODY,alertMsg);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_ALERT_MSG, "AryaConnect: "+alertMsg);//(jsonObject.isNull("body")) ? jsonObject.getString("from_user_name")+": Sent a file" : jsonObject.getString("from_user_name")+": "+jsonObject.getString("body")
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_MSG, jsonObject);//jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY)
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CALLBACK_URL, callbackUrl);
pnAPIdata.put(com.anyorg.constants.AppConstants.MAC_ADDRESS_ID, jsonObject.getString("mobile_rec_id"));
return pnAPIdata;
}
else{
return null;
}
}
Publish to APNs code
public class ANSNotificationDispatcher implements NotificationDispatcher {
protected static final Logger logger = Logger
.getLogger(ANSNotificationDispatcher.class);
public static final String OS_NAME = AppConstants.OS_TYPE_IPHONE;
String keystore;
String password;
boolean production;
public ANSNotificationDispatcher() {
try {
keystore = AppConfig.getAPNKeystore();
password = AppConfig.getAPNKeystorePassword();
PushyAPNMgr.init(keystore, password, AppConfig.isAPNProdcution());
} catch (Throwable e) {
e.printStackTrace();
}
}
private void push(Payload payload, String token, String userId,
String deviceId) throws ConfigurationException,
DeviceUnregisteredException {
// QueueManager.addToIOsQueue(payLoad, token, userId, ivUserDeviceId);
long stime = System.currentTimeMillis();
try {
PushyAPNMgr.push(token, payload.toString());
if (logger.isInfoEnabled())
logger.info("push(): APN PN userId [" + userId
+ "], device id [" + deviceId + "] payoad [" + payload
+ "] Response time ["
+ (System.currentTimeMillis() - stime) + "]ms");
} catch (Exception e) {
e.printStackTrace();
throw new ConfigurationException();
}
}
public static Payload createComplexPayload(JSONObject jsonObject) {
PushNotificationPayload complexPayload = null;
try {
complexPayload = createPayload(jsonObject);
String msg = Common.getStringAsNull(jsonObject,
AppConstants.FLD_MSG);
if (!Common.isEmpty(msg)) {
complexPayload.addCustomDictionary(AppConstants.FLD_MSG, msg);
}
if (logger.isInfoEnabled()) {
logger.info("createComplexPayloadV2(): payload ["
+ complexPayload.getPayload().toString() + "]");
}
} catch (JSONException e) {
e.printStackTrace();
}
return complexPayload;
}
public void dispatch(JSONObject jsonObject, String jsonData)
throws NotificationException, DeviceUnregisteredException,
MultipleRegistartionIdException, ConfigurationException {
String deviceToken = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_TOKEN);
if (Common.isEmpty(deviceToken)) {
logger.error("dispatch(): device token is null, cmd [" + jsonData
+ "]");
return;
}
Payload payload = createComplexPayload(jsonObject);
String userId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_USER_ID);
String deviceId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_ID);
push(payload, deviceToken, userId, deviceId);
}
public static void handleInvalidTokeException(String token) {
}
public static void handleDeviceUnregisteredException(String token) {
}
}
Ios push notification managed by Ios OS
My Apache Catalina log
I am a web service cloud developer faceing this issue last one days for only Ios app. So please, if some body have knowledge or done before. please advise and refer me some idea.
Emoji in my push notifications link.
https://mixpanel.com/help/questions/articles/how-do-i-send-custom-parameters-like-emoji-in-my-push-notifications
Thanks
Finally, APNs issue resolve in (Ios app) on java web service code by this Unicode encode and decode process. (unescapeJava and escapeJava) from lib commons-lang-2.6.jar and class org.apache.commons.lang.StringEscapeUtils
emojiBytes = alertMsg.getBytes("UTF-8"); text = new String(emojiBytes, "UTF-8");
private static PushNotificationPayload createPayload(JSONObject jsonObject)
throws JSONException {
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
byte[] emojiBytes=null;
String text=null;
try {
emojiBytes = alertMsg.getBytes("UTF-8");
text = new String(emojiBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String emojiAsString = new String(emojiBytes, Charset.forName("UTF-8"));
//System.out.println("#####alertMsg: "+text);
Integer badgeCnt;
if (jsonObject.has(AppConstants.FLD_BADGE_CNT)){
badgeCnt = Common.getIntegerAsNull(jsonObject,
AppConstants.FLD_BADGE_CNT);
}else{
badgeCnt = AppConstants.VAL_ZERO;
}
PushNotificationPayload payload = createPayload(badgeCnt, text);
return payload;
}
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
public static String getStringUnicodeAsNull1(JSONObject jsonObject,
String key) {
try {
if(jsonObject.isNull(key))
return null;
else
return StringEscapeUtils.unescapeJava(jsonObject.getString(key));
} catch (JSONException je) {
return null;
}
}
Respected sir and ma'am, If there is any other solution of java APNs emoji Unicode on IOS Push Notification.
Then please give me some hints.Thanks
you shouldn't need to mess about with html decoding. As you say the code point for smiling face is \u263A. In PHP you can represent that in a UTF8-encoded string as "\xE2\x98\xBA"
Lightning bolt (actually 'high voltage sign') is \u26A1 or "\xE2\x9A\xA1" in UTF-8.
Both these characters are present in some non-emoji fonts as regular Unicode symbols. You can see with:
<?php
header('Content-type: text/html; charset=utf-8');
echo "\xE2\x9A\xA1";
echo "\xE2\x98\xBA";
or other things...
for the googlers. json_encode() adds double \
$message = "\ue04a";
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'type' => $type,
'param' => $param
);
$payload = json_encode($body);
$payload = str_replace("\", "\\", $payload);
Please check with this two way... i think this is helpfull for you.

Categories