0

I am an Android beginner, and I wrote the following code, the code can show the toast in phone with API 10, but I cannot show the toast and run the onReceive in phone with API 19.

I had searched the internet and found out that I should add flag on the intent with flag_include_stopped_packages. I guess that is the answer for my problem.

But how do I add it for system broadcast? Appreciated if anyone can show the suitable code.I cannot find any suitable code from internet showing this. Thank you!

SMS.java

public class SMS extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

IncomingSms.java

public class IncomingSms extends BroadcastReceiver {
    final SmsManager sms = SmsManager.getDefault();

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 message = currentMessage.getDisplayMessageBody();
                String senderNum = currentMessage.getDisplayOriginatingAddress();
                Log.i("SmsReceiver", senderNum + message);
                Toast.makeText(context,
                        "send from " + senderNum + message, Toast.LENGTH_LONG).show();

            }
        }
    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);
    }
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.security.security" >

<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=".SMS"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.INFO"/>
        </intent-filter>
    </activity>

    <receiver android:name=".IncomingSms">
        <intent-filter android:priority="999">
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
    </receiver>

</application>

Shahzeb
  • 3,696
  • 4
  • 28
  • 47
Hon
  • 1
  • 2

1 Answers1

0

First create your own Receiver class by extending from Android default BroadcastReceiver class. Then @Override the onReceive() method in your class. This onReceive() method will be called when a new SMS will come to the phone. Below is my Receiver Class for getting incoming SMS notification.

//Here is your broadcast receiver class
public class YourBroadcastReceiver extends BroadcastReceiver{
    private static final String TAG = "MyBroadCastReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
    Log.i(TAG,"OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            Bundle bndl = intent.getExtras();
            SmsMessage[] msg = null;
            String str = "";         
            if (null != bndl)
            {
                //---retrieve the SMS message received---
                Object[] pdus = (Object[]) bndl.get("pdus");
                msg = new SmsMessage[pdus.length];         
                for (int i=0; i<msg.length; i++){
                    msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);             
                    str += "SMS From " + msg[i].getOriginatingAddress();                   
                    str += " :\r\n";
                    str += msg[i].getMessageBody().toString();
                    str += "\n";
                }
                //---display incoming SMS as a Android Toast---
                Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
            } 
        }
}

There are two different ways to register the broadcastreceiver in Android.

  1. Register the broadcastreceiver in your project’s Manifest file. If you will use this method then you can’t control the lifecycle of broadcast receiver. That means your application will getting notification unless until you uninstall the application.

  2. Register the broadcastreceiver using Android’s Context.registerReceiver() method. By using this method, we can control it’s lifecycle by registering and un-registering broadcast receiver as per your requirement. To Register the broadcastreceiver using Android’s Context visit this Answer

So let’s register your own Receiver class with the incoming SMS intent filter in Manifest file. For incoming SMS example, my manifest file looks like below.

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

<receiver
        android:name ="FULL_PACKAGE_NAME.YourBroadcastReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
   </receiver>

That’s it. Once you install the application, at that time the broadcastreceiver will be automatically register with Android OS, and you will get notification as an Android Toast with details.

Get more info visit here

Community
  • 1
  • 1
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87