Android 如何将ApplicationContext传递到新线程()中的函数中?
我需要在无限循环中每30秒获取一次关于GPS位置的位置信息,并通过HTTP请求发送到服务器。如果我从服务器得到适当的响应,GPS扫描应该停止,则无休止的循环。该服务称为DataTransferService,gps扫描仪称为GPSTracker,用于此和服务。问题是我无法在新线程(new Runnable())中为GPSTracker获取适当的上下文。 如果创建ThreadHandler,我的MainActivity将冻结。此外,即使我在服务中初始化以便以后使用,上下文也为null 这是我的Android 如何将ApplicationContext传递到新线程()中的函数中?,android,multithreading,asynchronous,android-asynctask,android-context,Android,Multithreading,Asynchronous,Android Asynctask,Android Context,我需要在无限循环中每30秒获取一次关于GPS位置的位置信息,并通过HTTP请求发送到服务器。如果我从服务器得到适当的响应,GPS扫描应该停止,则无休止的循环。该服务称为DataTransferService,gps扫描仪称为GPSTracker,用于此和服务。问题是我无法在新线程(new Runnable())中为GPSTracker获取适当的上下文。 如果创建ThreadHandler,我的MainActivity将冻结。此外,即使我在服务中初始化以便以后使用,上下文也为null 这是我的Da
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();
}
}
这是我的GPSTracker.java,如果您对它感兴趣:
如何将ApplicationContext传递到新线程()中的函数中
您不需要传递应用程序上下文,因为您可以通过
在代码库中定义android应用程序类
只需谷歌“定义应用程序类android示例”
MyApplication.instance.getApplicationContext()
应该是你想要的。(其中实例将是您将定义的单例对象)您是否检查了如果使用
HandlerThread
您的活动将被冻结的原因?您还可以在线程外创建处理程序
,并通过线程内的处理程序发送数据 我曾尝试创建一个独立的MyApplication,它将android.Application类外部化,但这对我没有帮助:我使用了新的AppContext(),gps Langtitdu和Lingtitude与以前一样为零。在before中:如果我将gps跟踪器放在除线程()以外的任何位置,它都可以正常工作。你能给我点别的建议吗?
D/---===> service(7264): com.my.program.MyApplication@40ce3ee0
D/---===> service(7264): StartLocationService() started
D/---===> service(7264): com.my.program.MyApplication@40ce3ee0