Search code examples
javaandroidbroadcastreceiver

How to call GetAppContext from Broadcast Receiver?


I'm trying to set up an app, where i update database from broadcast receiver, but when i have class of it, i can't extend AppCompatActivity in which there is getAppContext, needed for database calling, how can i get over it?

 public class AlarmReceiver extends BroadcastReceiver {

public static AppDatabase database;

@Override
public void onReceive(Context context, Intent intent) {
            database = Room.databaseBuilder(getAppContext(), AppDatabase.class, "mydb").
//get app context is red there, "cant resolve method"

                    allowMainThreadQueries().

                    build();

            UserDAO userDAO = database.getUserDAO();
            User user1 = new User();
            user1.setId(2);
            user1.setName("xDDDD");
            user1.setPassword("1234");
            userDAO.insert(user1);
        }
    }

Solution

  • You can:

    1- Make an Application class MyApplication that extends Application class and use it as global context for your receiver

    2- (not guaranteed, you may try) Cast the context parameter that you receive in onReceive method to AppCompatActivity then call getAppContext

    Hint* I don't recommend database code inside the onReceive method. It is better to make another service or intentservice and let the service handle the database code.

    Edit:

    First create new class in your main package:

    public class MyApplication extends Application {
    
        private static Context context;
    
        public void onCreate() {
            super.onCreate();
            MyApplication.context = getApplicationContext();
        }
    
        public static Context getAppContext() {
            return MyApplication.context;
        }
    }
    

    Then In the Android Manifest file, declare the following.

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

    Now in your onReceive method or anywhere you can call MyApplication.getAppContext() to get your application context.