There is a class in one of the methods of which you want to send a message using sendBroadcast. To call this method you need a context. Like that:

class Storage { void update(){ ... sendBroadcast(intent); } } 

The question is which is the most appropriate method for obtaining context in a class.

    1 answer 1

    I ask an example of passing the context to the class through the constructor

     class FirstClass{ // Cсылка Π½Π° контСкст private Context context; //ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ контСкст Π² конструктуС public YourTwoClass(Context context){ this.context=context; } 

    }

    Or one more example with it you can get the context "everywhere"

     public class MyApplication extends Application { static Context context; @Override public onCreate() { super.onCreate(); this.context = getApplicationContext() } public static Context getApplicationContext() { return this.context; } } 

    Do not forget to add to manifest and then throw an error

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

    and here is our hero

      MyApplication.getContext(); // ΠΏΠΎΠ»ΡƒΡ‡Π°ΠΉ Π»ΡŽΠ±ΠΈΠΌΡ‹ΠΉ контСкст))) 
    • The second example is not entirely clear. How can I use this in the static getApplicationContext method? - tilin
    • With this, you watch all the available methods of the class "Object" link. I advise you to try the code and it will make you clearer at the time of writing - elik
    • one
      I do not see something? The studio also tells me: error: non-static variable this cannot be referenced from a static context - tilin
    • one
      @tilin, error in the code. Context context must be static - YuriySPb ♦
    • one
      @elik probably your first option is optimal and easy, thanks. - tilin