在我的应用程序中,当广播接收器执行它所做的事情时,我也想启动一个数据库操作,但是处理数据库操作的类需要重新检查数据库单例的实例,我通常在应用程序对象中保存它,无法通过服务上下文访问
以下是发生的事情:
这是我的数据库处理程序:
public class DatabaseManager extends SQLiteOpenHelper {
// Its a good practice for DBTools to be a singleton. Do not instantiate it with "new DBTools(context)" but with
// DBTools.getInstance(context) instead
private static DatabaseManager sInstance;
public SQLiteDatabase database;
public static DatabaseManager getInstance(Context context) {
if (sInstance == null) {
sInstance = new DatabaseManager(context);
}
return sInstance;
}
public DatabaseManager(Context context) {
super(context, Preferences.LOCAL_SQLITE_DATABASE_NAME, null, 1);
}
在我的应用程序类中,我以这种方式实现它:
// SQLite Database Handler
public DatabaseManager databaseManager;
@Override
public void onCreate() {
super.onCreate();
databaseManager = DatabaseManager.getInstance(this);
在我的接收器中我想开始一个数据库操作:
public class PushNotificationReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//DatabaseManager databaseManager = DatabaseManager.getInstance(context); -> This didnt work when the database was closed in onDestroy of my app.
new IncrementProgressIntoDB(context, eventId).execute();
这是IncrementProgressIntoDB
public class IncrementProgressIntoDB extends AsyncTask<Void, Void, Boolean> {
private int eventId;
private Context context;
public IncrementProgressIntoDB(Context context, int eventId) {
this.context = context;
this.eventId= eventId;
}
@Override
protected Boolean doInBackground(Void... params) {
((MyApplication) context).databaseManager.database.beginTransaction();
在最后一行中,我得到以下异常:
06-02 10:45:00.552: E/AndroidRuntime(7778):
Caused by: java.lang.ClassCastException: android.app.ReceiverRestrictedContext
cannot be cast to com.asdqwe.asd.MyApplication
我从这里尝试了解决方案:Static way to get 'Context' on Android?
但是我得到的上下文无法将databaseManager解析为字段。
答案 0 :(得分:1)
在onReceive()
的{{1}}方法中,替换:
BroadcastReceiver
使用:
new IncrementProgressIntoDB(context, eventId).execute();
试试这个。它应该工作。