简体   繁体   中英

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

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.

Instead of getAppContext() try with context like below:

database = Room.databaseBuilder(context, AppDatabase.class, "mydb").
...

Context already here which is enough to create and manipulate database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM