I am sending notifications many a time from my iOS application. For this i have used APNS-PHP library for sending it from server to Apple Push Notification Gateway.
Here is the code.
public function publishAPush($requestBody){
try {
$toUserId=$requestBody->{KEY_USERID};
$toUserType=$requestBody->{KEY_USERTYPE};
$soundFileName=$requestBody->{"sound"};
$badge=$requestBody->{"badge"};
$customMessage=$requestBody->{"custom"};
$alertMesssage=$requestBody->{"alert"};
if(!empty ($toUserId)){
$push = new ApnsPHP_Push(
ApnsPHP_Abstract::ENVIRONMENT_SANDBOX,
'file.pem');
// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
// Connect to the Apple Push Notification Service
$push->connect();
// Instantiate a new Message with a single recipient
$message = new ApnsPHP_Message($deviceToken);
// Set badge icon to "3"
$message->setBadge($badgeCount);
// Set a simple welcome text
$message->setText($alertMesssage);
// Play the default sound
$message->setSound($soundFileName);
$message->setCustomProperty("custom", json_encode($customMessage));
$push->add($message);
// Send all messages in the message queue
$push->send();
// Disconnect from the Apple Push Notification Service
$push->disconnect();
// Examine the error message container
$aErrorQueue = $push->getErrors();
if (!empty($aErrorQueue)) {
Logger::getRootLogger()->error("Apple Server Error= " . $aErrorQueue);
}else{
Logger::getRootLogger()->info("Message Send successfully to " . $toUserId);
}
}
} catch (Exception $exc) {
Logger::getRootLogger()->error("Publish a Push= " . $exc);
}
}
But it happens that many a times I don't receive them, so what could be a possible solution for it. Is it because I am connecting and disconnecting it.
What would be a better way to write this code?
do you receive the token in the ios app correctly?
also, use this ( https://github.com/jPaolantonio/SimplePush/blob/master/simplepush.php ) short example and then modify it yourself.
this example is working for me.
Related
I am trying to retrieve OTP in Huawei device. but it is not working.
I have created the app in Huawei developer console with all the requirements.
Below is the code i am using to retrieve the sms.
private fun initSmsManager() {
val task = ReadSmsManager.start(this#MainActivity)
task.addOnCompleteListener {
if (task.isSuccessful) {
// The service is enabled successfully. Continue with the process.
Toast.makeText(this, "ReadSms service has been enabled.", Toast.LENGTH_LONG).show()
} else
Toast.makeText(this, "The service failed to be enabled.", Toast.LENGTH_LONG).show()
}
task.addOnSuccessListener(this, OnSuccessListener {
if(task.isSuccessful){
Toast.makeText(this, "ReadSms service has been enabled.", Toast.LENGTH_LONG).show()
myReceiver = MyBroadcastReceiver();
val intentFilter = IntentFilter(READ_SMS_BROADCAST_ACTION)
registerReceiver(myReceiver, intentFilter)
}
})
task.addOnFailureListener(this, OnFailureListener {
Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show();
})
}
Broadcast receiver
class MyBroadcastReceiver : BroadcastReceiver() {
companion object {
val TAG = MyBroadcastReceiver::class.java.simpleName
}
override fun onReceive(context: Context?, intent: Intent?) {
val bundle = intent!!.extras
if (bundle != null) {
val status: Status? = bundle.getParcelable(ReadSmsConstant.EXTRA_STATUS)
if (status?.statusCode == CommonStatusCodes.TIMEOUT) {
// Service has timed out and no SMS message that meets the requirement is read. Service ended.
// doSomethingWhenTimeOut()
} else if (status?.statusCode == CommonStatusCodes.SUCCESS) {
if (bundle.containsKey(ReadSmsConstant.EXTRA_SMS_MESSAGE)) {
// An SMS message that meets the requirement is read. Service ended.
//doSomethingWhenGetMessage(bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE))
bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE)?.let {
Log.d(TAG, it)
val local = Intent()
local.action = "service.to.activity.transfer"
local.putExtra("sms", it)
context!!.sendBroadcast(local)
}
}
}
}
}
}
Any help in this would be beneficial.
Please confirm the following points:
Check whether the broadcast for receiving SMS verification codes is enabled. You can do that by performing breakpoint debugging or recording logs.
Check whether the SMS message format meets the rules for automatically reading SMS messages.
For details,See Docs.
Check whether the hash_value field is correct.
If no error occurs during the preceding check, could you pls provide a complete log trace then i will try to find out what can be wrong about this issue. :)
All code is working fine it works well on debug mode when I build released apk then keystore changed also hash changes for release mode. If you know anything about how to run on release mode , please let us know. Maybe some changes are made in Huawei developer account
I'm working on a UWP application which should communicate via TCP/UDP to a remote device. My issue is that the UWP app successfully sends UDP messages to the remote device, but does not receive the replies.
Here follows the code extracted from the app (simplified):
async Task TestUdpIP()
{
// Writer to the DatagramSocket
DataWriter writer;
using (var udpClient = new DatagramSocket())
{
try
{
// UDP Socket binding
udpClient.MessageReceived += UdpClient_MessageReceived;
var controllerName = new Windows.Networking.HostName(controllerIpAddress.ToString());
await udpClient.BindEndpointAsync(controllerName, controllerIpPort.ToString());
var remoteHostName = new Windows.Networking.HostName(hostIpAddres.ToString());
await udpClient.ConnectAsync(remoteHostName, remoteHostPort.ToString());
// Create a message to send
string message = "Some message";
// Reset the counter of messages received back from the remote robot
messagesReceived = 0;
// Send the message
writer = new DataWriter(udpClient.OutputStream);
writer.WriteString(message);
await writer.StoreAsync();
// Wait for robot status messages
await Task.Delay(5000);
}
catch
{
}
}
}
void UdpClient_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
// Just increment the number of messages received
messagesReceived++;
}
However the UdpClient_MessageReceived handler does not fire. I'm sure that UDP messages are correctly sent from the UWP app and that the remote device replies back as shown in the following screenshot from Wireshark (the test has been taken on the same PC where the UWP app is running)
.
(IP Address, Port) details are shown in the following list to better explain the picture above
UWP application: (192.168.1.108, 19000) to send and receive.
Remote device: (192.168.1.152, 15999) to receive and (192.168.1.152, 54697) to send
Note: this is a similar question, where the answer says that for whatever reason the DatagramSocket should fire some messages before being able to receive. In my example a message is sent out however the message received handler does not fire anyway.
Note: The UWP app has been granted the internet (client) and the internet (client and server) capabilities
Note: I've tried also this (more readable) approach to bind the inbound/outbound datagram socket on the UWP app obtaining the same results:
// UDP Socket binding
var controllerName = new HostName(controllerIpAddress.ToString());
var remoteHostName = new HostName(hostIpAddres.ToString());
EndpointPair endpointpar = new EndpointPair(controllerName,
controllerIpPort.ToString(),
remoteHostName,
remoteHostPort.ToString());
udpClient.MessageReceived += UdpClient_MessageReceived;
await udpClient.ConnectAsync(endpointpar);
Where is the issue? Many thanks!
Please try to also add the Private Networks (Client & Server) capability in your app's manifest.
On other hand, you can try the Official DatagramSocket sample to see whether the both devices can communicate with each other.
After some experimenting, I came out with the idea of using two different DatagramSocket instances: one to send out UDP messages, and one to listen for incoming messages. With this code, I've been able to send UDP messages to the remote device (as before) and also I've been able to receive UDP messages from the remote device.
async Task TestUdpIP_DifferentPorts()
{
// Writer to the DatagramSocket
DataWriter writer;
// Inbound and outbound DatagramSocket
DatagramSocket udpListener = new DatagramSocket();
DatagramSocket udpSender = new DatagramSocket();
try
{
// String containing the serializaed message
string serializedMessage = "Some message";
var controllerName = new HostName(controllerIpAddress.ToString());
var remoteHostName = new HostName(hostIpAddres.ToString());
// Bind listener
udpListener.MessageReceived += UdpClient_MessageReceived;
await udpListener.BindEndpointAsync(controllerName, controllerIpPort.ToString());
// Connect sender
await udpSender.ConnectAsync(remoteHostName, remoteHostPort.ToString());
// Reset the counter of messages received back from the remote robot
messagesReceived = 0;
// Send the message
writer = new DataWriter(udpSender.OutputStream);
writer.WriteString(JsonConvert.SerializeObject(message));
await writer.StoreAsync();
// Wait for robot status messages
await Task.Delay(1000);
}
catch (Exception ex)
{
// Some exception handling
}
udpSender.Dispose();
udpListener.Dispose();
}
void UdpClient_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
// Just increment the number of messages received
messagesReceived++;
}
With this approach only the IP port (or service name) of the inbound listener needs to be specified. The framework will choose the next available outbound IP port.
Note: If I understand well the DatagramSocket.ConnectAsync(EndpointPair) documentation, the same DatagramSocket instance can be used to send and listen for incoming message, so I could not figure out the need for two different instances. From the documentation:
This ConnectAsync(EndPointPair) method on a DatagramSocket is used to define the local and remote endpoint where datagrams will be sent when using the OutputStream property. This method also restricts remote IP addresses of packets that will be accepted to the remote hostname in the endpointPair parameter. Only incoming packets that match the remote endpoint in the endpointPair parameter will trigger the MessageReceived event on the DatagramSocket.
For my thesis, I am using Smack to log a XMPP network that uses the MUC module.
Another software is currently sending IoT sensor data into different MUC rooms.
I'd like to know for every message sent into a MUC room, which users were in that room at the time of the message. Is this possible? I could use a messageListener to every muc room, however the listener only receives a message as an argument. Therefore I could not know who is logged into the room inside the listener method.
you can get all muc message in StanzaListener in xmpp. Please follow few steps to done this
Step 1. Declare as a global variables
ChatManagerListener chatListener;
Chat chat;
StanzaListener packetListener;
Step 2. Use this code in oncreate or in fragment
Note: Make sure you have connected with chat server.
packetListener = new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
if (packet instanceof Message) {
final Message message = (Message) packet;
}
}
};
XMPP.getInstance().getConnection(acitiviy)).addAsyncStanzaListener(stanzaListener, null);
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(XMPP.getInstance().getConnection(acitiviy)));
sdm.addFeature("jabber.org/protocol/si");
sdm.addFeature("http://jabber.org/protocol/si");
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
Step 3. Methods for one to one chat purposer
void sendMessage(String message) {
if (chat != null) {
try {
chat.sendMessage(message);
Message msg = new Message();
msg.setTo(JidCreate.bareFrom(jid));
msg.setFrom(XMPP.getInstance().getConnection(acitiviy)
.getUser());
ChatStateExtension ext = new ChatStateExtension(
ChatState.paused);
msg.addExtension(ext);
lastComposing = System.currentTimeMillis();
chat.sendMessage(msg);
} catch (SmackException.NotConnectedException e) {
} catch (Exception e) {
}
}
}
Step 4. On destroy
XMPP.getInstance().getConnection(acitiviy)).removeAsyncStanzaListener(stanzaListener);
Hope this will help you and if you want more information take a look from here. Thankyou
Nothing prervents you from calling Multi UserCaht.getParticipants() from within the listener. But be warned: If your goal is to determine the other receivers of receivers, then this approach is fragile. I also suggest to think about using PubSub instead of MUC for your IoT use case.
I have created an application for FIX transactions using QuickFIX c++ API. The application is connecting to the server but the server sends "Provide UserName<553>" message. I looked for and result and found that i need to add username and password to the toAdmin method created this following code to in order to achieve that
void Application::toAdmin( FIX::Message& message, const FIX::SessionID& sessionID)
{
if (FIX::MsgType_Logon == message.getHeader().getField(FIX::FIELD::MsgType))
{
FIX44::Logon& logon_message = dynamic_cast<FIX44::Logon&>(message);
logon_message.setField(FIX::Username("my_username"));
logon_message.setField(FIX::Password("my_password"));
}
}
But then it throws and Exception. Please suggest what to do
remove this line and exception is handled
FIX44::Logon& logon_message = dynamic_cast<FIX44::Logon&>(message);
after that Put it
message.setField(FIX::Username("my_username"));
```````
message.setField(FIX::Password("my_password"));
Hi is there any way to do android xmpp client which will be able to get message receive confirmation (XEP-0184) I read that there is XEP-0184 in smack but normal smack is not working with android(or I can't do it) there is always SASL authentication exception.
Smack received support for XEP-0184 with SMACK-331. You can't use Smack < 4.1 directly under Android, you need Smack 4.1 (or higher).
You can read more about Smack's XEP-0184 API in the javadoc of DeliveryReceiptManager.
Yes this works with normal Smack.
Gradle Dependencies
compile "org.igniterealtime.smack:smack-android:4.1.0"
compile "org.igniterealtime.smack:smack-tcp:4.1.0"
compile "org.igniterealtime.smack:smack-extensions:4.1.0" // <-- XEP-0184 classes
Prepare the XMPPTCPConnection i.e. before you connect() wire up a handler for when you get a delivery receipt
DeliveryReceiptManager.getInstanceFor(mConnection).addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(String fromJid, String toJid, String deliveryReceiptId, Stanza stanza) {
Log.d(TAG, "onReceiptReceived: from: " + fromJid + " to: " + toJid + " deliveryReceiptId: " + deliveryReceiptId + " stanza: " + stanza);
}
});
When sending a message, ensure you include a MessageReceiptRequest
Chat chat;
if (StringUtils.isNullOrEmpty(threadId)) {
chat = getChatManager().createChat(to);
Log.d(TAG, "sendMessage: no thread id so created Chat with id: " + chat.getThreadID());
} else {
chat = getChatManager().getThreadChat(threadId);
Log.d(TAG, "sendMessage: thread id was used to continue this chat");
}
Message message = new Message(to);
message.addBody("EN", messageText);
String deliveryReceiptId = DeliveryReceiptRequest.addTo(message);
chat.sendMessage(message);
Log.d(TAG, "sendMessage: deliveryReceiptId for this message is: " + deliveryReceiptId);
All done
Now, you can tell when a sent message has been received by the other side because the deliveryReceiptId obtained in the Chat.sendMessage(Message) code above will be logged by the onReceiptReceived callback set up earlier.