0

I created a Service to Upload data in Background. If there's no Internet Connection I want to register a Broadcast Receiver which is waiting for Internet Connection and then start the Service again. My Problem:

The broadcastreceiver starts with the app. I don't want this. The broadcastreceiver should be unregisteres until the Service register it. How can I do this?

And can anybody post a Code Sample how to register an unregister the Receiver from service?

Thanks

t18935
  • 59
  • 1
  • 6
  • possible duplicate of [Programmatically register a broadcast receiver](http://stackoverflow.com/questions/4805269/programmatically-register-a-broadcast-receiver) – Sam Dozor Aug 22 '14 at 18:10

1 Answers1

2

Example code which registers receiver and unregisters receiver inside service.

public class CallDetectService extends Service {
    BroadcastReceiver phoneCallreceiver;
    Calendar futuretime=Calendar.getInstance();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        Log.v("ranjith","Inside onstartcommand of calldetectservice");

        phoneCallreceiver = new PhoneCallreceiver();

        registerReceiver(phoneCallreceiver, intentFilter);


        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(getApplicationContext(), "Service destroy called", Toast.LENGTH_LONG).show();
        Log.v("ranjith", "stopped the service");
        if (phoneCallreceiver != null) {

            unregisterReceiver(phoneCallreceiver);
            Log.v("ranjith", "Unregistered receiver");
        }
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
Psypher
  • 10,717
  • 12
  • 59
  • 83