java - 在服务接收器中使用什么来实例化对象的正确上下文是什么?

标签 java android android-intent service android-context

我的应用程序从服务接收到一个 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.thisgetApplicationContext() 它不会导致错误。

关于java - 在服务接收器中使用什么来实例化对象的正确上下文是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770692/

相关文章:

java - Spring security + sendRedirect 不起作用

java - gcloud-java。权限_拒绝 : Google Cloud Pub/Sub API (Experimental)

android - 如何使我的全屏覆盖在方向更改后保持全屏?

android - 如何使用 Intent.ACTION_VIEW 查看文件夹的内容?

安卓 Intent : when can the action be null?

Java Android 互联网访问 : WIFI or 3G

java - 包和类路径

java - Try-Catch 的 Catch 部分未执行

android - Dalvik VM 调用问题

android - 图像在 LinearLayout 中最后显示时不显示