Reading incoming SMS but not able to update EditText in android - android

I am getting the message from BroadcastReceiver but I am unable to update the EditText in my Activity. Message displayed in logcat using Log.i() but EditText is not updating.
my receiver class is as follows:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
public class IncomingSms extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
final Bundle bundle = intent.getExtras();
try {
if (bundle != null)
{
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj .length; i++)
{
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber ;
String message = currentMessage .getDisplayMessageBody();
try
{
if (senderNum .equals("TA-DOCOMO"))
{
Otp Sms = new Otp();
Sms.recivedSms(message );
}
}
catch(Exception e){}
}
}
} catch (Exception e)
{
}
}
}
My Activity class
public class Otp extends Activity
{
static EditText OtpNumber;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.otp);
OtpNumber= (EditText) findViewById(R.id.txtName);
}
public void recivedSms(String message)
{
try
{
OtpNumber.setText(message);
}
catch (Exception e)
{
}
}
}
in mainfest file
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" >
</uses-permission>
<receiver android:name=".IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
i have followed this link

bro if your edit text is in another activity then you need to transfer the data (otp) to another activity using intent
here is the reference

Related

How to send Intent to SMS Receiver?

I would like a send an intent to this receiver from another application, which handles SMS. I am quite new to this SMS handling. Can someone kindly guide me on what intent,I mean, how and what and intent should have to execute this piece of receiver code. Thanks.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
try {
Object[] objArr = (Object[]) extras.get("pdus");
for (Object obj : objArr) {
SmsMessage createFromPdu = SmsMessage.createFromPdu((byte[]) obj);
String displayOriginatingAddress = createFromPdu.getDisplayOriginatingAddress();
String displayMessageBody = createFromPdu.getDisplayMessageBody();
try {
if (displayOriginatingAddress.contains("MADAPP")) {
if (displayMessageBody.contains("The PIN is")) {
Toast.makeText(context, displayMessageBody, 1).show();
}
if (displayMessageBody.contains("successfully validated")) {
displayMessageBody.contains("activating Pockets");
}
}
} catch (Exception e) {
}
}
} catch (Exception e2) {
}
}
}
}
Try this code
write this in your manifest
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
For more description
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87

UDP Client on Android

I have made an UDP Server on a Wi-Fi demo board and test it using and android App (UDP Sender).
I created my own UDP client apps on Android, but it doesn't work.
I created and configured well the socket port and the IPaddress but the app doesn't work and I don't know why.
PS : In the manifest I added the uses-permission to access to the Wi-Fi
her is my simple code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Udp_Client extends Activity {
/** Called when the activity is first created. */
TextView txt5,txt1;
byte[] send_data = new byte[1024];
Button hello;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt1 = (TextView)findViewById(R.id.textView1);
txt5 = (TextView)findViewById(R.id.textView5);
hello = (Button) findViewById(R.id.button1);
hello.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
client();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void client() throws IOException{
String str="Hello";
int port = 50000;
DatagramSocket client_socket = new DatagramSocket(port);
InetAddress IPAddress = InetAddress.getByName("192.168.0.1");
send_data = str.getBytes();
DatagramPacket send_packet = new DatagramPacket(send_data,str.length(), IPAddress, port);
//client_socket.setBroadcast(true);
client_socket.send(send_packet);
client_socket.close();
}
}
[1]: http://i.stack.imgur.com/aXPhf.png
I found the solution for the problem
The problem was in the manifest
Here is my new code and my manifest
The main in wich I call the UDP_Client :
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView sceen = null;
private Button launch = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sceen = (TextView)findViewById(R.id.textView1);
launch = (Button)findViewById(R.id.udpbutton);
launch.setOnClickListener(this);
launch.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
//UDP Client erstellen
UDP_Client Client = new UDP_Client();
Client.Message = "Your message";
Client.NachrichtSenden();
}
}
The code of my UDP_Client
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;
public class UDP_Client
{
private InetAddress IPAddress = null;
private String message = "Hello Android!" ;
private AsyncTask<Void, Void, Void> async_cient;
public String Message;
#SuppressLint("NewApi")
public void NachrichtSenden()
{
async_cient = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
DatagramSocket ds = null;
try
{
byte[] ipAddr = new byte[]{ (byte) 192, (byte) 168,43, (byte) 157};
InetAddress addr = InetAddress.getByAddress(ipAddr);
ds = new DatagramSocket(5000);
DatagramPacket dp;
dp = new DatagramPacket(Message.getBytes(), Message.getBytes().length, addr, 50000);
ds.setBroadcast(true);
ds.send(dp);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else async_cient.execute();
}
}
The manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.udp_server"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I added the part of code in my manifest
hope that it will help someone in the future ;)
I think you miss this:
public void connect (InetAddress address, int port)
Of the DataGramSocket Object.
Try:
client_socket.connect(IPAddress, port);
client_socket.send(send_packet);

How to call BroadCast receiver class from the main activity

i'm developing an android application which will filter out the messages from a particular number and read its message body.
I have written a class which extends to broadcast receiver as follows.
package com.tutecentral.restfulapiclient;
import android.content.BroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class Filter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle extras = intent.getExtras();
if (extras != null) {
Object[] pdus = (Object[])extras.get("pdus");
if (pdus.length < 1) return;
StringBuilder sb = new StringBuilder();
String sender = null;
for (int i = 0; i < pdus.length; i++) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
if (sender == null){
sender = message.getOriginatingAddress(); //get the sender
}
String text = message.getMessageBody(); //get the message body
Log.d("my broadcast","works");
//System.out.println("tsettexttt"+text);
if (text != null){
sb.append(text);
}
System.out.println("texttst"+text);
}
String number = "+94716355075"; //add the number
abortBroadcast();
}
}
}
}
Now what i want to do is to call this class from the main activity and also get the results from this class (String text : which holds the message body) so that i can use that value for other options in the app.
I went through every stackoverflow question posted regarding this but couldn't find the answer. Please be kind enough to help me out!!
Thanks in advance,
Regards
You can open your activity from the BroadcastReceiver passing some parameters, once the activity is open if certain parameters have been passed to this activity, call the method you want.
Hope it helps!
Edit: check this code out!
#Override
public void onReceive(Context context, Intent intent) {
//Do your normal work...
//start activity
Intent i = new Intent(context,YourActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("param","value"); //your parameter
context.startActivity(i);
}

Declaring global variables in android [duplicate]

This question already has answers here:
How to declare global variables in Android?
(17 answers)
Closed 9 years ago.
I went through many pages, but couldn't understand properly how to declare a class to contain global variables and its declaration in manifest file (most important thing, need some extra concentration on that)
The class
global file
/**
*
*/
package com.furniture;
/**
* #author sanketh
*
*/
public class Gloabal extends ap{
public String refer="";
public int set=0;
public String getData(){
return this.refer;
}
public void setData(String d,int i){
this.refer=d;
set=i;
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.furniture"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".Gloabal">
<activity
android:name="com.furniture.login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"></activity>
<activity android:name=".passforgot"></activity>
<activity android:name=".newuser"></activity>
<activity android:name=".settings"></activity>
<receiver android:name=".smsreciever">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
somefile
package com.furniture;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class smsreciever extends BroadcastReceiver
{
public String value;
#Override
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---
// Intent i1=new Intent();
//((Gloabal)this.get).setData(str);
// Gloabal g1=new Gloabal();
Global g = (Global)getApplication();
int data=g.getData();
Log.v("sanketh","smsreciver value of str:"+str);
int a=1;
g1.setData(str,a);
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
Here i want to set the data to it...
Global g = (Global)getApplication(); // this line gives error for get application
Apart from using Application to create Global Variables, you can create a regular class to hold your variables. Right now, I am using this:
public class GlobalVar {
public String getGlobalVar1() {
return GlobalVar1;
}
public void setGlobalVar1(String GlobalVar1) {
this.GlobalVar1 = GlobalVar1;
}
private String GlobalVar1 = "";
static {
instance = new GlobalVar();
}
private GlobalVar() {
}
public static GlobalVar getInstance() {
return GlobalVar.instance;
}
}
For setting a new value to your GlobalVar1 :
GlobalVar.getInstance().setGlobalVar1(value);
And for getting the value:
GlobalVar.getInstance().getGlobalVar1;
public class GlobalState extends Application {
private int gameScore = 0;
public int getGameScore() {
return gameScore;
}
public void setGameScore(int gameScore) {
this.gameScore = gameScore;
}
public void incrementScore(){
gameScore++;
}
Manifest file
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:name="GlobalState" >
<!-- component definitions -->
</application>
Usage in Activity
GlobalState state = ((GlobalState) getApplicationContext());

NFC Intent Filter - Sending Message Non-Main Activity

I am sure this is simple but I cannot figure it out. All I am trying to do is send a message via NFC. The code I have work perfectly if I am sending it to the main activity, but I don't know how to send it to a different activity. I have looked over both the NFC and Intent Filter articles on the Android Developer pages but am still not sure exactly how to do this. I am trying to send it to a NFC activity, I will post my manifest and NFC class below.
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.justbaumdev.tagsense"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo" >
<activity
android:name=".TagSense"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.justbaumdev.tagsense.NFC" android:exported="false">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/com.justbaumdev.tagsense" />
</intent-filter>
</activity>
</application>
</manifest>
NFC Class:
package com.justbaumdev.tagsense;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.widget.Toast;
public class NFC extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfc);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // Check for available NFC Adapter
if (mNfcAdapter == null)
{
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
else
{
mNfcAdapter.setNdefPushMessageCallback(this, this); // Register callback to set NDEF message
mNfcAdapter.setOnNdefPushCompleteCallback(this, this); // Register callback to listen for message-sent success
}
}
#Override
public void onResume() {
super.onResume();
// Check to see that the Activity started due to an Android Beam
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
#Override
public NdefMessage createNdefMessage(NfcEvent event) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
String newMac = mac.substring(0, 2);
mac = mac.substring(2);
int hex = Integer.parseInt(newMac, 16) + 0x2;
newMac = Integer.toHexString(hex);
String text = newMac + mac;
NdefMessage msg = new NdefMessage(NdefRecord.createMime(
"application/com.justbaumdev.tagsense", text.getBytes()));
return msg;
}
/**
* Implementation for the OnNdefPushCompleteCallback interface
*/
#Override
public void onNdefPushComplete(NfcEvent arg0) {
// A handler is needed to send messages to the activity when this
// callback occurs, because it happens from a binder thread
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
/** This handler receives a message from onNdefPushComplete */
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SENT:
Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
break;
}
}
};
/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
//TODO Currently overwrites any previously saved mac addresses. Get FB ID as value. Auto end activity.
void processIntent(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
//textView.setText(new String(msg.getRecords()[0].getPayload()));
String payload = new String(msg.getRecords()[0].getPayload());
Toast.makeText(this, new String(msg.getRecords()[0].getPayload()), Toast.LENGTH_LONG).show();
SharedPreferences appData = getSharedPreferences("appData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
String addresses = appData.getString("mac_address", null);
if(addresses==null)
{
JSONArray addressArray = new JSONArray();
addressArray.put(payload);
addresses = addressArray.toString();
}
else
{
try {
if(!addresses.contains(payload))
{
JSONArray addressArray = new JSONArray(addresses);
addressArray.put(payload);
addresses = addressArray.toString();
}
} catch (JSONException e) {
Toast.makeText(this, "Error adding new friend. Please try again.", Toast.LENGTH_SHORT).show();
}
}
editor.putString("mac_address", addresses);
editor.commit();
}
}
Thanks for your help.
Remove the attribute android:exported="false". See also https://stackoverflow.com/a/12719621/1202968

Categories

Resources