sgon00
sgon00

Reputation: 5777

How to getAssets in a service?

I fail to find out how to getAssets in a service.

for example the receiver:

public class BroadcastReceiverOnBootComplete extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent);
            } else {
                context.startService(serviceIntent);
            }
        }
    }
}

In the AndroidServiceStartOnBoot class, how to get getContext().getAssets().open("server.crt"); ?

Thanks a lot.

Edited:

The question is not how to call getAssets in BroadcastReceiverOnBootComplete class, instead, the question is how to getAssets in the service AndroidServiceStartOnBoot class.

The reason why I posted BroadcastReceiverOnBootComplete class is because that is how I call AndroidServiceStartOnBoot class. Sorry that it's kinda misleading. Thanks.

Upvotes: 2

Views: 834

Answers (2)

Jay Patel
Jay Patel

Reputation: 2451

onReceive gives you the context in your broadcast receiver class

public abstract void onReceive (Context context, Intent intent)

from there, you can use it directly or assign it to your class level variable and you'll be able to use it in other methods as well

Context myContext = null;

@Override
public void onReceive(Context context, Intent intent) {
    //here you can access to context directly
    context.getAssets().open("MY_FILE");
    //or you can save it in your class level variable
    myContext = context;
    // now you can use this myContext to other methods of this class
}

Edit

Service is an inherent of Context

So in Service, you can directly do like this...

Context context = this;

Upvotes: 1

Milad Bahmanabadi
Milad Bahmanabadi

Reputation: 968

You already have context
did you try this?
context.getAssets().open("FILE_NAME");
it works for me

enter image description here

Upvotes: 0

Related Questions