Asqan
Asqan

Reputation: 4479

Using Context in Receiver Class

I have an application which starts when the device is opened. What i try to do is not opening any activity, instead, an thread which does some process.

Here is my receiver class:

public class BOOTReceiver extends BroadcastReceiver {
   Info info = new Info();

   public void onReceive(Context context, Intent intent) {
       assignUserInfo(context);
       SomeThread u = new SomeThread(info);
       u.run();
   }

   private void assignUserInfo(Context ctx) {
       info.setInfo(AnotherClass.getInfo(ctx));
    }
}

If i call 'assignUserInfo' which calls another classes with parameter "context", then app does not start. Otherwise, thread is working.

What is wrong with this code?

Upvotes: 0

Views: 78

Answers (2)

Asqan
Asqan

Reputation: 4479

As pskink stated, i saw the following notes in the documentation:

Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it.

Thus, containing all the processess in the onReceive() function resolves my problem.

However, again from documentation:

This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.

Thus, as Junior Buckeridge stated, using Service is also an alternative to do more longer operations.

Upvotes: 0

Junior Buckeridge
Junior Buckeridge

Reputation: 2085

I think you should use an IntentService to do the thread processing. Also, if your app can wake up the phone, you should try extending your receiver from WakefulBroadcastReceiver. As an additional recommendation, try using the application context when possible

context.getApplicationContext();

to avoid memory leaks.

http://developer.android.com/reference/android/app/IntentService.html http://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

Hope it helps.

Upvotes: 1

Related Questions