Search code examples
androidbroadcastreceiverandroid-service

How to make BroadcastReceiver work after reboot?


I have a written a program which intercepts incoming call using BroadcastReceiver. When I start my app, it starts working. Now the problem is when I restart my android phone, this BroadcastReceiver doesn't work. So I am assuming that I need to make a service for this. But I don't know when to start service and where to start BroadcastReceiver.

BroadcastReceiver code -

public class CallInterceptor extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Service started", Toast.LENGTH_LONG).show();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        String state = extras.getString(TelephonyManager.EXTRA_STATE);
        Toast.makeText(context, "Phone is " + state, Toast.LENGTH_LONG).show();
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            String phoneNumber = extras
                    .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            Toast.makeText(context, "Call from " + phoneNumber, Toast.LENGTH_LONG).show();
            //sendSMS(phoneNumber);

            //toggle ringer mode
            AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            toggleMode(am);
        }

    }

}

AndroidManifest file -

<receiver android:name="com.nagarro.service.CallInterceptor" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" >
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                </action>
            </intent-filter>
        </receiver>

I don't think <action android:name="android.intent.action.BOOT_COMPLETED" /> is working.

Also, is it possible to do this without service? Please suggest approach which will help me to intercept call evertime (even after reboot).


Solution

  • You've improperly closed your first action tag. Your receiver section should look like:

    <receiver android:name="com.nagarro.service.CallInterceptor" >
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    

    Also, you are not using a Service. You're using a Broadcast Receiver. See this page for the basics Application Fundamentals.