guys is it possible to know if the sim card has a balance/load using android Studio.
i just want to notified if sim card don't have a load.
I have a switch, which is use to send a constant text using Smsmanager...
here is my example
if i try to switch outlet 1 (insert trigger where in no load detected) then the switch will not on
By the way I do send that constant message using this
//function o send message sms
private void sendMessage(String phoneNo, String Message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Message, null, null);
Toast.makeText(getApplicationContext(), "Switching...", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Message Sending Failed", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Related
I'm subscribing to a MQTT Topic(in my case it is app unique user id).I'm using AWS IOT core services for subscription.Whenever home screen opens up and I got connected callback from awsConnectClient,I make the call for subscription. Now what is happening if app gets open up three times It subscribed to the same topic 3 time.Now whenever any message publish to that topic.It received by app 3 times.
Now what I want to do that I want to know that if this userId is already subscribed from this device I would not make a call for subscription again from same device.
One approach could be If I save in my app that I had already subscribed to this topic and do not make the call for subscription again. but I doubt if this approach could be correct for all scenarios.Could it be possible that we could drive this logic from the server end only, if any aws iot api could give me that this is already subscribed.
fun connectClick() {
Log.d(TAG, "clientId = $clientId")
try {
mqttManager.connect(clientKeyStore) { status, throwable ->
Log.d(TAG, "Status = " + status.toString())
var formattedStatus = String.format(getString(R.string.status_msg),status.toString())
if (status == AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.Connected) {
Log.i(TAG, " subscribed to - " + VoiceXPreference(this).rosterName)
unsubscribe()
subscribeClick(VoiceXPreference(this).rosterName)
}
runOnUiThread {
tv_iot_status.text = formattedStatus
if (throwable != null) {
Log.e(TAG, "Connection error.", throwable)
}
}
}
} catch (e: Exception) {
Log.e(TAG, "Connection error.", e)
}
}
Above is my subscription code.Although I'm always unsubscribing before subscribing but this is not working for me.
Following is my initClient call which makes the connection request. I have added the if check if mqttManager is already initialised first disconnect and then make connect request. Although I have put initRequest inside onCreate() call back of app screen which calls only once when the app opens up. I have checked the logs it is being called only once.
AWSMobileClient.getInstance().initialize(this, object : Callback<UserStateDetails> {
override fun onResult(result: UserStateDetails) {
Log.i(TAG,"connect request called");
if(mqttManager != null){
mqttManager?.disconnect()
}
initIoTClient()
}
override fun onError(e: Exception) {
Log.e(TAG, "onError: ", e)
}
})
Following is my subscribe code snippet which is subscribing to unique userId
fun subscribeClick(topic: String) {
Log.d(TAG, "topic = $topic")
try {
mqttManager?.subscribeToTopic(topic, AWSIotMqttQos.QOS0,
{ topic, data ->
runOnUiThread {
try {
val message = String(data, Charsets.UTF_8)
Log.d(TAG, "Message arrived:")
Log.d(TAG, " Topic: $topic")
Log.d(TAG, " Message: $message")
val gson = Gson()
val notificationModel = gson.fromJson(message, NotificationModel::class.java)
var orderServiceMapperResponseModel = OrderServiceMapperResponseModel()
orderServiceMapperResponseModel.seatId = notificationModel.seatId
orderServiceMapperResponseModel.serviceName = notificationModel.service
orderServiceMapperResponseModel.id = notificationModel.id
orderServiceMapperResponseModel.createdDate = notificationModel.createdDate
serviceList.add(orderServiceMapperResponseModel)
if (isPictureInPictureMode) {
if (isShownNotification) {
updateNotificationCount()
} else {
updatePIPWindowContent()
}
} else {
updateAdapterDataSource()
}
} catch (e: UnsupportedEncodingException) {
Log.e(TAG, "Message encoding error.", e)
}
}
})
} catch (e: Exception) {
Log.e(TAG, "Subscription error.", e)
}
}
I'm also always making disconnect() request inside onDestroy() of my app screen
mqttManager?.disconnect()
But Still I'm getting 3 subscription messages instead of 1.
You receive 3 duplicated messages not because you subscribe 3 times but because you create 3 individual connections.
The MQTT specification clearly states that
If a Server receives a SUBSCRIBE Packet containing a Topic Filter that is identical to an existing Subscription’s Topic Filter then it MUST completely replace that existing Subscription with a new Subscription.
meaning duplicated subscriptions per connection never happen, unless the server has a broken implementation.
Your code looks like that it never send disconnect requests while a new connection is created whenever the code block is invoked.
You should keep a single MQTT session, or make sure you close the connection when the app is closed.
I'm implementing email server in asp.net core 2.0 with mailkit. About my scenario, I have to send email and need to return feedback with the email sent status.I have implemented email send part and it's working fine.
I know try catch is a one option.But it's not enough with my situation. Because exception will be occurred only when network error or authentication failure. But exception won't occur if some receiver email is invalid.
I have to return email sent status for each email in List.But If there is invalid email or another error I can't catch it.
I saw a event called MessageSent. But I don't know to implement that event and whether it's match with my condition.
This is my full code.
public void SendEmail(List<EmailMessage> emailMessages)
{
List<MimeMessage> emailQueue = new List<MimeMessage>();
foreach (EmailMessage emailMessage in emailMessages)
{
var message = new MimeMessage();
message.MessageId = emailMessage.MessageId;
message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
message.Subject = emailMessage.Subject;
message.Body = new TextPart(TextFormat.Html)
{
Text = emailMessage.Content
};
emailQueue.Add(message);
}
using (var emailClient = new SmtpClient())
{
emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, _emailConfiguration.EnableSSL);
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);
foreach (MimeMessage email in emailQueue)
{
try
{
emailClient.Send(email);
}
catch (Exception ex)
{
}
}
emailClient.Disconnect(true);
}
}
You need override the GetDeliveryStatusNotifications class, something like this:
using MailKit;
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Collections.Generic;
namespace YourProject
{
public class CustomSmtpClient : SmtpClient
{
protected override DeliveryStatusNotification? GetDeliveryStatusNotifications(MimeMessage message, MailboxAddress mailbox)
{
if (!(message.Body is MultipartReport report) || report.ReportType == null || !report.ReportType.Equals("delivery-status", StringComparison.OrdinalIgnoreCase))
return default;
report.OfType<MessageDeliveryStatus>().ToList().ForEach(x => {
x.StatusGroups.Where(y => y.Contains("Action") && y.Contains("Final-Recipient")).ToList().ForEach(z => {
switch (z["Action"])
{
case "failed":
Console.WriteLine("Delivery of message {0} failed for {1}", z["Action"], z["Final-Recipient"]);
break;
case "delayed":
Console.WriteLine("Delivery of message {0} has been delayed for {1}", z["Action"], z["Final-Recipient"]);
break;
case "delivered":
Console.WriteLine("Delivery of message {0} has been delivered to {1}", z["Action"], z["Final-Recipient"]);
break;
case "relayed":
Console.WriteLine("Delivery of message {0} has been relayed for {1}", z["Action"], z["Final-Recipient"]);
break;
case "expanded":
Console.WriteLine("Delivery of message {0} has been delivered to {1} and relayed to the the expanded recipients", z["Action"], z["Final-Recipient"]);
break;
}
});
});
return default;
}
}
}
There is a good explanation of MailKit's MessageSent here - https://stackoverflow.com/a/48132905/1105937
TLDR: Use the try/catch as that will tell you if the message was sent or not..
var IsEmailSent = false;
try
{
emailClient.Send(email);
IsEmailSent = true;
}
catch (Exception ex)
{
}
You won't be able to tell if the users email address does not exist for privacy issues, but the person who sent the email will get any bounce back messages.
If you send out all the emails using a generic email address like do-not-reply#my-cool-app.com then add the app user (the person sending the email) as a "reply to" email so they will recieve a copy of any bounce backs as they occur.
We can get MessageSent like this.It's confirm email is send by smtp service.But it's not returning email receive status.
Eg: my smtp server is gmail and i'm sending email to yahoo email address. Using MessageSent we can confirm that email is dispatch from smtp gmail client.But we can't get the received status of yahoo email.
foreach (MimeMessage email in emailQueue)
{
try
{
emailClient.MessageSent += OnMessageSent;
emailClient.Send(email);
}
catch (Exception ex)
{
}
}
------------------------------------------------------------------------------
void OnMessageSent(object sender, MessageSentEventArgs e)
{
Console.WriteLine("The message was sent!");
}
While creating a GCM client application, asynctask is giving compilation errors.
OnCreate we are calling registerBackgrouod which will check whether gcm instance is running or not, if not create one.
But asyntask is giving error : "Asynctask cannot be resolved to a type"
private void registerBackground() {
new AsyncTask() {
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the message
// using the 'from' address in the message.
// Save the regid - no need to register again.
setRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
As already observed by the AlexBcn, and according to the documentation of AsyncTask, you would pass to the AsyncTask three types as param. Because you want to return the payload of the GCM push notification as a String, you would invoke AsyncTask<Void, Void, String>
So the correct code snippet of GCM client is:
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}.execute(null, null, null);
}
This is because of the params you pass in to Async task.
For further help:
I recently uploaded the fully functional GCM java client to my Github Account:
GCM Android Client
It has got both server and client implementation.
I am trying to open my bitcoin-qt wallet with bitcoinj. I have this simple code:
private static final File WALLET_FILE = new File("__PATH__");
public static void main(String[] args) {
Wallet wallet;
try {
wallet = Wallet.loadFromFile(WALLET_FILE);
} catch (IOException e) {
System.out.println("Couldn't open wallet: " + e);
return;
}
System.out.println("Balance: " + wallet.getBalance());
}
I get an error:
Couldn't open wallet: com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
I check the status on bitcoin-qt and my wallet seems synchronize.
I am far from an expert in bitcoin, but I wonder if you know the solution.
apparently this is not possible, I asked the question on bitcoin stackechange and they told me it is not the same format:
https://bitcoin.stackexchange.com/questions/8463/open-bitcoin-qt-wallet-with-bitcoinj/8466?noredirect=1#8466
I'm facing problems to send e-mails with Java Mail on Glashfish 3.1.1.
The server doesn't throw any Exception, just send an empty message with only header to recipient.
Running Java Mail without the Glashfish, everything works fine.
public void sendHtmlMessage(String subject, String html){
// Creates a email Session and
// and Authenticator attached to it
Session session = getMailSession();
try{
MimeMessage message = createMessage(session, subject, MailSender.MIME_Type.TEXT_HTML, html); // creates message
transportSMTPMessage(session, message); // transport message
} catch(AddressException e){ log("Internet address is invalid!"); e.printStackTrace(); }
catch(NoSuchProviderException e){ log("Host is invalid!"); e.printStackTrace(); }
catch(MessagingException e){ log("Message is invalid!"); e.printStackTrace(); }
catch(Exception e){ log("Gereric Exception!"); e.printStackTrace(); }
}
// Helper to obtain Mail Session
private Session getMailSession(){
Properties props = new Properties();
return Session.getInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
}
// Helper to create MimeMessage
private MimeMessage createMessage(Session session, String subject, MailSender.MIME_Type mime, String content)
throws AddressException, MessagingException{
// Some code to create the message...
message.saveChanges();
return message;
}
// Helper to transpot the message thru the SMTP protocol
private void transportSMTPMessage(Session session, Message message)
throws NoSuchProviderException, MessagingException{
// Creates the transport connection and
// Send the message
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
I think everything's fine with the code, I just don't understand, why it doesn't work on Glassfish?
I'd be grateful if someone help me.
Thanks in advance.
Call session.setDebug(true) in your application after creating the Session. Then look at the server log file to see if the JavaMail debug output has any clues about what's going wrong. I'm assuming you're not getting any exceptions.