如何将应用程序上下文传递到新 Thread() 中的函数中



我需要在无限循环中每30秒获取一次有关GPS位置的位置信息,并通过HTTP请求发送到服务器。如果应该停止GPS扫描,则无休止的循环 如果我从服务器得到适当的响应。服务称为数据传输服务,GPS扫描仪称为GPSTracker,用于此和服务。问题是我无法在我的新线程(新 Runnable())中获得我的 GPSTracker 的正确上下文。如果我创建一个线程处理程序,我的主活动将冻结。此外,即使我在服务中初始化以供以后使用,上下文也是 null。

这是我的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();
}
}

由于我想在用户按下"停止"按钮时停止无限循环,因此我创建了布尔变量,该变量指示循环是否应该计数或停止。

更新:我添加了一些调试输出(在我的 Thread() 之前和里面)来确定 getApplicationContext() 结果是否真的不同,我发现所有对象都是相等的。我在 Thread() 之前使用了 Log.d(LOG_TAG, getApplicationContext().toString());,在 Thread() 中使用了Log.d(LOG_TAG, mApplication.getInstance().getApplicationContext().toString());,其中 mApplication - 是我的单例。结果:

D/---===> service(7264): com.my.program.MyApplication@40ce3ee0
D/---===> service(7264): StartLocationService() started
D/---===> service(7264): com.my.program.MyApplication@40ce3ee0

这是我的GPSTracker.java如果你对它感兴趣的话:http://pastebin.com/p6e3PGzD

您是否检查过为什么如果您使用HandlerThread您的活动将被冻结?您还可以从线程中创建Handler,并通过线程中的处理程序发送数据。

如何将应用程序上下文传递到新线程()中的函数中

您无需传递应用程序上下文,因为您可以通过以下位置从任何地方访问它 在代码库中定义安卓应用程序类。

只是谷歌"定义应用程序类安卓示例"

http://developer.android.com/reference/android/app/Application.html

http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

MyApplication.instance.getApplicationContext();

应该是你想要的。(其中实例将是您将定义的单例对象)

最新更新