Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:如何获取IntentService中调用活动的上下文?_Android_Intentservice - Fatal编程技术网

Android:如何获取IntentService中调用活动的上下文?

Android:如何获取IntentService中调用活动的上下文?,android,intentservice,Android,Intentservice,如果我打电话 Intent intent = new Intent(ReadingActivity.this, AdService.class); startService(intent); 在MyActivity类的onCreate方法中,如何从IntentService类的onhandlecontent()方法中访问MyActivity @Override protected void onHandleIntent(Intent arg0) { // TODO Aut

如果我打电话

Intent intent = new Intent(ReadingActivity.this, AdService.class);
startService(intent);       
MyActivity
类的
onCreate
方法中,如何从
IntentService
类的
onhandlecontent()方法中访问
MyActivity

@Override
protected void onHandleIntent(Intent arg0) {
    // TODO Auto-generated method stub
    ((BookLib) getApplication()).createAd(I need to pass the calling activities context here);
}

在我看来,您似乎正在尝试与您的
活动
服务
进行双向沟通。不要将<代码>意图<代码>发送到您的服务中,而是考虑它。

编辑:回应Commonware的评论:


绑定到
IntentService
的问题在哪里?我已经发布了一些运行良好的应用程序,其中包含绑定的
IntentService
。你没有提供任何证据来支持你的主张

发件人:

服务既可以启动,也可以绑定连接。在里面 在这种情况下,系统将尽可能长时间地保持服务运行 它已启动,或者与它有一个或多个连接
Context.BIND\u AUTO\u CREATE
标志。一旦这两种情况都发生了 按住此键,将调用服务的
onDestroy()
方法,并关闭服务 有效终止。所有清理(停止线程、取消注册) 从
onDestroy()
返回时,接收器)应完整

文档明确表示系统支持同时绑定和启动。在常规
服务上使用
IntentService
不会改变这一点。即使在处理
意图后明确停止服务,只要有东西仍然绑定到它,Android也会让它继续运行

此外,根据OP试图执行的操作,
IntentService
可能不再需要

如何从IntentService类的onHandleIntent方法中访问MyActivity.this

你没有

createAd()
移动到活动中。如果时间是个问题,请使用
AsyncTask
而不是
IntentService


IntentService
主要用于您希望工作与任何活动分离的情况(例如,即使用户离开UI继续做其他事情,文件下载也应继续进行)。

绑定和
IntentService
不能很好地结合在一起。绑定到常规服务没有问题,向
IntentServices
(通过
startService()
)发送命令也没有问题。“绑定到IntentServices的问题在哪里?”--充其量,只有在调用
startService()
之前先绑定才能工作。否则,您将获得竞争条件,其中
onHandleIntent()
在绑定发生之前完成,导致第一个
IntentService
实例被销毁(通过
stopSelf()
)并在第二个实例上发生绑定。嗯,如果你认为你想绑定到一个
IntentService
,你真的应该绑定到一个常规的
服务
,只需要管理你自己的后台线程。谢谢。我想我需要去研究一下,这个答案在这种情况下是一个很好的建议。但是,如果您需要访问上下文(可能是活动的实例),
getApplicationContext()
。我认为,即使是从
IntentService
来看,也有一些情况是有意义的。例如,获取系统服务(例如
context.getSystemService(context.ALARM\u SERVICE);
)。