Search code examples
androidservicebroadcastreceiverbackground-service

why Broadcast receiver is not working continuously inside service


My Broadcast receiver is working properly inside the Service until my application is running but immediately stops working if I close my application.

Here, I want my application to detect internet change and show a Toast every time but the Toast messages are shown until my application is working.

I've started my service in the MainActivity and defined my broadcast inside my service.

Inside onCreate in MainActivity-

Intent service = new Intent(MainActivity.this, LatestCallService.class);
    startService(service);

BroadcastReceiver inside the service:

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

  IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    _mContext = getApplicationContext();
    _mContext.registerReceiver(br, filter);

Please let me know what is wrong with my code.


Solution

  • I've changed my code. I've stared the foreground service after which my code is working and broadcast receiver also working even after closing the application.

    Foreground service in main Activity-

      Intent serviceIntent = new Intent(this, LatestCallService.class);
      serviceIntent.putExtra("inputExtra", "Foreground Service");
      ContextCompat.startForegroundService(this, serviceIntent);
    

    Android Manifest file-

      uses-permission android:name="android.permission.FOREGROUND_SERVICE"
    

    This way you can see whether your service is working in the background or not. Hope that helps!! :)