我的应用程序从服务接收到一个 Intent ,然后弹出一个通知。这个 Intent 有一个对象 ID,我想从我的数据库中检索整个对象,以便我可以设置通知标题和副标题。但是,我需要将一个上下文传递给我的 dbManager,而且无论我尝试使用哪个上下文,我都会收到错误消息。
代码如下:
public class ReceiveTransitionsIntentService extends IntentService {
private DBManager dbManager;
public ReceiveTransitionsIntentService() {
super("ReceiveTransitionsIntentService");
}
protected void onHandleIntent(Intent intent) {
//somewhere
sendNotification(..);
}
private void sendNotification(String transitionType, String ids) {
Intent notificationIntent =
new Intent(getApplicationContext(),MainActivity.class);
...
//have tried with getbaseContext() and this, still failures
dbManager = new DBManager(getApplicationContext());
...
}
}
有人对我能做什么有什么想法吗?
这些是错误:
新的 DBManager(this) -> java.lang.ClassCastException: .ReceiveTransitionsIntentService 无法转换为 android.app.Activity
新的 DBManager(getApplicationContext) -> java.lang.ClassCastException: android.app.Application 无法转换为 android.app.Activity
新的 DBManager(getBaseContext) -> java.lang.ClassCastException: android.app.Contextimpl 不能转换为 android.app.activity
最佳答案
您将获得以下内容:
java.lang.ClassCastException:
.ReceiveTransitionsIntentService cannot be cast to android.app.Activity
new DBManager(getApplicationContext) ->
java.lang.ClassCastException: android.app.Application
cannot be cast to android.app.Activity
new DBManager(getBaseContext) ->
java.lang.ClassCastException:
android.app.Contextimpl cannot be cast to android.app.activity
这仅仅意味着您正在接收参数中的 Activity。那是你的函数签名包含:
functionName(Activity context);
将函数更改为:
functionName(Context context), thus when you pass context, as `this`
或someOtherActivity.this
或getApplicationContext()
它不会导致错误。
关于java - 在服务接收器中使用什么来实例化对象的正确上下文是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770692/