我正在尝试创建一个即使我的应用程序关闭也能运行的服务.但是,我需要在此服务中使用我的应用上下文.当应用程序运行时,该服务也可以正常工作,但是当我关闭应用程序(调用onDestroy())时,getContext()始终返回null.
服务
public class SubscribeService extends Service { private Context context; @OverrIDe public IBinder onBind(Intent intent) { return null; } @OverrIDe public voID onCreate() { super.onCreate(); context = this; //Returns null when service is running on background context = MyApp.getContext(); //Also null } @OverrIDe public int onStartCommand(Intent intent, int flags, int startID) { //do stuff using context }
MyApp的
public class MyApp extends Application { private static Context context; public static Context getContext() { return context.getApplicationContext(); } @OverrIDe public voID onCreate() { context = getApplicationContext(); super.onCreate(); }}
服务从Activity onCreate()开始
startService(new Intent(this, SubscribeService.class));
在这种情况下我应该如何使用Context?
编辑
在Onik的帮助下管理以使其正常工作.
我只需要调用MyApp.getContext();在super.onCreate()之前;
像这样:
@OverrIDepublic voID onCreate() { context = MyApp.getContext(); super.onCreate();}
解决方法:
Service扩展为Context.您可以使用它,这是对Service实例的引用.
关于以下SubscribeService类的代码,请在下面的评论中提供更多详细信息:
@OverrIDepublic voID onCreate() { super.onCreate(); context = this; context = MyApp.getContext();}
在您的服务的onCreate()上下文中=基本编程范例不能为空.另一方面,context = MyApp.getContext()可以为null,但很可能是因为此代码行位于MyApp类中的super.onCreate()之后:
@OverrIDepublic voID onCreate() { context = getApplicationContext(); super.onCreate();}
替换最后两行的顺序.
总结以上是内存溢出为你收集整理的java – 后台服务上的Android getContext全部内容,希望文章能够帮你解决java – 后台服务上的Android getContext所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)