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

时间:2014-02-14 04:08:43

标签: java android android-intent service android-context

我的应用程序从服务接收一个意图,然后弹出一个通知。这个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());
         ...
    }
}

有没有人对我能做什么有任何想法?

这些是错误:

new DBManager(this) - > java.lang.ClassCastException:.ReceiveTransitionsIntentService无法强制转换为android.app.Activity

new DBManager(getApplicationContext) - > java.lang.ClassCastException:android.app.Application无法强制转换为android.app.Activity

new DBManager(getBaseContext) - > java.lang.ClassCastException:android.app.Contextimpl无法强制转换为android.app.activity

1 个答案:

答案 0 :(得分:1)

您将获得以下内容:

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() 它不会导致错误。