我需要在无限循环中每30秒获取有关GPS位置的位置信息,并通过HTTP请求发送到服务器。应停止GPS扫描的无限循环如果我从服务器获得适当的响应。服务被称为DataTransferService,gps扫描仪被称为GPSTracker为此和服务。问题是我无法在我的新线程(新的Runnable())中为我的GPSTracker获取适当的上下文。 如果我创建一个ThreadHandler,我的MainActivity将冻结。另外,即使我在服务中初始化以后使用,上下文也是空的。如何将ApplicationContext传递到新线程()中的函数中?
这里是我的DataTransferService.java
public class DataTransferService extends Service {
final static String LOG_TAG = "---===> service";
private boolean isRunning = false;
private GPSTracker gps;
private double lat;
private double lng;
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "onCreate");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
if (!isRunning) {
StartLocationService();
isRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
isRunning = false;
super.onDestroy();
Log.d(LOG_TAG, "onDestroy");
}
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return null;
}
private void StartLocationService(final String login, final String password) {
Thread thread = new Thread(new Runnable() {
public void run() {
Log.d(LOG_TAG, "StartLocationService() started");
while (true) {
//CHECK IF SERVICE IS RUNNING
if (!isRunning) {
stopSelf();
break;
}
//HERE IS THE PROBLEM <----------------
gps = new GPSTracker(getApplicationContext());
//GETTING GPS INFO
if(gps.canGetLocation()){
lat = gps.getLatitude();
lng = gps.getLongitude();
}else{
gps.showSettingsAlert();
}
try {
Log.d(LOG_TAG, String.format("location is: %f; %f", lat, lng));
//i wanted to send HTTP request to the server here with the gps coordinates
} catch (MalformedURLException e) {
e.printStackTrace();
}
//SERVICE DELAY
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
当我想阻止无限循环,当用户按下“停止”这表明,如果周期应该蜜蜂countinued或停止按钮,我创建了布尔变量。
UPDATE: 我加了一些调试输出(我的主题()和里面前),以确定是否getApplicationContext()导致isreally不同,我发现,所有的对象都是平等的。我使用Log.d(LOG_TAG, getApplicationContext().toString());
之前Thread()和Log.d(LOG_TAG, mApplication.getInstance().getApplicationContext().toString());
内部的Thread(),其中mApplication - 是我的单例。 结果:
D/---===> service(7264): [email protected]
D/---===> service(7264): StartLocationService() started
D/---===> service(7264): [email protected]
这是我GPSTracker.java,如果你对它感兴趣:http://pastebin.com/p6e3PGzD
我试过创建一个单例MyApplication,它会给出android.Application类,但它并没有帮助我:我使用了新的AppContext(),而gps Langtitdu和Lingtitude也像之前一样。在之前:我的GPS跟踪工作正常,如果我把它放在任何地方,但我的线程()。你能告诉我其他什么吗? –