Receive SMS via My application in android - java

I am developing an android application that would let people send and receive SMS to a unique number via my application. I can send SMS but it is appearing in INBOX message box!
I want it to appear in my application
I googled and find this but I do not want it to appear in Toast message, I want it like in What's app in android and how to save all the SMS from this number?
this is the code:
package net.learn2develop.SMSMessaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver
{
#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---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}

As per: Can we delete an SMS in Android before it reaches the inbox?
Incoming SMS message broadcasts
(android.provider.Telephony.SMS_RECEIVED) are delivered as an
"ordered broadcast" — meaning that you can tell the system which
components should receive the broadcast first.
If you define an android:priority attribute on your SMS-listening
, you will then receive the notification before the
native SMS application.
At this point, you can cancel the broadcast, preventing it from
being propagated to other apps.

In your manifest, you should have something that looks like this:
<receiver android:name=".SmsReceiver">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Note android:priority="999".
In your onReceive() method, the first line should be abortBroadcast();. Timing does matter and you will get bundle from the intent.

Related

Broadcast Receiver Not receive messages from Mobile default messags application Why?

In BroadcastReceiver i want to receive sms from default Mobile application.
But when user send sms without internet connect then i receive, but when user (send sms via wifi or Mobile Network) i unable to read message.
public class MessageReciver extends BroadcastReceiver {
private static MessageListener mListener;
public static final String reciveSMS="android.provider.Telephony.SMS_RECEIVED";
public static final String TAG ="SmsBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("fsdfdsfdsfdgfdsg "," rerwerw");
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
String formate = data.getString("format");
for (int i = 0; i < pdus.length; i++) {
SmsMessage smsMessage = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
{
smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i], formate);
} else {
smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String message = smsMessage.getMessageBody();
Toast.makeText(context, "Message Received: " + message, Toast.LENGTH_SHORT).show();
}
}
}
}
I have't understand why i face this problem , because Broadcast receiver can send or receive broadcast messages from the Android system and other Android apps. It only receive (sms without using internet), But every mobile messages application have default enable option(Use wifi or data for messaging when available).
Anyone please help receive sms from default Mobile Messages Application
already register your receiver yet?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(messageReciver , new IntentFilter(YOUR FILTER));
}
try this
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application>
// add this
<receiver android:name=".MessageReciver">
<intent-filter android:priority="1">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ( ContextCompat.checkSelfPermission(
this,
Manifest.permission.RECEIVE_SMS
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.RECEIVE_SMS}, 1);
}
}
It's true, since some month before I have the same problem. If wifi is off and LTE is off, then MMS and SMS actions are broadcasted with sms_received or wap_push_received are recognized by broadcast receiver intent.
In new Smartphones these messages are marked by green color.
But if the sender phone turn on wifi or turn on LTE data mode, then shit happens.
These sms or mms over wifi or over LTE are now CHAT messages. These chat messages are not broadcasted by sms_received or wap_push_received. These CHAT messages are blue marked on modern phones. If you try to send messages (sms or mms) to an smartphone with wifi off or LTE off, you will be informed that now your messages will be send only as normal SMS or MMS.
You can find these CHAT messages over contentresolver content://im/chat
Unfortunately I doesn't know yet, how to receive broadcasted chat messages. For now I pull every 1 second the contentresolver for new chat messages.

Intercept android SMS going to default inbox - BroadcastReceiver

I'm developing a SMS based chat application using some Telco APIS.
I am receiving SMS only from a particular number and I want to know how I can prevent SMS being sent to the the default inbox of android.
Following is the code of my SMS receiver.
Compile SDK: 27
public void onReceive(Context context, Intent intent) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
this.intent = new Intent(BROADCAST_ACTION);
this.context = context;
chatlogDBAdapter = new ChatlogDBAdapter(context);
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;
if(senderNum.equals("77100")){
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
String timestamp = String.valueOf(System.currentTimeMillis());
String[] messagearray = message.split(",", -1);
String username = messagearray[0];
String messagebody = messagearray[1];
chatlogDBAdapter.addMessage(username,username,"username",messagebody,timestamp);
msgusername = username;
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 10);
}
}
abortBroadcast();
return;
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
And the manifest
<receiver
android:name=".IncomingSms"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.provider.Telephony.SMS_DELIVER" />
<action android:name="android.provider.Telephony.SMS_DELIVER_ACTION" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
As of KitKat only one app can consume received sms directly with SMS_DELIVER_ACTION: changelog blog here.
Any filters for the SMS_RECEIVED_ACTION broadcast in existing apps will continue to work the same on Android 4.4, but only as an observer of new messages, because unless your app also receives the SMS_DELIVER_ACTION broadcast, you cannot write to the SMS Provider on Android 4.4.
how I can prevent SMS being sent to the the default inbox of android.
Its not possible unless you make your app default SMS app. Starting from Andriod Kitkat only SMS default app has capability to Write data to the provider.
You can send/receive Binary SMS which won't be visible in the Inbox/Sent box

SMS receiver didn't work

i am new with android SMS and I am trying to study it. So i am trying to make an android app that always works on the background, and when I receive sms with the content of "hello"(somebody sending "hello" to my phone by SMS) a music will play.
I searched all over the internet, and I built a project that worked on the AVD, but when I tested it on my phone it didn't work:
import info.kfsoft.android.R.raw;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.TextView;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
MediaPlayer ourSong;
//static final int uniqueID=12345;
TextView display;
public void onReceive(Context context, Intent intent)
{
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
ourSong = MediaPlayer.create(context, R.raw.music2);
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// strMessage += "SMS From the king him self: " + messages[i].getOriginatingAddress();
// strMessage += " : ";
strMessage += messages[i].getMessageBody();
// strMessage += "\n";
}
//max volume
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_MUSIC,am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),0);
Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
// Notification n=new Notification(android.R.drawable.)
// nm.notify(uniqueID,n);
ourSong.start();
}
}
public void a(){
}
}
THX.
Maybe it's your intent priority too low and system-installed SMSApp receives a message before your application. Try adding priority="999"
<receiver android:name="OnAlarmReceiver">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Another trick is not register SMS_RECEIVED in a AndroidManifest.xml file but programmatically in an application code. Here is an example where I actually register multiple events to a same broadcastreceiver.
broadcastReceiver = new EventReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY-1);
registerReceiver(broadcastReceiver, filter);

android sms receive and reply without user interface

i want to build a android application that first received a message from any number and after
receive message i want hold the message string and number in the variables and then reply message adding some extra string in message to same no automatically without user interface.
i am new in android so please help me.
only i have receiving message code....plese give me solution for rest of code.
thank you
My brodcost reciver class
package com.example.broadcastreceiver;
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;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the 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();
System.out.println(phoneNumber);
System.out.println(currentMessage);
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
my main activity
package com.example.broadcastreceiver;
import com.androidexample.broadcastreceiver.R;
import android.os.Bundle;
import android.app.Activity;
public class BroadcastNewSms extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.androidexample_broadcast_newsms);
Ssystem.out.println("")
}
}
Well, you now should send your message from your broadcast, you should:
PendingIntent sentIntent; // can be null
PendingIntent deliveryIntent; // can be null
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentIntent, deliveryIntent);
http://developer.android.com/reference/android/telephony/SmsManager.html
you might consider putting it into IntentService, I am not sure how long execution of sendTextMessage takes, and broadcasts should not do any heavy computations/processing. Also putting this code into IntentService, will prevent android from killing your app, this is important because you want this to work in background and android might create your app just to make it receive broadcast, and after onReceive ends it might kill your app, Service will prolong your app life.

Receiving SMS messages in my app

I am creating an app that receives SMS text messages, I have created a class that extends BroadcastReceiver to receive and display SMS messagesin a toast within the app. I have also added permissions too my manifest along with the declaration of the receiver. The problem is it still does not seem to display the message. It will only appear on the top bar as a notification. Hopefully someone will be able to see where i am going wrong. Do i have to have some code in my mainactivity in order to display the message?? or should it display in my all my activities straight from the receiver clas?? code below:
UPDATE
I ended up deleting my receiver and recreating everything, now it seems to work fine
SmsReceiver.java:
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras ==null)
return;
//toast
Toast.makeText(context, "Received", Toast.LENGTH_LONG).show();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender+":"+body);
context.sendBroadcast(in);
this.abortBroadcast();
}
}
}
The problem is it still does not seem to display the message. It will only appear on the top bar as a notification
do you know what is - Ordered Broadcast?
in case you don't know - it's a broadcast that receives synchronously (one after another) by all receivers that registered for this broadcast. you can set in the manifest receiver deceleration a priority , and each one of the receivers can control if the broadcast will pass on in the priorities chain to additional registered receivers by using the aboartBroadcast() method.
what's to this and receiving SMS? - the system sends ordered broadcast when SMS receives. if your receivers priority is lower then the "default SMS app" priority - then what usually happens is that the application that got the broadcast first will cancel the broadcast, and you'll never receives it.
to get the broadcast before the default SMS application you have to declare your receiver with high priority (providing priority = 1000 should do the trick).
without providing priority - it's automatically set to zero.
you can have a look on this example - How Can i INTERCEPT an Incoming SMS With A specific Text
also make sure you declared the permission to RECEIVE_SMS in the manifest
Try starting again and setting up your receiver like so....
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras ==null)
return;
//toast
Toast.makeText(context, "Received", Toast.LENGTH_LONG).show();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender+":"+body);
context.sendBroadcast(in);
this.abortBroadcast();
}
}
}
#Override
public void onReceive(Context context, Intent arg1) {
SmsMessage msgs[] = getMessagesFromIntent(arg1);
for (int i = 0; i < msgs.length; i++) {
SmsMessage mesg = msgs[i];
Toast toast = Toast.makeText(context, mesg.getDisplayMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
}
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
// retrieve the SMS message received ::
Object[] pdus = (Object[]) extras.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";
// Toast to display SMS ::
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
// Send SMS ::
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("put your phoneNumber(emulatorPort)", null, str, null, null);
}
}
}
--
Have nice time !
Don't forget to add permissions !

Categories