I want to receive notification when the messages arrives with using Broadcast Receiver. I wrote this code but it doesnt work;
I added this code in my AndroidManifest class;
<receiver android:name=".receiver.SMSReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
And my SMSReceiver class;
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 SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
Toast.makeText(context, "New SMS: " + messages.getMessageBody(),
Toast.LENGTH_LONG).show();
Log.d(getClass().getName().toString(), "SMS Arrived");
}
}
This code must show me a Toast Message when SMS arrived. How can i fix this problem?
Thank you.
You must have the permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
If you want to send sms you will need permission :
<uses-permission android:name="android.permission.SEND_SMS" />
I think you need to register your broadcast receiver. Hope for help.
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
Related
I have been working on an application that use to receive SMS and show a Toast using Broadcast Receiver and i have an activity with no purpose, when i removed that activity and build the apk and run on my phone, application is not responding when SMS is received (no Toast showing), although remaining code is same as it was previously. Can anyone help please i am so stuck and couldn't help myself reading hundreds of answers. I studied i should create a service but still no Toast is appearing. below is my code. I can not have any GUI in my application even don't want to have auto kill activity.
BroadcastReceiver.java
package com.test.testservice;
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 static final String SMS_BUNDLE = "pdus";
private static final String LOG = "SmsBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
if (sms != null)
{
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i)
{
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, smsMessageStr, Toast.LENGTH_LONG).show();
//MyService objService=new MyService();
//objService.startService(intent);
//objService.stopService(intent);
Intent myIntent = new Intent(context, MyService.class);
//myIntent.putExtra("Sender", Sender);
//myIntent.putExtra("Fullsms", Fullsms);
context.startService(myIntent);
}
}
}
}
MyService.java
package com.test.testservice;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String LOG = "MyService";
#Override
public boolean stopService(Intent name) {
if (super.stopService(name))
{
Toast.makeText(this,"HELLO stopService",Toast.LENGTH_LONG).show();
Log.i(LOG, "stopService");
return true;
}
else return false;
}
#Override
public ComponentName startService(Intent service) {
return super.startService(service);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"HELLO onCreate",Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this,"HELLO onStart",Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.testservice">
<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/AppTheme">
<receiver android:name=".SmsReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.REBOOT"/>
</intent-filter>
</receiver>
</application>
<service android:name="com.test.testservice.service.MyService"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
Unless you are creating your own phone, or your own custom ROM, you need the activity. Your BroadcastReceiver will not work when your app is first installed. It will only start to work once the user has launched your activity (or something else uses an explicit Intent to start one of your components).
I can not have any GUI in my application
Then your app will not work on Android 3.1+ devices, which make up the vast majority of the Android device ecosystem.
I am trying to build a simple app that can notify if there is a sms incoming. Just get the broadcaster to work, but what happens is that my app crashes when I get a SMS, and then next time it get a SMS nothing happens. I don't have any error message to go after or show either.
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studerande.upg62_b">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
my broadcaster class which extends BroadcastReceiver. Excuse my Toasts but I just wanted to see if it was running but it isn't..
package com.example.studerande.upg62_b;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
/**
* Created by Studerande on 2017-03-18.
*/
public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
final SmsMessage smsMessage = extractSmsMessage(intent);
processMessage(context, smsMessage);
}
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
private SmsMessage extractSmsMessage(final Intent intent) {
final Bundle pudsBundle = intent.getExtras();
final Object[] pdus = (Object[]) pudsBundle.get("pdus");
String format = pudsBundle.getString("format");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0], format);
return smsMessage;
}
else {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
return smsMessage;
}
}
private void processMessage(final Context context, final SmsMessage smsMessage) {
// Do something interesting here
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
}
MainActivity. You don't need to do anything here if I understood it correctly right?
package com.example.studerande.upg62_b;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I realized that the problem is because of the API version. The broadcaster works in phone that has API 22 or below, but not in the later versions because of the new permission-handling that was introduced. So I need to ask permission before I can read SMS. https://developer.android.com/training/permissions/requesting.html
I want my app to send a SMS when it receives a SMS, and I got it working. The problem is that once it gets 1 SMS it doesn't stop sending them.
Its like onReceive() method keeps getting called.
I would like it to send 1 SMS per 1 SMS received.
/******************************************************************************/
BroadcastReceiver class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
public class SMSListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("031130130", null, "sms text", null, null);
}
}
/*****************************************************************************/
/***************************************************************************/
MainActivity
broadcastReceiver = new SMSListener() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED") && intent.getExtras() != null){
try{
doStuffsIfStolenOnce();
}catch (Exception e){
Toast.makeText(Running.this,"Something went wrong:" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
};
IntentFilter myFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(broadcastReceiver, myFilter);
/****************************************************************************/
added intent filter and permission in manifest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<receiver android:name=".SMSListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
It feels like the problem is something obvious, but i can't find anybody else having this problem.
Solved my problem! Turns out it was my silly mistake, I was testing the app on my phone(real device) and i didn't have a second phone to send the "request" SMS. So I used my own phone to send the initial SMS and the app, working fine, send one back, but that meant it send a SMS to itself and once it received the second SMS it proceeded to send another one... and it got itself in a nice loop.
I know the AlarmManagerBroadcastReceiver will stay system to keep watch over SMS after I installed the .apk
Will the AlarmManagerBroadcastReceiver expend battery even if I never receive s SMS?
Do I need disable the AlarmManagerBroadcastReceiver when I stop watch SMS ?
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabledisablebroadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.code4reference.enabledisablebroadcastreceiver.EnableDisableBroadcastReceiver"
android:label="#string/title_activity_enable_disable_boradcast_receiver" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Broadcast receiver -->
<receiver android:name="com.code4reference.enabledisablebroadcastreceiver.AlarmManagerBroadcastReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<service android:name="com.code4reference.enabledisablebroadcastreceiver.MyInternetServer"></service>
</application>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
</manifest>
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;
public class AlarmManagerBroadcastReceiver 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("CWCGR1",
// "From: " + messages[i].getOriginatingAddress()+
// " Msg: " + messages[i].getMessageBody());
HandleMsg(context,messages[i].getOriginatingAddress(), messages[i].getMessageBody());
}
}
}
private void HandleMsg(Context context,String address, String body ){
Intent msgIntent = new Intent(context,MyInternetServer.class);
msgIntent.putExtra("address", address);
msgIntent.putExtra("body", body);
context.startService(msgIntent);
}
}
import com.example.enabledisablebroadcastreceiver.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class EnableDisableBroadcastReceiver extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnExit=(Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
public void enableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
public void disableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
}
As discussed here, an incoming SMS belongs to a special group of low-level system events that will cause the CPU to wake from the battery-saving "sleep mode" (this group includes incoming calls, incoming mobile data packets and AlarmManager events). The device's GSM radio will listen to incoming SMS regardless of your broadcast receiver being set or not. When an SMS arrives, the system will choose which receiver(s) will handle it. Thus, having a SMS broadcast receiver registered has no impact in the battery consumption. Besides, energy consumption due to a registered receiver in memory is not significant.
You can unregister the broadcast receiver programmatically if there is a functional requirement to do so.
Because you have fined your AlarmManagerBroadcastReceiver in the android manifest, android will wake up your app and call the AlarmManagerBroadcastReceiver every time an sms is received.
If no SMS are received, your app won't be woken up so there won't be any impact on battery.
If you want control over when to receive those broadcasts, register and unregister your receiver programmatically through the registerReceiver(BroadcastReceiver receiver, IntentFilter filter) method on a Context (e.g. Activity).
I just want to ask if anyone knows or have a working SMS receiver / handler code for android. Because I've been searching the net for days now and I still haven't seen an updated code, most seem to have deprecated codes on them like the one here http://mobiforge.com/developing/story/sms-messaging-android I would REALLY appreciate it if someone could teach me the new codes for receiving SMS in an application. thanks!
I've just recently implemented a working BroadcastReceiver to handle SMS messages. The key parts are the manifest and the BroadcastReceiver.
In the manifest you need the RECEIVE_SMS permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
You don't need READ_SMS. Your receiver entry should look something like this:
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
The bit that most people seem to forget is android:exported="true" which is required because the broadcast originates from outside your application. Some postings suggest you need android:permission="android.permission.RECEIVE_SMS" or android:permission="android.permission.BROADCAST_SMS" but this isn't the case.
My BroadcastReceiver implementation looks like this:
package smsmanager;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
final SmsMessage smsMessage = extractSmsMessage(intent);
processMessage(context, smsMessage);
}
}
private SmsMessage extractSmsMessage(final Intent intent) {
final Bundle pudsBundle = intent.getExtras();
final Object[] pdus = (Object[]) pudsBundle.get("pdus");
final SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
return smsMessage;
}
private void processMessage(final Context context, final SmsMessage smsMessage) {
// Do something interesting here
}
}
And everything works just as I want it to, and I can stop burning up my SMS allowance testing ths
This Should work, and is not deprecated, if you replace android.telephony.gsm.SmsMessage with android.telephony.SmsMessage. it's just about listening for android.provider.Telephony.SMS_RECEIVE.
There is a thread here which includes code to do what you're asking for. Note that there are some corrections in the answers there.