Get information of text message received in android 6.0.1 Marshmallow API: 23 - android-6.0-marshmallow

I want to get information from the text message received. Information like Body of text sender's phone number etc. I am trying to do it with the code below. I have permissions in the Manifest.
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "n";
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
It works. But not on Marshmallow 6.0.1 API:23. Also, SmsMessage, createFromPdu and getMessageBody all of them are deprecated. I can not find a way to do it in Marshmallow. Please, give me the solution.

BroadcastReceiver smsReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT < 19) {
if(Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs;
String sender;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
sender = msgs[i].getOriginatingAddress();
String messageBody = msgs[i].getMessageBody();
// do things here
}
}
}catch(Exception e){
Log.d("Exception caught",e.getMessage());
}
}
}
}
else{
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String messageBody = smsMessage.getMessageBody();
String sender = smsMessage.getOriginatingAddress();
// do things here
}
}
}
}
};
Dont forget to register receiver. OnCreate:
IntentFilter intentFilter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
intentFilter.setPriority(990);
registerReceiver(smsReceiver, intentFilter);
And also unregister.
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
threadTimer.interrupt();
}

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

SignalR. Timer is not stopping on the server

We are using SignalR for information exchange.
When the web browser is connected a timer starts, but it is not stopping when user close the browser.
Here is the code. starttimer function runs when browser connected.
When user disconnect the browser, timer still running on the server.
[HubName("myChatHub")]
public class InboundCallsDataShare : Hub
{
private OverrideTimer timer ;
private List<GroupNConnectionId> groupsList = new List<GroupNConnectionId>();
public void send(string message)
{
Clients.All.addMessage(message);
//Clients..addMessage(message);
}
public void starttimer(string queue)
{
//var connectionId = this.Context.ConnectionId;
//GroupNConnectionId objGroupNConnectionId=new GroupNConnectionId();
//objGroupNConnectionId.Group = queue;
//objGroupNConnectionId.ConnectionID = connectionId;
//if(groupsList.Contains(objGroupNConnectionId))return;
//////////////////////////////////////////////////////
//groupsList.Add(objGroupNConnectionId);
Groups.Add(this.Context.ConnectionId, queue);
timer = new OverrideTimer(queue);
timer.Interval = 15000;
timer.Elapsed +=new EventHandler<BtElapsedEventArgs>(timer_Elapsed);
//first time call
timer_Elapsed(timer,new BtElapsedEventArgs(){Queue = queue});
//ends
timer.Start();
Console.WriteLine("Timer for queue " +queue);
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected()
{
//timer.Stop();
return base.OnDisconnected();
}
public void getdatafromxml(string queue)
{
string list = (new Random()).Next(1, 10000).ToString();
Clients.All.getList(list);
//Clients..addMessage(message);
}
public ICBMObject GetInterationList(string queue)
{
//ININInterations.QueueListViewItemData _obj = new ININInterations.QueueListViewItemData();
return GetInboundCallCountFromXML(queue);
//return _obj.MainFunctionIB();
}
void timer_Elapsed(object sender, BtElapsedEventArgs e)
{
ICBMObject objICBMObject = GetInboundCallCountFromXML(e.Queue);
Clients.Group(e.Queue).getList(objICBMObject);
CreateFile(e.Queue);
//Clients.All.getList(objICBMObject);
}
private void CreateFile(string queue)
{
string path = #"D:\t.txt";
string text = File.ReadAllText(path);
text += queue+ DateTime.Now.ToString() + Environment.NewLine;
File.WriteAllText(path, text);
}
public ICBMObject GetInboundCallCountFromXML(string queue)
{
FileStream fs = null;
int totalInboundCalls = 0,
totalInboundCallsUnassigned = 0;
string longestDuration = "";
bool updateText = false;
try
{
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
int i = 0;
string str = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "InboundXML/" + queue + ".xml",
FileMode.Open, FileAccess.Read);
if (fs.CanRead)
{
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName(queue);
for (i = 0; i <= xmlnode.Count - 1; i++)
{
totalInboundCalls = Convert.ToInt32(xmlnode[i].ChildNodes.Item(0).InnerText.Trim());
totalInboundCallsUnassigned = Convert.ToInt32(xmlnode[i].ChildNodes.Item(1).InnerText.Trim());
longestDuration = xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
}
updateText = true;
}
}
catch (Exception)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
return new ICBMObject()
{
TotalInboundCalls = totalInboundCalls,
TotalInboundCallsUnassigned = totalInboundCallsUnassigned,
LongestDuration = longestDuration,
UpdateText = updateText
//string.Format("{0:D2}:{1:D2}:{2:D2}",
// _LongetInbound.Hours,
// _LongetInbound.Minutes,
// _LongetInbound.Seconds)
};
}
}
Besides the fact that its commented out? Did you put a break point on the timer to see if its getting hit at all? It might be that there is a delay in calling the onDisconnect, if the timeout property is set too large, it might not fire. it might be entering onReconnected if it does not know the client is closed.

HttpModule Web Api

I'm trying to get an auth basic on my web api. I've written a simple HttpModule to check it
public class BasicAuth : IHttpModule
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
private const string Realm = "MyRealm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthorizeRequest += new EventHandler(OnApplicationAuthenticateRequest);
context.EndRequest += new EventHandler(OnApplicationEndRequest);
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private bool CheckPassword(string username, string password)
{
var parameters = new DynamicParameters();
parameters.Add("#UserName", username);
parameters.Add("#Password", password);
con.Open();
try
{
var query = //query to db to check username and password
return query.Count() == 1 ? true : false;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
private bool AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
if (AuthenticateUser(authHeaderVal.Parameter))
{
//user is authenticated
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
catch
{
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
well, this code works pretty well, except the fact it asks for basic auth even on controller I don't put the [Authorize] tag on. And when it occurs, it gives the right data back.
Let me explain:
My HistoryController has [Authorize] attribute, to make a POST request I have to send Header auth to get data, if I don't do it, I receive 401 status code and a custom error.
My HomeController doesn't have [Authorize] attribute, if i make a get request on my homepage, the browser popups the authentication request, but if I hit Cancel it shows my home page. (The page is sent back with 401 error, checked with fiddler).
What am I doing wrong?

android volley posting binary body

Scenario - upload binary data in the body of a post, handle a response body containing JSON.
How to do the following using Volley?
curl -X POST -H "X-Application-Id: 3KxPB" -H "X-REST-API-Key: jkuI9" -H "Content-Type: audio/3gp" --data-binary '#test.3gp' https://host/1/files/audio
IMO - there is a gap in Volley handling binary POST body types that apache httpclient handles in subclasses of abstracthttpentity. If buffered binary data generated on the phone by camera, microphone, or other binary output sensors needs a mechanism to be wrapped and written to the body of a POST how to do it in volley?
I've looked at PoolingByteArrayOutputStream and would like to do something like fill the buffer and get the PBAOutStrm ,writing to PBAOutStrm from the buffer and then flipping OutStrm to InputStream and then wrap it in the body of a POST request as something like a ByteArrayEntity. I cant see how to do that in volley.
To send binary data you can do something like what I did in this answer How to send a “multipart/form-data” POST in Android with Volley .
I was able to solve this using a Volley GsonRequest:
public class MainActivity extends AppCompatActivity {
String url = "https://arcane-anchorage-34204.herokuapp.com/handleCode";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jsonBody = null;
try {
jsonBody = new JSONObject ("{\"code\":\"NZ4UBUB\"}");
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error e = " + e, Toast.LENGTH_SHORT).show();
}
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
RequestQueue queue = Volley.newRequestQueue(this);
GsonRequest<Routine[]> gsonRequest = new GsonRequest<Routine[]>(Request.Method.POST, url, Routine[].class, headers, new Response.Listener<Routine[]>() {
#Override
public void onResponse(Routine[] routineData) {
TextView serverData = (TextView)findViewById(R.id.serverData);
String complete = "";
String repeat = "";
String hold = "";
String perform = "";
String txtData = "";
for (int i = 0; i < routineData.length; i++) {
complete = (routineData[i].instructions.complete != null) ? "Complete: " + routineData[i].instructions.complete : "";
repeat = (routineData[i].instructions.repeat != null) ? "Repeat: " + routineData[i].instructions.repeat : "";
hold = (routineData[i].instructions.hold != null) ? "Hold: " + routineData[i].instructions.hold : "";
perform = (routineData[i].instructions.perform != null) ? "Perform: " + routineData[i].instructions.perform : "";
txtData += "DESCRIPTION: " + routineData[i].description[0] + ": " + routineData[i].description[1] + ", " + complete + ", " + repeat + ", " + hold + ", " + perform + " ";
}
serverData.setText("Response: " + txtData);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
TextView serverData = (TextView)findViewById(R.id.serverData);
serverData.setText("Response: " + volleyError.toString());
}
}, jsonBody);
queue.add(gsonRequest);
}
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
private JSONObject parameters = null;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener, JSONObject parameters) {
this(method, url, clazz, headers, listener, errorListener);
this.parameters = parameters;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return parameters.toString().getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException e) {
}
return null;
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i("RESPONSE", json);
return Response.success(
gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
}

How to resend email using SendAsync() in asp.net

I am using SendAsync to send an email. The reason I'm using async is simply to free up the UI rather than send multiple emails.
I have created the following callback event:
static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
var client = sender as SmtpClient;
var message = e.UserState as MailMessage;
if (e.Error.IsNotNull())
{
if (e.Error is SmtpFailedRecipientException)
{
var status = ((SmtpFailedRecipientException)(e.Error)).StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable ||
status == SmtpStatusCode.TransactionFailed)
{
// a new message!
}
else
{
// TODO: Log other uncaught recipient failures
}
}
else
{
// TODO: Log all other failure reasons
}
}
client.Dispose();
message.Dispose();
}
As you can see I'm attempting to catch some recipients failures. If I find such an exception I want to try and resend the email.
I'm trying to work out how to resend the email safely. I'm thinking to create a new SmtpClient rather than reuse the existing one, but to be honest, I'm fairly new to .net and I'm not so sure of the implications.
Any advice would be appreciated.
Sending email asynchronously without delaying response back to the client(UI) requires a Backgroundworker in .Net. I implemented this on my site and will share the class source code with you.
using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel; //Background worker namespace
using System.Net.Mail;
/// <summary>
/// Summary description for ClassName
/// </summary>
///
public class postmail
{
BackgroundWorker bw = new BackgroundWorker();
string email1, subject1, message1, failedemails;
public postmail(string email, string subject, string message)
{
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = false;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
email1 = email;
subject1 = subject;
message1 = message;
}
public postmail()
{
// TODO: Complete member initialization
}
public void startsending() {
bw.RunWorkerAsync();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Flush(); // send all buffered output to client
HttpContext.Current.Response.End();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
var finalemail = email1.Split(new[] { ',' }, StringSplitOptions.None);
//loop through the email addresses and send individually
for (int c = 0; c < finalemail.Length; c++) {
try
{
MailMessage mailMessage = new MailMessage();
// Sender Address
mailMessage.From = new MailAddress("emailaddress");
// Recepient Address
mailMessage.To.Add(finalemail[c].ToString());
// Subject
mailMessage.Subject = subject1.ToString();
// Body
mailMessage.Body = message1.ToString();
// format of mail message
mailMessage.IsBodyHtml = true;
// new instance of Smtpclient
SmtpClient mailSmtpClient = new SmtpClient("mail server");
//mailSmtpClient.EnableSsl = true;
mailSmtpClient.Credentials = new System.Net.NetworkCredential("emailaddress", "password");
// mail sent
Object userState = mailMessage;
mailSmtpClient.SendAsync(mailMessage, userState);
}
catch (Exception exc)
{
//fix for you
var ext = exc.ToString(); //catch exception for failed message
failedemails = failedemails + finalemail[c] + ","; //create a string of failed emails
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//called when the background process is done working
if(failedemails != null){
postmail(failedemails, subject1, message1); //resend the failed email
startsending();
}
}
}
Your concept might not be exact like mine but the key methods are:
Create an event handlers for the BackgroundWorker.
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = false;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//Send your mail
}
catch (Exception exc)
{
//Catch exception here and call the resend method
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do something after completion
}
The fix i made for you was to build a string of all failed addresses, then resend them after the backgroundworker is done working. cheers!!

Resources