Search code examples
androidservicebroadcastreceiver

Issue while creating BroadcastReceiver inside Service


I have a service in which I have registered a simple Broadcast receiver to check whether the device is plugged/unplugged from the charger. I started the service by calling,

      Intent intent = new Intent(MyActivity.this,TestReceiverService.class); 
      startService(intent);

TestReceiverService.class

public class TestReceiverService extends Service {
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
}

@Override
public void onCreate() {
    super.onCreate();
    registerTestReceiver();
}


private void registerTestReceiver() {

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(mTestReceiver, intentFilter);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {

    return null;
}

public BroadcastReceiver mTestReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Event triggered--------", Toast.LENGTH_SHORT).show();
    }
};}

But I didn't get the toast when the device is plugged / unplugged. I have tried to call this broadcast receiver directly from activity and it worked.But inside service it is not working. I am not much familiar with service. Please suggest a solution

Thanks in advance.


Solution

  • If you want to do it only once, then your logic is okay.

    onCreate will call only once, so it will execute one time. Whenever any client calls startService() or bindService(), then that service will return the available binder and the onServiceConnected() call back will called.

    This means that next time it won't execute onCreate() again, so for your case this toast has displayed only once.

    So onStartCommand() or onBind() will call directly whenever a user tries to call startService() or bindService().

    Or if you want to display the toast whenever you connect with service, then you have to do either in onStart() or onBind()