Android How to read an asset from outside the main activity

I need to be able to call readAsset from outside the main action of my application. I heard people talking about the need to go around the context, but the language was very vague. Can someone describe the steps necessary to add the ability to call readAsset into an existing class, which is not the main activity? Creating a public function in the main action and calling others that will not work as the place where you want to add readAsset is in a separate thread.

+5
source share
3 answers
public class NonActivity {
    public void doStuff(Context c) {
        //read from assets
        c.getAssets();
        //use assets however
    }
}

, , , , - ? . :

public class MyActivity extends Activity {
  public void OnCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    NonActivity n = new NonActivity();
    n.doStuff(this);
  }
}
+7

, , onCreate(). , , AysncTask.

0

, Context, Activity, Context; Application.

Android ? ?

public class MyApplication extends Application {
    private static MyApplication instance;

    public MyApplication() {
        instance = this;
    }

    public static MyApplication getInstance() {
         return instance;
    }
}

android:name <application> AndroidManifest.xml:

 <application android:name="com.example.MyApplication" ... />

MyApplication.getInstance().getAssets() .

Alternatively, you can use the Dagger dependency injection to inject Applicationdirectly into your object. (Embedding the context is a Applicationlittle tricky. See Dagger 2: Embedding the Android context , and this issue was filed in the Danger github repository .)

0
source

All Articles