首页 文章

如何在服务中获取资产?

提问于
浏览
2

我没有找到如何在服务中 getAssets .

例如接收器:

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);
            }
        }
    }
}

AndroidServiceStartOnBoot 类中,如何获取 getContext().getAssets().open("server.crt");

非常感谢 .

Edited:

问题不是如何在 BroadcastReceiverOnBootComplete 类中调用 getAssets ,相反,问题是如何在服务 AndroidServiceStartOnBoot 类中 getAssets .

我发布 BroadcastReceiverOnBootComplete 类的原因是因为这就是我调用 AndroidServiceStartOnBoot 类的方法 . 对不起,这有点误导 . 谢谢 .

2 回答

  • 0

    你已经 context
    你试过这个吗?
    context.getAssets().open("FILE_NAME");
    这个对我有用

    enter image description here

  • 2

    onReceive为您提供广播接收器类中的上下文

    public abstract void onReceive (Context context, Intent intent)
    

    从那里,你可以直接使用它或将它分配给你的类级别变量,你也可以在其他方法中使用它

    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
    }
    

    编辑

    ServiceContext的固有内容

    所以在服务中,你可以直接这样做......

    Context context = this;
    

相关问题