SMS receiver didn't work - java

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);

Related

Java Android Media Player (Notification)

So I have the following code and it is working fine, however I want to show the media controls in the users Notification area so they can play and stop the music as they please while the app is in the background.
I am wondering how one does this?
Code:
package com.radiomedia.a1liferadio;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ImageView imagePlayPause;
private TextView textCurrentTime, textTotalDuration;
private SeekBar playerSeekBar;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePlayPause = findViewById(R.id.imagePlayPause);
textCurrentTime = findViewById(R.id.textCurrentTime);
textTotalDuration = findViewById(R.id.textTotalDuration);
playerSeekBar = findViewById(R.id.playerSeekBar);
mediaPlayer = new MediaPlayer();
playerSeekBar.setMax(100);
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaPlayer.isPlaying())
{
handler.removeCallbacks(updater);
mediaPlayer.pause();
imagePlayPause.setImageResource(R.drawable.ic_play);
}else{
mediaPlayer.start();
imagePlayPause.setImageResource(R.drawable.ic_pause);
updateSeekBar();
}
}
});
prepareMediaPlayer();
}
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource("http://stream.radiomedia.com.au:8003/stream"); //url of media
mediaPlayer.prepare();
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
} catch (Exception exception){
Toast.makeText(this,exception.getMessage(), Toast.LENGTH_SHORT).show();
}
};
private Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
long currentDuration = mediaPlayer.getCurrentPosition();
textCurrentTime.setText(milliSecondsToTimer(currentDuration));
}
};
private void updateSeekBar(){
if(mediaPlayer.isPlaying()) {
playerSeekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
handler.postDelayed(updater, 1000);
}
};
private String milliSecondsToTimer(long milliSeconds) {
String timerString = "";
String secondsString;
int hours = (int)(milliSeconds / (1000 * 60 * 60));
int minutes = (int)(milliSeconds % (1000 * 60 * 60)) / (1000 *60);
int seconds = (int)((milliSeconds % (1000 * 60 *60)) % (1000 * 60) / 1000);
if(hours > 0)
{
timerString = hours + ":";
}
if(seconds < 10)
{
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
}
You should follow this old google mediaplayer sample (Use this commit if the master version crashes for you) if you want to keep using the MediaPlayer.
But If you don't mind using ExoPlayer, then you should instead follow this new one, since ExoPlayer can already take care of part of the notification stuff.
But so in these sample projects you can see that:
It's not as simple as just a notification, it also ties into people pressing on a play button on their headset etc.
You really need a service for this, to bind to the notification, to handle the action.MEDIA_BUTTON intents.
Minimal code for adding such a notification with a MediaSession and Service with the MediaPlayer (so not ExoPlayer) like you are using would look something like this:
Add the media compat libraries to your apps' build gradle:
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation "androidx.media:media:1.1.0"
}
Then create a class for creating the Notification:
package com.radiomedia.a1liferadio;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.media.app.NotificationCompat.MediaStyle;
import androidx.media.session.MediaButtonReceiver;
/**
* Keeps track of a notification and updates it automatically for a given MediaSession. This is
* required so that the music service don't get killed during playback.
*/
public class MediaNotificationManager {
public static final int NOTIFICATION_ID = 412;
private static final String TAG = MediaNotificationManager.class.getSimpleName();
private static final String CHANNEL_ID = "com.example.android.musicplayer.channel";
private static final int REQUEST_CODE = 501;
private final MediaSessionService mService;
private final NotificationCompat.Action mPlayAction;
private final NotificationCompat.Action mPauseAction;
private final NotificationManager mNotificationManager;
public MediaNotificationManager(MediaSessionService musicContext) {
mService = musicContext;
mNotificationManager =
(NotificationManager) mService.getSystemService(Service.NOTIFICATION_SERVICE);
mPlayAction =
new NotificationCompat.Action(
R.drawable.ic_play,
"play",
MediaButtonReceiver.buildMediaButtonPendingIntent(
mService,
PlaybackStateCompat.ACTION_PLAY));
mPauseAction =
new NotificationCompat.Action(
R.drawable.ic_pause,
"pause",
MediaButtonReceiver.buildMediaButtonPendingIntent(
mService,
PlaybackStateCompat.ACTION_PAUSE));
// Cancel all notifications to handle the case where the Service was killed and
// restarted by the system.
mNotificationManager.cancelAll();
}
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
}
public NotificationManager getNotificationManager() {
return mNotificationManager;
}
public Notification getNotification(MediaMetadataCompat metadata,
#NonNull PlaybackStateCompat state,
MediaSessionCompat.Token token) {
boolean isPlaying = state.getState() == PlaybackStateCompat.STATE_PLAYING;
MediaDescriptionCompat description = metadata.getDescription();
NotificationCompat.Builder builder =
buildNotification(state, token, isPlaying, description);
return builder.build();
}
private NotificationCompat.Builder buildNotification(#NonNull PlaybackStateCompat state,
MediaSessionCompat.Token token,
boolean isPlaying,
MediaDescriptionCompat description) {
// Create the (mandatory) notification channel when running on Android Oreo.
if (isAndroidOOrHigher()) {
createChannel();
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, CHANNEL_ID);
builder.setStyle(
new MediaStyle()
.setMediaSession(token)
.setShowActionsInCompactView(0)
// For backwards compatibility with Android L and earlier.
.setShowCancelButton(true)
.setCancelButtonIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(
mService,
PlaybackStateCompat.ACTION_STOP)))
.setColor(ContextCompat.getColor(mService, R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_play)
// Pending intent that is fired when user clicks on notification.
.setContentIntent(createContentIntent())
// Title - Usually Song name.
.setContentTitle(description.getTitle())
// When notification is deleted (when playback is paused and notification can be
// deleted) fire MediaButtonPendingIntent with ACTION_PAUSE.
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(
mService, PlaybackStateCompat.ACTION_PAUSE));
builder.addAction(isPlaying ? mPauseAction : mPlayAction);
return builder;
}
// Does nothing on versions of Android earlier than O.
#RequiresApi(Build.VERSION_CODES.O)
private void createChannel() {
if (mNotificationManager.getNotificationChannel(CHANNEL_ID) == null) {
// The user-visible name of the channel.
CharSequence name = "MediaSession";
// The user-visible description of the channel.
String description = "MediaSession and MediaPlayer";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(
new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
Log.d(TAG, "createChannel: New channel created");
} else {
Log.d(TAG, "createChannel: Existing channel reused");
}
}
private boolean isAndroidOOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
private PendingIntent createContentIntent() {
Intent openUI = new Intent(mService, MainActivity.class);
openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
return PendingIntent.getActivity(
mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);
}
}
Then Create a Service class that handles playback and the notification button presses:
package com.radiomedia.a1liferadio;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.view.KeyEvent;
import androidx.annotation.Nullable;
public class MediaSessionService extends Service {
public MediaPlayer mediaPlayer;
public static final String TAG = "MediaSessionService";
public static final int NOTIFICATION_ID = 888;
private MediaNotificationManager mMediaNotificationManager;
private MediaSessionCompat mediaSession;
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
mMediaNotificationManager = new MediaNotificationManager(this);
mediaSession = new MediaSessionCompat(this, "SOME_TAG");
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
mediaPlayer.start();
}
#Override
public void onPause() {
mediaPlayer.pause();
}
});
Notification notification =
mMediaNotificationManager.getNotification(
getMetadata(), getState(), mediaSession.getSessionToken());
startForeground(NOTIFICATION_ID, notification);
}
public MediaMetadataCompat getMetadata() {
MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder();
builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "artist");
builder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "title");
builder.putLong(
MediaMetadataCompat.METADATA_KEY_DURATION, mediaPlayer.getDuration()
);
return builder.build();
}
private PlaybackStateCompat getState() {
long actions = mediaPlayer.isPlaying() ? PlaybackStateCompat.ACTION_PAUSE : PlaybackStateCompat.ACTION_PLAY;
int state = mediaPlayer.isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
final PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder();
stateBuilder.setActions(actions);
stateBuilder.setState(state,
mediaPlayer.getCurrentPosition(),
1.0f,
SystemClock.elapsedRealtime());
return stateBuilder.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ("android.intent.action.MEDIA_BUTTON".equals(intent.getAction())) {
KeyEvent keyEvent = (KeyEvent) intent.getExtras().get("android.intent.extra.KEY_EVENT");
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Update your manifest for declaring the service and sending the action.MEDIA_BUTTON intent to it.
<service
android:name=".MediaSessionService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</service>
<receiver android:name="androidx.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
This MediaButtonReceiver above is needed for pre-OREO devices, it will forward the event to the service on those platforms.
Then start the service from your main activity.
ContextCompat.startForegroundService(
MainActivity.this.getApplicationContext(),
new Intent(MainActivity.this.getApplicationContext(), MediaSessionService.class));
Things still to do here are making your main activity send actions to your service or the player in the service somehow, updating the notification and service state on a change, but you should be able to get something working with this code and figure out the rest from the google sample code.
There are two scenarios :
First
if you want to play song in background you should have to start a forground service. forground service is with notification .(pass the seekbar position, play pause state, playlist or video url to service).
After you creating custome notification with media controls whatever you want
you have to add a media player to service also pass your parameters like position , play pause state to service player that it play from your previous state of activity player.
on click of notification you have to do same parameters pass to activity .
Second
Start forground service with attaching a player and bind the activity to it, and handle all controls from notification and activity at the same time.
you can pass player controls to notfication in sense of froground service to start and play song in background .
you can use preference or tinydb for best performance in getting parameters to pass in first case.

Broadcasting SMS from android on boot complete

I am trying to get SMS broadcasted to few mobile numbers every time the sim card is changed. Unfortunately, it doesn't work when I try it on my device. Can someone identify the issue in my following code please. The onBoot permissions are all added.
public class SendSmsOnTheft extends BroadcastReceiver
{
static void sendSMS(String destinationAddress, String text, Context context)
{
Intent intent = new Intent(context, SendSmsOnTheft.class);
PendingIntent pendingintent = PendingIntent.getActivity(context, 0, intent, 0);
SmsManager.getDefault().sendTextMessage(destinationAddress, null, text, pendingintent, null);
}
public void onReceive(Context context, Intent intent)
{
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
Log.d("VogueTools", "Got the Boot Event>>>");
TelephonyManager telephonymanager = (TelephonyManager)context.getSystemService("phone");
SharedPreferences sharedpreferences = context.getSharedPreferences("file", 0);
String number1 = sharedpreferences.getString("no1", "");
String number2 = sharedpreferences.getString("no2", "");
String number3 = sharedpreferences.getString("no3", "");
String number4 = sharedpreferences.getString("no4", "");
String extra = ("Mobile of IMEI NO: ")+
telephonymanager.getDeviceId()+
" is currently used" +
" by the SIM card service provider:" +
telephonymanager.getSimOperatorName().toString();
String simno = sharedpreferences.getString("simno", "");
String serialno = ((TelephonyManager)context.getSystemService("phone")).getSimSerialNumber();
if (number1.length() == 0)
{
System.exit(0);
}
if (simno.equals(serialno))
{
sendSMS(number1, extra, context);
sendSMS(number2, extra, context);
sendSMS(number3, extra, context);
sendSMS(number4, extra, context);
}
}
System.exit(0);
}
}
Here is the code that I used in my app for the same purpose:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class ListeningToBoot extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String urphone = tm.getLine1Number();
Log.v("Uphone","is "+urphone);
Toast.makeText(context, "MDN:"+urphone, Toast.LENGTH_SHORT).show();
SharedPreferences prefs = context.getSharedPreferences("MySimPreferences", Context.MODE_PRIVATE);
String mobile_No=prefs.getString("MDN", "un-known");
Log.v("from shared pref","MDN"+mobile_No);
String imei=prefs.getString("IMEI", "un-known");
Log.v("from shared pref","IMEI"+imei);
if(urphone.equals(mobile_No))
{
Log.v("MDN is same","shoudl do nothing");
Toast.makeText(context, "MDN no change", Toast.LENGTH_LONG).show();
}
else
{
Log.v("MDN is not same","send a message to someone");
SharedPreferences prefs_names = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
String number_to_send=prefs_names.getString("Moblie_Number", "un-known");
Toast.makeText(context, "MDN changed", Toast.LENGTH_LONG).show();
String message_to_send="Your mobile number chagned:\nNew Number: "+urphone+"\nIMEI: "+imei;
SmsManager.getDefault().sendTextMessage(number_to_send, null, message_to_send, null,null);
}
}
}
}
Hope this helps.
Edit: Make sure you have given all the required permissions in manifest file.
I think we need a little more information in order to help you. Anyway, have you registered the receiver properly? You must have been something like this under application:
<receiver
android:name=".SendSmsOnTheft"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
With permissions:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SEND_SMS" />

Read and display incoming message text android

I am new to android development.I am developing small android application. In my application I want to retrieve newly coming sms and display this message to user. My code looks like
// HellowordActivity.java
package com.example.helloword;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class HellowordActivity extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
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: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody().toString();
strMessage += "\n";
}
// Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
Intent _intent = new Intent(context, PopupActivity.class);
_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
_intent.putExtra("strMessage", strMessage);
startActivity(_intent);
}
}
}
I added receiver and permission in Android Manifest.xml
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<receiver android:name=".HellowordActivity" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<activity android:name=".PopupActivity" android:launchMode="singleTop" />
I am not doing any thing in layout part.What I want as an output when new message will come;
message text display to user with simple popup.
Need Help.. Thank you...
Try this it works for me you will get a toast shown to you with the content of the message received:
package com.example.a;
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 SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
}
}
}
}
}
The AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.HARDWARE_TEST"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name=".SMSBroadcastReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Use DDMS to send sms to your emulator via Telnet
if you want to show an popup when SMS is Recived then you will need to Create an Activity with android:launchMode="singleTop" as:
In manifast declare Activity as:
<activity android:name=".PopupActivity" android:launchMode="singleTop" />
From HellowordActivity BroadcastReceiver start Activity as:
Intent intent = new Intent(context, PopupActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent .putExtra("strMessage", strMessage);
context.startActivity(intent);
And in your PopupActivity.class:
public class PopupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
Intent intent= getIntent();//get message here
String strMessage = intent.getStringExtra("strMessage");
//NOW YOU CAN SHOW THIS MESSAGE IN POPUP
}
#Override
protected void onStop() {
super.onStop();
this.finish();
// The activity is no longer visible (it is now "stopped")
}
You can also checkout these Smspopup apps source code:
android-smspopup
sms-enhancer

Receive SMS via My application in android

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.

Retrieving the SMS Messages from the SIM card on with android

I was wondering if anyone knew anything about programmatically getting the sms messages off of your phone's sim card on an android platform. I would like to write a program that allows you to save either individual messages or entire threads to the sd card, but after looking around for a bit, I have discovered that google decided to take out that api from the current android sdk. I saw in a few places that there are hidden apis for this, but no one knew what they were or how to use them.
Here is a code snippet that lets you read messages.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.telephony.gsm.SmsManager;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String from= "";
String body="";
boolean inSIM=false;
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]);
from = ""+messages[i].getOriginatingAddress();
body = ""+messages[i].getMessageBody();
inSIM = (messages[i].getIndexOnSim() != -1);
if (inSIM)
{
int status = messages[i].getStatusOnSim();
if (status == SmsManager.STATUS_ON_SIM_UNREAD)
{
Toast.makeText(context, "Message Unread on SIM: "+from+": "+body, Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
Another simple approach is
class SmsReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent)
}
}

Categories