在 while(true) 语句中,我创建了一个 Intent ,该 Intent 将在 onHandleIntent 中运行一个案例。但是,如果不将 Activity 类扩展到我的 LocationTracker 类,我无法使用 startService(i) 启动 Intent 。当我执行 LocationTracker 扩展 Activity 时,我可以使用 startService(i) 但应用程序会中断并停止工作。我收到错误“Activity 已泄漏服务连接”。有办法解决这个问题吗?我确实需要的方法在BackgroundService 类中是私有(private)的,并且我的MainScreen 扩展 Activity 使用相同的代码 fragment 来启动服务。我是否同时运行两个 Intent ,如果是的话,有没有办法可以调用其他类中的私有(private)方法?
public class LocationTracker{
DSApi dsApi=new DSApi((ContextWrapper)mContext,null);
if(dsApi.initialize(AppSettings.IP_ADDRESS,AppSettings.PORT,false)) {
interv = (int)dsApi.sendLocationInfo(l);
if (dsApi.needRemoteWipe()) {
while(true){
Intent i = IntentFactory.getBackgroundService();
i.putExtra(BackgroundService.EXTRA_OPERATION,BackgroundService.OPERATION_BACKUP);
startService(i);
AppSettings.addEventLog(EventLog.TYPE_BACKUP, "Data backed up");
break;
}
AppSettings.setRemoteWipe(true);
}
}
Log.d("SendLocationTask", "finished");}
最佳答案
startService()
方法来自 Context
类,看起来您已经引用了一个方法。请尝试以下操作:
mContext.startService(i);
它在 Activity
中没有 Context
的情况下工作的原因是 Activity
扩展了 Context
并获取该方法通过继承。
关于java - 如何不在 MainActivity 上实现 startService(i),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333811/