Here I am trying to read the message and toast it I have seen various examples where there is a separate class that extends BroadcastReceiver but they have not mentioned how to start this class(do we use startactivity() or somthing else). I have posted the code that I dowladed through a link from O'Reilly's cookbook. I've tried to sms from ddms but it doesn't show toast of message. Any help is appreciated as this is my first time with BroadcastReceiver.
invitationSMSreciever.java
package com.SMS;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.sax.StartElementListener;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class invitationSMSreciever extends BroadcastReceiver {
final String TAG = "BombDefusalApp";
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String message = "";
if (bundle != null) {
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]);
message = msgs[i].getMessageBody();
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
if (msgs[i].getMessageBody().equalsIgnoreCase("Invite")) {
// Intent myIntent = new Intent(MainMenu.this,
// com.bombdefusal.ReceivedSMSActivity.class);
Intent myIntent = new Intent();
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.setAction("com.example.helloandroid.INVITE");
context.startActivity(myIntent);
}
}
}
}
}
MainMenu
package com.SMS;
import com.SMS.R;
import android.app.Activity;
import android.os.Bundle;
public class MainMenu extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
ReceivedSMSActivity
package com.SMS;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import com.SMS.R;
public class ReceivedSMSActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent ("com.android.PLAY"));
setContentView(R.layout.invite);
}
public boolean onKeyDown(int keyCode, KeyEvent service) {
stopService(new Intent("com.bombdefusal.START_AUDIO_SERVICE"));
finish();
return true;
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.SMS" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainMenu" android:label="#string/app_name">
<intent-filter>
<action android:name="com.SMS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.SMS.ReceivedSMSActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.example.helloandroid.INVITE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<receiver android:name="com.SMS.invitationSMSreciever"
android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</application>
</manifest>
You have two options to do this:
Register you broadcast receiver statically in the AndroidManifest file. Thus, it will be called automatically.
Register you broadcast receiver dynamically in your code using registerReceiver() method. In this case, this method should be paired with unregisterReceiver() where you unregister your receiver.
Usually, if broadcast receiver is implemented as a separate class then it usually registered statically in AndroidManifest file. I guess in you case you should just add the following lines to your file:
<receiver android:name=".invitationSMSreciever" android:exported="true" >
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Related
I am building 2 NFC enabled apps, one is supposed to send a message and the other to receive it.
Sending app Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.joyride.nfc_merchant">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NFC_Merchant">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Sending app Main Activity
package com.joyride.nfc_merchant;
import androidx.appcompat.app.AppCompatActivity;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
String message;
NdefRecord ndefRecord;
NdefMessage ndefMessage;
NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
}
public void sendMessage(View view) {
message = ((EditText) findViewById(R.id.text_message)).getText().toString();
ndefRecord = NdefRecord.createTextRecord(null, message);
ndefMessage = new NdefMessage(ndefRecord);
nfcAdapter.setNdefPushMessage(ndefMessage, this);
}
}
Receiving app android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.joyride.nfc_customer">
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NFC_Customer">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Receiving app Main Activity
package com.joyride.nfc_customer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
TextView messageView = (TextView)findViewById(R.id.messageView);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messageView.setText(((NdefMessage) rawMessages[i]).toString());
}
}
}
}
}
I've installed each app on another phone. Off course the receiving app is not registering the message. Am I missing something here? How do I go about debugging this?
This is an app which toasts a received message and gives it a reply
when i tested with the emulator it is working fine but not on device
-----this is the MainActivity.java---------
package com.example.yj.example;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
-------This is SmsReceiver.java-----------
package com.example.yj.example;
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.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
if(bundle != null){
Object[] pdus= (Object[]) bundle.get("pdus");
String senderNumber=null;
for(int i=0; i<pdus.length; i++){
SmsMessage sms=SmsMessage.createFromPdu((byte[]) pdus[i]);
senderNumber = sms.getDisplayOriginatingAddress();
String message= sms.getDisplayMessageBody();
Toast.makeText(context, "From:" + senderNumber + " Message:" + message, Toast.LENGTH_LONG).show();
}
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(senderNumber,null,"u r lucky!!!!! its finally working",null,null);
}
}
}
---------this is AndroidManifest.xml -----------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yj.example" >
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/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>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
</manifest>
I am stuck for more than 6 hours, I have gone through every possible helpful post but no luck
The onReceive() method of BroadcastReceiver is not getting fired.
Below is the code of my MainAcitivty, Manifest and BroadCastReceiver.
This is code of my mainactivity
package com.example.luckydraw;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This is My broadcast reciever
package com.example.luckydraw;
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 Smsrcv extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "Smsrcv";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "I re", Toast.LENGTH_LONG).show();
Log.i(TAG, "Intent recieved: " + intent.getAction());
String message="test message";
String PhoneNumber="03214304743";
SmsManager.getDefault().sendTextMessage(PhoneNumber, null, message, null, null);
if (intent.getAction() == 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) {
Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
}
}
}
}
}
And finally this is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.luckydraw"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".Smsrcv"
android:enabled="true"
android:exported="true"
>
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
There are certain messaging applications e.g. GO SMS PRO etc which have broadcast recievers' intent fiters like
<intent-filter android:priority="2147483647" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
Here android:priority is 2147483647
This wasnt letting my app to catch System's broadcast !!
If you want to check all messaging applications' priorities on your device
use this
Intent intent = new Intent("android.provider.Telephony.SMS_RECEIVED");
List<ResolveInfo> infos = getPackageManager().queryBroadcastReceivers(intent, 0);
for (ResolveInfo info : infos) {
System.out.println("Receiver name:" + info.activityInfo.name + "; priority=" + info.priority);
}
SOLUTION
You should uninstall those with priority > 1000, to make your app work..
I have this program that will try to monitor incoming SMS messages. But when I tried to run my program in the emulator and I tried to send a SMS message, it works. But when I installed my program in my phone, its not working.
What is the problem?
And I want to run the program at the backend as well. How to do that?
BTW, below are the whole codes for this sample app.
Thanks
RJ
import java.io.BufferedWriter;
import java.io.FileWriter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class MySMSMonitor extends BroadcastReceiver
{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent)
{
if(intent!=null &&
intent.getAction()!=null &&
ACTION.compareToIgnoreCase(intent.getAction())==0)
{
Object[]pduArray= (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i<pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu ((byte[])pduArray [i]);
}
Log.d("MySMSMonitor","SMS Message Received.");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="spy.Frandy.com"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="6" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".TelephonyDemo"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MySMSMonitor"> <intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter>
</receiver>
</application>
</manifest>
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TelephonyDemo extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button sendBtn = (Button)findViewById(R.id.sendSmsBtn);
sendBtn.setOnClickListener(new OnClickListener(){
#Override public void onClick(View view) {
EditText addrTxt = (EditText)TelephonyDemo.this.findViewById(R.id.addrEditText);
EditText msgTxt = (EditText)TelephonyDemo.this.findViewById(R.id.msgEditText);
try {
sendSmsMessage(
addrTxt.getText().toString(),msgTxt.getText().toString());
Toast.makeText(TelephonyDemo.this, "SMS Sent",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(TelephonyDemo.this, "Failed to send SMS", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void sendSmsMessage(String address,String message)throws Exception {
SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendTextMessage(address, null, message, null, null);
}
}
I would simply insist you to use ContentObserver and register content://sms Uri and fetch the type of the SMS using
cusor.getString(cusor.getColumnIndex("type")); // 1 = SMS Received
// 2 = SMS Sent
Further you can easily get the required data from the cursor that you fetched. Here is a blog for the same.
I'm going to assume with the little detail you have provided that the reason it works on a emulator and not your actual phone; may be another conflicting app intercepting the messages before they are broadcasted to your app.
try adding android:priority="1000" to your intent-filter of your receiver in your apps manifest
(a thousand being whatever number you feel necessary, could be higher if needed)
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
more info on - intent-filter priority
Try This:
<receiver android:name=".MySMSMonitor"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="2">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
I am new to android, i am trying a broadcast demo, I gave my best effort by reading the documentation but its not working. Please have a look at my code:
BroadcastDemoActivity.java
package com.broadcastdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class BroadcastDemoActivity extends Activity {
/** Called when the activity is first created. */
public static final String PUBLIC_HOLIDAYS = "com.paad.action.PUBLIC_HOLIDAYS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(getIntent());
}
}
Receive.java
package com.broadcastdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class Receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String message = intent.getStringExtra("Holiday");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcastdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".BroadcastDemoActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Receive">
<intent-filter>
<action android:name="com.paad.action.PUBLIC_HOLIDAYS"/>
</intent-filter>
</receiver>
</application>
</manifest>
I know that i am missing something which i am not aware of, please help.
I believe your problem is in the call to sendBroadcast.
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(getIntent());
You are not sending the intent that you construct, you're sending the intent returned from getIntent(), which will be the intent that the activity was started with.
It should be
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(intent);