【问题标题】:How can I pass ApplicationContext into the function in a new Thread()?如何将 ApplicationContext 传递给 new Thread() 中的函数?
【发布时间】:2013-10-29 05:27:29
【问题描述】:

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

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

因为我想在用户按下“停止”按钮时停止无限循环,所以我创建了 bool 变量来指示循环是否应该被计数或停止。

更新: 我添加了一些调试输出(在我的 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

【问题讨论】:

    标签: android multithreading asynchronous android-asynctask android-context


    【解决方案1】:

    您是否检查过如果您使用HandlerThread,您的 Activity 为何会被冻结?您还可以在线程外创建Handler,并通过线程内的处理程序发送数据。

    【讨论】:

      【解决方案2】:

      如何将 ApplicationContext 传递给 new Thread() 中的函数

      您不需要传递应用程序上下文,因为您可以通过以下方式从任何地方访问它 在您的代码库中定义 android Application 类。

      只需google“定义应用程序类android示例”

      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();

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

      【讨论】:

      • 我已经尝试创建一个外接 android.Application 类的单例 MyApplication 但它没有帮助我:我使用了 new AppContext() 并且 gps Langtitdu 和 Lingtitude 像以前一样为零。之前:如果我把它放在除了我的 Thread() 之外的任何地方,我的 gps 跟踪器工作正常。你还能给我什么建议吗?
      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 2011-08-09
      • 2021-06-30
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      相关资源
      最近更新 更多