Search code examples
androidbroadcastreceiverstatic-variables

MediaRecorder static object becomes null in onReceive


I have a BroadcastReceiver for receive call states and record calls.

public class CallBroadcastReceiver extends BroadcastReceiver {
    private static MediaRecorder recorder;

    ...
}

The problem is when the call takes a long time, the recorder object becomes null.

I know android OS kills the application's process after a while and clears static variables from memory for freeing up the device's RAM.

It is clear that I can't use Preferences or Database for saving recorder object.

So how can I solve my problem?

Note: I have this problem just in android 6.

Thank you for your answers.


Solution

  • I found the solution :

    I have a Service that starts BroadcastReceiver class and a method that registers the receiver:

    public class TService extends Service {
         @Override
         public int onStartCommand(Intent intent, int flags, int startId) {
    
              ...
    
              br_call = new CallBroadcastReceiver();
              this.registerReceiver(br_call, filter);
    
              //****** THE SOLUTION IS HERE *******
              return START_STICKY;
         }
    }
    

    I replaced the return START_NO_STICKY; with return START_STICKY; so the receiver's variables sticks in the memory during the calls and then the recorder object never becomes null.