EzDevInfo.com

broadcastreceiver interview questions

Top broadcastreceiver frequently asked interview questions

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I have figured out how to send and receive SMS messages. To send SMS messages I had to call the sendTextMessage() and sendMultipartTextMessage() methods of the SmsManager class. To receive SMS messages, I had to register a receiver in the AndroidMainfest.xml file. Then I had to override the onReceive() method of the BroadcastReceiver. I have included examples below.

MainActivity.java

public class MainActivity extends Activity {
    private static String SENT = "SMS_SENT";
    private static String DELIVERED = "SMS_DELIVERED";
    private static int MAX_SMS_MESSAGE_LENGTH = 160;

    // ---sends an SMS message to another device---
    public static void sendSMS(String phoneNumber, String message) {

        PendingIntent piSent = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
        PendingIntent piDelivered = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
        SmsManager smsManager = SmsManager.getDefault();

        int length = message.length();          
        if(length > MAX_SMS_MESSAGE_LENGTH) {
            ArrayList<String> messagelist = smsManager.divideMessage(message);          
            smsManager.sendMultipartTextMessage(phoneNumber, null, messagelist, null, null);
        }
        else
            smsManager.sendTextMessage(phoneNumber, null, message, piSent, piDelivered);
        }
    }

    //More methods of MainActivity ...
}

SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver {
    private final String DEBUG_TAG = getClass().getSimpleName().toString();
    private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private Context mContext;
    private Intent mIntent;

    // Retrieve SMS
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;

        String action = intent.getAction();

        if(action.equals(ACTION_SMS_RECEIVED)){

            String address, str = "";
            int contactId = -1;

            SmsMessage[] msgs = getMessagesFromIntent(mIntent);
            if (msgs != null) {
                for (int i = 0; i < msgs.length; i++) {
                    address = msgs[i].getOriginatingAddress();
                    contactId = ContactsUtils.getContactId(mContext, address, "address");
                    str += msgs[i].getMessageBody().toString();
                    str += "\n";
                }
            }   

            if(contactId != -1){
                showNotification(contactId, str);
            }

            // ---send a broadcast intent to update the SMS received in the
            // activity---
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("SMS_RECEIVED_ACTION");
            broadcastIntent.putExtra("sms", str);
            context.sendBroadcast(broadcastIntent);
        }

    }

    public static SmsMessage[] getMessagesFromIntent(Intent intent) {
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        byte[][] pduObjs = new byte[messages.length][];

        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[]) messages[i];
        }
        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
    }

    /**
    * The notification is the icon and associated expanded entry in the status
    * bar.
    */
    protected void showNotification(int contactId, String message) {
        //Display notification...
    }
}

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_MMS" />
    <uses-permission android:name="android.permission.WRITE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher_icon"
        android:label="@string/app_name" >

        <activity
            //Main activity...
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            //Activity 2 ...
        </activity>
        //More acitivies ...

        // SMS Receiver
        <receiver android:name="com.myexample.receivers.SMSReceiver" >
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

However, I was wondering if you could send and receive MMS messages in a similar fashion. After doing some research, many examples provided on blogs simply pass an Intent to the native Messaging application. I am trying to send an MMS without leaving my application. There doesn't seem to be a standard way of sending and receiving MMS. Has anyone gotten this to work?

Also, I am aware that the SMS/MMS ContentProvider is not a part of the official Android SDK, but I was thinking someone may have been able to implement this. Any help is greatly appreciated.

Update

I have added a BroadcastReceiver to the AndroidManifest.xml file to receive MMS messages

<receiver android:name="com.sendit.receivers.MMSReceiver" >
    <intent-filter>
        <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />

        <data android:mimeType="application/vnd.wap.mms-message" />
    </intent-filter>
</receiver>

In the MMSReceiver class, the onReceive() method is only able to grab the phoneNumber that the message was sent from. How do you grab other important things from an MMS such as the file path to the media attachment (image/audio/video), or the text in the MMS?

MMSReceiver.java

public class MMSReceiver extends BroadcastReceiver {
    private final String DEBUG_TAG = getClass().getSimpleName().toString();
    private static final String ACTION_MMS_RECEIVED = "android.provider.Telephony.WAP_PUSH_RECEIVED";
    private static final String MMS_DATA_TYPE = "application/vnd.wap.mms-message";

     // Retrieve MMS
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        String type = intent.getType();

        if(action.equals(ACTION_MMS_RECEIVED) && type.equals(MMS_DATA_TYPE)){

            Bundle bundle = intent.getExtras();

            Log.d(DEBUG_TAG, "bundle " + bundle);
            SmsMessage[] msgs = null;
            String str = "";
            int contactId = -1;
            String address;

            if (bundle != null) {

                byte[] buffer = bundle.getByteArray("data");
                Log.d(DEBUG_TAG, "buffer " + buffer);
                String incomingNumber = new String(buffer);
                int indx = incomingNumber.indexOf("/TYPE");
                if(indx>0 && (indx-15)>0){
                    int newIndx = indx - 15;
                    incomingNumber = incomingNumber.substring(newIndx, indx);
                    indx = incomingNumber.indexOf("+");
                    if(indx>0){
                        incomingNumber = incomingNumber.substring(indx);
                        Log.d(DEBUG_TAG, "Mobile Number: " + incomingNumber);
                    }
                }

                int transactionId = bundle.getInt("transactionId");
                Log.d(DEBUG_TAG, "transactionId " + transactionId);

                int pduType = bundle.getInt("pduType");
                Log.d(DEBUG_TAG, "pduType " + pduType);

                byte[] buffer2 = bundle.getByteArray("header");      
                String header = new String(buffer2);
                Log.d(DEBUG_TAG, "header " + header);

                if(contactId != -1){
                    showNotification(contactId, str);
                }

                // ---send a broadcast intent to update the MMS received in the
                // activity---
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction("MMS_RECEIVED_ACTION");
                broadcastIntent.putExtra("mms", str);
                context.sendBroadcast(broadcastIntent);

            }
        }

    }

    /**
    * The notification is the icon and associated expanded entry in the status
    * bar.
    */
    protected void showNotification(int contactId, String message) {
        //Display notification...
    }
}

According to the Documentation of android.provider.Telephony:

Broadcast Action: A new text based SMS message has been received by the device. The intent will have the following extra values:

pdus - An Object[] of byte[]s containing the PDUs that make up the message.

The extra values can be extracted using getMessagesFromIntent(android.content.Intent) If a BroadcastReceiver encounters an error while processing this intent it should set the result code appropriately.

 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
 public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

Broadcast Action: A new data based SMS message has been received by the device. The intent will have the following extra values:

pdus - An Object[] of byte[]s containing the PDUs that make up the message.

The extra values can be extracted using getMessagesFromIntent(android.content.Intent). If a BroadcastReceiver encounters an error while processing this intent it should set the result code appropriately.

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String DATA_SMS_RECEIVED_ACTION = "android.intent.action.DATA_SMS_RECEIVED";

Broadcast Action: A new WAP PUSH message has been received by the device. The intent will have the following extra values:

transactionId (Integer) - The WAP transaction ID

pduType (Integer) - The WAP PDU type`

header (byte[]) - The header of the message

data (byte[]) - The data payload of the message

contentTypeParameters (HashMap<String,String>) - Any parameters associated with the content type (decoded from the WSP Content-Type header)

If a BroadcastReceiver encounters an error while processing this intent it should set the result code appropriately. The contentTypeParameters extra value is map of content parameters keyed by their names. If any unassigned well-known parameters are encountered, the key of the map will be 'unassigned/0x...', where '...' is the hex value of the unassigned parameter. If a parameter has No-Value the value in the map will be null.

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String WAP_PUSH_RECEIVED_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";

Update #2

I have figured out how to pass extras in a PendingIntent to be received by a BroadcastReceiver: Android PendingIntent extras, not received by BroadcastReceiver

However, the extra gets passed to the SendBroadcastReceiver not the SMSReceiver. How can I pass an extra to the SMSReceiver?

Update #3

Receiving MMS

So after doing more research I saw some suggestions of registering a ContentObserver. That way you can detect when there are any changes to the content://mms-sms/conversations Content Provider, consequently allowing you to detect incoming MMS. Here is the closest example to get this to work that I have found: Receiving MMS

However, there is a variable mainActivity of type ServiceController. Where is the ServiceController class implemented? Are there any other implementations of a registered ContentObserver?

Sending MMS

As for sending MMS, I have come across this example: Send MMS

The problem is that I tried running this code on my Nexus 4, which is on Android v4.2.2, and I am receiving this error:

java.lang.SecurityException: No permission to write APN settings: Neither user 10099 nor current process has android.permission.WRITE_APN_SETTINGS.

The error gets thrown after querying the Carriers ContentProvider in the getMMSApns() method of the APNHelper class.

final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Carriers.CONTENT_URI, "current"), null, null, null, null);

Apparently you can't read APNs in Android 4.2

What is the alternative for all those applications which use mobile data to perform operations (like sending MMS) and don't know the default APN setting present in the device?

Update #4

Sending MMS

I have tried following this example: Send MMS

As @Sam suggested in his answer:

You have to add jsoup to the build path, the jar to the build path and import com.droidprism.*; To do that in android, add the jars to the libs directory first, then configure the project build path to use the jars already in the libs directory, then on the build path config click order and export and check the boxes of the jars and move jsoup and droidprism jar to the top of the build order.

So now I no longer get the SecurityException errors. I am testing now on a Nexus 5 on Android KitKat. After running the sample code it gives me a 200 response code after the call to

MMResponse mmResponse = sender.send(out, isProxySet, MMSProxy, MMSPort);

However, I checked with the person I tried sending the MMS to. And they said they never received the MMS.


Source: (StackOverflow)

Programmatically register a broadcast receiver

I'd like to know what is the best practice/way of programmatically register a broadcast receiver. I want to register specific receivers according to user choice.

As the registration is done through the manifest file, I'm wondering if there's a proper way to achieve this in code.


Source: (StackOverflow)

Advertisements

Using a broadcast intent/broadcast receiver to send messages from a service to an activity

So I understand (I think) about broadcast intents and receiving messages to them.

So now, my problem/what I can't work out is how to send a message from the onReceive method of a receiver to an activity. Lets say I have a receiver as such:

public class ReceiveMessages extends BroadcastReceiver 
{
@Override
   public void onReceive(Context context, Intent intent) 
   {    
       String action = intent.getAction();
       if(action.equalsIgnoreCase(TheService.DOWNLOADED)){    
           // send message to activity
       }
   }
}

How would I send a message to an activity?

Would I have to instantiate the receiver in the activity I want to send messages to and monitor it somehow? Or what? I understand the concept, but not really the application.

Any help would be absolutely amazing, thank you.

Tom


Source: (StackOverflow)

Enable and disable a Broadcast Receiver

I try to enable and disable a broadcast receiver by using this PackageManager method:

setComponentEnabledSetting(componentName,
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP);

The broadcast receiver is registered in the manifest. The receiver works fine but when i try to disable it, it still receives the broadcast messages. When i disable the receiver in the manifest by "android:enabled="false"", the receiver does not receive anything but I can not enable it.

I call the method from inside a service.

    PackageManager pm  = getApplicationContext().getPackageManager();
    ComponentName componentName = new ComponentName("com.app",
             ".broadcast_receivers.OnNetworkChangedReceiver");
    pm.setComponentEnabledSetting(componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);

Android manifest:

    <receiver android:name=".broadcast_receivers.OnNetworkChangedReceiver"
                android:enabled="true">
            <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
    </receiver>

The Receiver

public class OnNetworkChangedReceiver extends BroadcastReceiver {
private static final String TAG = "OnNetworkChangedReceiver";

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "in OnNetworkChanged");
    }
}

I also called the method from inside an Activity yesterday. I thought it worked but today nothing works anymore. Could it be that there is sometimes a big delay in the intent (android.net.conn.CONNECTIVITY_CHANGE) that I misinterpreted yesterday as disabling the receiver?

Is the approach with the PackageManager the right direction or is there a basic error in the idea?

Thanks a lot, Sven


Source: (StackOverflow)

how to check if Receiver is registered in android

I need to check if my registered receiver is still registered if not how do i check it any methods?


Source: (StackOverflow)

Android BroadcastReceiver within Activity

I'm just trying this little sample project, all it does: Activity one has a Button that sends a Broadcast. Activity two displays a toast when received. Below is the code, the Broadcast is never received. What do I do wrong?

Sending the Broadcast

public class SendBroadcast extends Activity {

    public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void sendBroadcast(View v){
        Intent broadcast = new Intent();
        broadcast.setAction(BROADCAST_ACTION);
        sendBroadcast(broadcast);
    }
}

Receiving it

public class ToastDisplay extends Activity {

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);
        }
    };

    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SendBroadcast.BROADCAST_ACTION);
        registerReceiver(receiver, filter);
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(receiver);
        super.onPause();
    }
}

Manifest

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".SendBroadcast" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ToastDisplay">
        <intent-filter>
            <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"></action>
        </intent-filter>
    </activity>
</application>

Source: (StackOverflow)

Determine addAction click for Android notifications

I'm trying to use the new notifications interface. I've added 3 buttons to the notifications, and I want to save something to my database once each of them is clicked.

The notification itself works well and is shown when called, I just don't know how to capture each of the three different button clicks.

I'm using a BroadcastReceiver to catch the clicks, but I don't know how to tell which button was clicked.

This is the code of AddAction(I've excluded the rest of the notification, as it's working well) -

    //Yes intent
    Intent yesReceive = new Intent();  
    yesReceive.setAction(CUSTOM_INTENT);
    Bundle yesBundle = new Bundle();            
    yesBundle.putInt("userAnswer", 1);//This is the value I want to pass
    yesReceive.putExtras(yesBundle);
    PendingIntent pendingIntentYes = PendingIntent.getBroadcast(this, 12345, yesReceive, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.addAction(R.drawable.calendar_v, "Yes", pendingIntentYes);

    //Maybe intent
    Intent maybeReceive = new Intent();  
    maybeReceive.setAction(CUSTOM_INTENT);
    Bundle maybeBundle = new Bundle();            
    maybeBundle.putInt("userAnswer", 3);//This is the value I want to pass
    maybeReceive.putExtras(maybeBundle);
    PendingIntent pendingIntentMaybe = PendingIntent.getBroadcast(this, 12345, maybeReceive, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.addAction(R.drawable.calendar_question, "Partly", pendingIntentMaybe);

    //No intent
    Intent noReceive = new Intent();  
    noReceive.setAction(CUSTOM_INTENT);
    Bundle noBundle = new Bundle();            
    noBundle.putInt("userAnswer", 2);//This is the value I want to pass
    noReceive.putExtras(noBundle);
    PendingIntent pendingIntentNo = PendingIntent.getBroadcast(this, 12345, noReceive, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.addAction(R.drawable.calendar_x, "No", pendingIntentNo);

This is the code of the BroadcastReceiver-

 public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Log.v("shuffTest","I Arrived!!!!");
     //Toast.makeText(context, "Alarm worked!!", Toast.LENGTH_LONG).show();

    Bundle answerBundle = intent.getExtras();
    int userAnswer = answerBundle.getInt("userAnswer");
    if(userAnswer == 1)
    {
        Log.v("shuffTest","Pressed YES");
    }
    else if(userAnswer == 2)
    {
        Log.v("shuffTest","Pressed NO");
    }
    else if(userAnswer == 3)
    {
        Log.v("shuffTest","Pressed MAYBE");
    }

}           
}

I've registered the BroadcastReceiver in the Manifest. Also, I want to mention that the BroadcastReceiver is called when I click one of the buttons in the notification, but the intent always includes an extra of '2'.

This is the notifcation iteslf - notification


Source: (StackOverflow)

BroadcastReceiver not receiving BOOT_COMPLETED

I've looked around here for similiar problems, but for some reason my BroadcastReceiver never ends up receiving the android.intent.action.BOOT_COMPLETED Intent.

Here is my (relative) Android.Manifest File:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>    
<receiver android:name=".BootReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="BootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>

        </intent-filter>
    </receiver>

And Here is the actual Receiver.

public class BootReceiver extends BroadcastReceiver {
private static final String TAG="BootReceiver";

@Override public void onReceive(Context context,Intent intent){
    try{
        context.startService(new Intent(context,ConnectivityListener.class));
        Log.i(TAG,"Starting Service ConnectivityListener");
    }catch(Exception e){
        Log.e(TAG,e.toString());
    }
}
}

Thanks! Any help is greatly appreciated


Source: (StackOverflow)

Android BroadcastReceiver or simple callback method?

In my projects I am using BroadcastReceivers as a callback from a long running thread (eg. notify the activity that a download was finished and send some response data from a Worker Thread so that the activity can display the appropriate message to the user..). To use BroadcastReceivers I have to be careful to register and unregister the broadcast receiver each time I am using it and also have to care of what messages to send esspecialy when I am using this method for more different actions(like downloading, making WebService calls etc..). And also to send custom Objects through Broadcast's intent I need also to make the objects Parcelable.

Unlike this approach, I have seen also the callback methods approach which appears to be simpler than the method I use. Callback methods are simple Interface methods implementation that can be used to achieve the same effect like the BroadcastRecaiver's in app messaging. This approach doesn't need Parcelable implementation to return complex objects and it doesn't use keys like BroadcastReceiver.. I think the bad part is that I need to check the callback object for null value before I want to call a callback method.. and also to make sure I am running the code from the implementation on the UI thread so I can update the UI without errors.

Ok, I hope you understood what I meant to say :).

Now the question is do you think that the callback method is better (lighter, cleaner, faster..) than the BroadcastReceiver approach when are used just inside of a single application? (Note that I am not using Android Service for background work.. just AsyncTask and Threads)

Thank you!


Source: (StackOverflow)

Android - SMS Broadcast receiver

I have been trying to get this program to work but so far having no luck. I cannot find where I am doing wrong. I'm not sure if there's something wrong with the code, or debugging.

I'm trying to be notified if a new SMS arrives.

Here is my program:

package Technicaljar.SMSBroadcastReceiver;

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 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() == 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 the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Technicaljar.SMSBroadcastReceiver"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true" >
        <receiver android:name=".SMSBroadcastReceiver">
            <intent-filter>
                <action android:name="android.provider.telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest> 

I am sending SMS through Telnet, and I cannot see any Intent received messages in the logcat. Here is my logcat from the time of installation.

D/AndroidRuntime(  478): 
D/AndroidRuntime(  478): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  478): CheckJNI is ON
D/AndroidRuntime(  478): --- registering native functions ---
D/AndroidRuntime(  478): Shutting down VM
D/dalvikvm(  478): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  478): NOTE: attach of thread 'Binder Thread #3' failed
D/Mms:app (  220): getSmsNewMessageNotificationInfo: count=14, first addr=12345, thread_id=4
D/dalvikvm(  151): GC_EXPLICIT freed 391 objects / 22552 bytes in 65ms
D/dalvikvm(  220): GC_EXPLICIT freed 926 objects / 44840 bytes in 73ms

So the SMS seems to be received by the emulator, but looks like the no intents are firing. What am I doing wrong here? After installing, do I have to somehow 'start' this receiver? Because when I install, I get

 [2010-11-07 21:24:41 - SMSBroadcastReceiver] No Launcher activity found!
[2010-11-07 21:24:41 - SMSBroadcastReceiver] The launch will only sync the application package on the device!

So I'm wondering if something's wrong here.


Source: (StackOverflow)

BroadcastReceiver with multiple filters or multiple BroadcastReceivers?

I have an Android Activity that needs to catch two different broadcasts. My current approach is to have a single BroadcastReceiver within the Activity and catch both the broadcasts with it:

public class MyActivity extends Activity {
    private MyActivity.BroadcastListener mBroadcastListener;
    private boolean mIsActivityPaused = false;

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

        // Create the broadcast listener and register the filters
        mIsActivityPaused = false;
        mBroadcastListener = new BroadcastListener();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Params.INTENT_REFRESH);
        filter.addAction(Params.INTENT_UPDATE);
        registerReceiver(mBroadcastListener, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsActivityPaused = true;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mBroadcastListener);
        super.onDestroy();
    }

    private void refresh() {
        // refresh
    }

    private void update() {
        // update
    }

    private class BroadcastListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Params.INTENT_REFRESH && !mIsActivityPaused)) {
                refresh();
            } else if (intent.getAction().equals(Params.INTENT_UPDATE)) {
                update();
            }
        }
    }
}

I want to execute refresh() only if my Activity is visible on the screen, but I want to catch INTENT_UPDATE and execute update() during the entire lifetime of the Activity, regardless of whether the Activity is visible or not.

I didn't find any way to unregister only one of the two filters that I register in onCreate, so I use a flag to enable or disable the action to be executed when the INTENT_REFRESH broadcast is caught, depending on the state of the Activity.

The question is: is this the correct approach?

Or, would it be better to have two separate BroadcastReceivers as follows:

public class MyActivity extends Activity {
    private MyActivity.BroadcastListenerRefresh mBroadcastListenerRefresh;
    private MyActivity.BroadcastListenerUpdate mBroadcastListenerUpdate;
    private boolean mIsBroadcastListenerRefreshRegistered = false;

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

        // Create the broadcast listeners
        mBroadcastListenerRefresh = new BroadcastListenerRefresh();
        mBroadcastListenerUpdate = new BroadcastListenerUpdate();

        registerReceiver(mBroadcastListenerRefresh, new IntentFilter(Params.INTENT_REFRESH));
        registerReceiver(mBroadcastListenerUpdate, new IntentFilter(Params.INTENT_UPDATE));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBroadcastListenerRefresh != null && !mIsBroadcastListenerRefreshRegistered) {
            registerReceiver(mBroadcastListenerRefresh, new IntentFilter(Params.INTENT_REFRESH));
            mIsBroadcastListenerRefreshRegistered = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBroadcastListenerRefresh != null && mIsBroadcastListenerRefreshRegistered) {
            unregisterReceiver(mBroadcastListenerRefresh);
            mIsBroadcastListenerRefreshRegistered = false;
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mBroadcastListenerRefresh);
        unregisterReceiver(mBroadcastListenerUpdate);
        super.onDestroy();
    }

    private void refresh() {
        // refresh
    }

    private void update() {
        // update
    }

    private class BroadcastListenerRefresh extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Params.INTENT_REFRESH)) {
                refresh();
            }
        }
    }

    private class BroadcastListenerUpdate extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Params.INTENT_UPDATE)) {
                update();
            }
        }
    }
}

And which one has better performance?


Source: (StackOverflow)

Pop up window over Android native incoming call screen like true caller Android app

Update -- 09 May 2013 *I tried to implement Toast in the broadcast receiver's onReceive method because toast is a native component of Android, but it is also not getting displayed in Android 4.1 (Jelly Bean).

My idea was to implement Toast in the broadcast receiver's onReceive method and afterwards changing its design according to our needs and tuning its duration of display. But one more problem is that findViewById doesn't work in the broadcast receiver, so I think we have to make a LinearLayout programmatically for customizing the toast.*

Update -- After bounty also I am not getting the exact thing I am looking for, but I will get back to all; I am working upon it. Anyway, this code works for most Android phones. If anybody is going to use and catch the solution for it, please write here so that everybody can get the benefit. Thanks for all your answers.

I am developing a broadcast receiver for in coming calls in Android and on getting incoming calls I want to inflate an pop up over the native incoming call screen.

I completed that code. But now the problem is that in the Android 4.1 (Jelly Bean) API level 17 when a phone rings, the PHONE_STATE is coming as OFF HOOK, and if I am calling an activity, it gets called, but the code under it doesn't get executed. I am listing the code:

My broadcast receiver

package com.example.popwindowonincomingcallscreen;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;

public class IncomingBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("IncomingBroadcastReceiver: onReceive: ", "flag1");

        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        Log.d("IncomingBroadcastReceiver: onReceive: ", state);
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)
                || state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {

            Log.d("Ringing", "Phone is ringing");

            Intent i = new Intent(context, IncomingCallActivity.class);
            i.putExtras(intent);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            Wait.oneSec();
            context.startActivity(i);
        }
    }
}

An the activity which I am calling:

import android.app.Activity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View.MeasureSpec;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

public class IncomingCallActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        try {
            Log.d("IncomingCallActivity: onCreate: ", "flag2");

            */ After this line, the code is not executed in Android 4.1 (Jelly Bean) only/*

            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

            Log.d("IncomingCallActivity: onCreate: ", "flagy");

            setContentView(R.layout.main);

            Log.d("IncomingCallActivity: onCreate: ", "flagz");

            String number = getIntent().getStringExtra(
                    TelephonyManager.EXTRA_INCOMING_NUMBER);
            TextView text = (TextView) findViewById(R.id.text);
            text.setText("Incoming call from " + number);
        } 
        catch (Exception e) {
            Log.d("Exception", e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

After

try {
    Log.d("IncomingCallActivity: onCreate: ", "flag2");
}

The code is not executing in Android 4.1 (Jelly Bean), but in other versions it is working.

I have tried almost all ways I can do. This code is displaying an translucent activity over the native call screen, and it doesn't block background controls, like picking up the phone. But I want it like true caller. I have attached an snapshot on how the true caller is displaying a window on the incoming call screen.

How can I achieve this functionality for an Android app?

This is how a true caller works:

Enter image description here

My present output:

Enter image description here


Source: (StackOverflow)

Is there any way to receive a notification when the user powers off the device?

I need to know when the user powers off his/her phone. Are there any broadcasts (or similar) that notify when the user's phone is powered off?


Source: (StackOverflow)

android - "Exported receiver does not require permission" on receivers meant to receive from system services

I have some receivers declared in my manifest :

<receiver <!-- no warning -->
    android:name=".receivers.TriggerMonitoringBootReceiver"
    android:enabled="false" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<receiver <!-- no warning -->
    android:name=".receivers.ScanResultsReceiver"
    android:enabled="false" >
    <intent-filter>
        <action android:name="android.net.wifi.SCAN_RESULTS" />
    </intent-filter>
</receiver>
<receiver <!-- warning : Exported receiver does not require permission-->
    android:name=".receivers.BatteryMonitoringReceiver"
    android:enabled="false" >
    <intent-filter>
        <action android:name="@string/intent_action_setup_alarm" />
        <action android:name="@string/intent_action_cancel_alarm" />
        <action android:name="@string/intent_action_monitor" />
    </intent-filter>
</receiver>

The first one is meant to receive a BOOT_COMPLETED action. The second is meant to receive android.net.wifi.SCAN_RESULTS. The third one is meant to receive some actions I broadcast (intent_action_monitor) and some actions broadcasted by the AlarmManager (intent_action_setup_alarm etc).
Two questions :

  • Why don't I get the warning on all receivers ?
  • What permissions do I need to set for receivers meant to receive from system services to correct the warning (I understand what it is about and I don't want anyone to use my receivers anyway) ? Will exported="false" do for boot receivers, wifi receivers, alarm receivers etc ?
    I thought of using a custom permission with android:protectionLevel="signatureOrSystem" but the docs advise against both this protection level and custom permissions. So how I should handle this warning ?

Links to the docs and/or some code will be much appreciated.


Source: (StackOverflow)

Android - Start service on boot

From everything I've seen on Stack Exchange and elsewhere, I have everything set up correctly to start an IntentService when Android OS boots. Unfortunately it is not starting on boot, and I'm not getting any errors. Maybe the experts can help...

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.phx.batterylogger"
  android:versionCode="1"
  android:versionName="1.0"
  android:installLocation="internalOnly">

<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <service android:name=".BatteryLogger"/>
    <receiver android:name=".StartupIntentReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
        </intent-filter>  
    </receiver>
</application>

</manifest>

BroadcastReceiver for Startup:

package com.phx.batterylogger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class StartupIntentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent serviceIntent = new Intent(context, BatteryLogger.class);
        context.startService(serviceIntent);
    }
}

UPDATE: I tried just about all of the suggestions below, and I added logging such as Log.v("BatteryLogger", "Got to onReceive, about to start service"); to the onReceive handler of the StartupIntentReceiver, and nothing is ever logged. So it isn't even making it to the BroadcastReceiver.

I think I'm deploying the APK and testing correctly, just running Debug in Eclipse and the console says it successfully installs it to my Xoom tablet at \BatteryLogger\bin\BatteryLogger.apk. Then to test, I reboot the tablet and then look at the logs in DDMS and check the Running Services in the OS settings. Does this all sound correct, or am I missing something? Again, any help is much appreciated.


Source: (StackOverflow)