我需要从服务中获取对主要 Activity 的引用。
这是我的设计:
MainActivity.java
public class MainActivity extends Activity{
private Intent myIntent;
onCreate(){
myIntent=new Intent(MainActivity.this, MyService.class);
btnStart.setOnClickListener(new OnClickListener(){
public void onClick(View V){
startService(myIntent);
});
}}
MyService.java
class MyService extends Service{
public IBinder onBind(Intent intent) {
return null;
}
onCreate(){
//Here I need to have a MainActivity reference
//to pass it to another object
}
}
我该怎么做?
[编辑]
感谢大家的回答! 这个应用程序是一个网络服务器,目前只适用于线程,我想改用服务,让它在后台也能工作。 问题是我有一个类负责从 Assets 中获取页面,要执行此操作我需要使用此方法:
InputStream iS =myActivity.getAssets().open("www/"+filename);
此时我的项目只有一个Activity,没有任何服务,所以我可以直接从自身传递主Activity的引用:
WebServer ws= new DroidWebServer(8080,this);
那么,为了让这个应用程序与服务一起工作,我应该在我的设计中改变什么?
最佳答案
你没有解释为什么你需要这个。但这绝对是糟糕的设计。存储对 Activity 的引用是您不应该对 Activity 做的第一件事。可以,但是您必须跟踪 Activity 生命周期并在其 onDestroy()
被调用后释放引用。如果您不这样做,就会发生内存泄漏(例如,当配置更改时)。而且,好吧,在 onDestroy()
被调用之后,Activity 被认为是死的并且很可能无论如何都没有用。
所以不要将引用存储在服务中。相反,请描述您需要实现的目标。我确信有更好的选择。
更新
好的,所以您实际上不需要引用 Activity。相反,您需要引用 Context(在您的情况下应该是 ApplicationContext,以便不保留对 Activity 或任何其他组件的引用)。
假设您有一个单独的类来处理 WebService 请求:
class WebService
{
private final Context mContext;
public WebService(Context ctx)
{
//The only context that is safe to keep without tracking its lifetime
//is application context. Activity context and Service context can expire
//and we do not want to keep reference to them and prevent
//GC from recycling the memory.
mContext = ctx.getApplicationContext();
}
public void someFunc(String filename) throws IOException
{
InputStream iS = mContext.getAssets().open("www/"+filename);
}
}
现在您可以从 Service
(推荐用于此类后台任务)甚至从 Activity
(当 web涉及服务调用或长时间的后台任务)。
服务
的例子:
class MyService extends Service
{
WebService mWs;
@Override
public void onCreate()
{
super.onCreate();
mWs = new WebService(this);
//you now can call mWs.someFunc() in separate thread to load data from assets.
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
关于android - 从服务中获取 Activity 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7298375/