[英]What's the proper way to use reflection to instantiate objects of unknown classes at runtime?
[英]What's the proper context to use in service receiver to instantiate objects?
我的应用程序从服务接收到意图,然后弹出通知。 这个意图有一个对象ID,我希望从该对象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()
不会导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.