有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在OnBackpress、onPause或OnResume中停止线程

在这里,我使用location来更新经度和纬度,每当我尝试按下back按钮或app is background或任何实例时,我都希望location\u线程停止运行它。当我切换到当前活动时恢复它

location_thread = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(2000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("TAG",currentThread().getName()+" Running");
                                updateLatLongInfo();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        location_thread.setDaemon(false);
        location_thread.start();
    }

    @Override
//whenever user press a backbutton thread must stoppped
    public void onBackPressed() {
        super.onBackPressed();
        location_thread.stop();
        Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class);
        startActivity(intent);
        finish();
    }


    private void updateLatLongInfo() {
        try {
            int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            latlongInfo.setBackgroundResource(R.drawable.latlng_info);
            GradientDrawable drawable = (GradientDrawable) latlongInfo.getBackground();
            if (locationMode == 0 || locationMode == 1 || locationMode == 2) {
                latlongInfo.setText("Please enable high accuracy in your location settings");
                drawable.setColor(Color.RED);
            } else {
                try {
                    String context = Context.LOCATION_SERVICE;
                    locationManager = (LocationManager) this.getSystemService(context);
                    String provider = LocationManager.GPS_PROVIDER;
                    安卓.location.Location location = locationManager.getLastKnownLocation(provider);
                    updateWithNewLocation(location);
                    locationManager.requestLocationUpdates(provider, 0, 0, locationListener);

                    param_latitude = df.format(lat).toString();
                    param_longitude = df.format(lng).toString();

                    // latlongInfo.setText("Latitude :" + Math.round(lat * 1000000.0) / 1000000.0 + " ," + " Longitude :" + Math.round(lng * 1000000.0) / 1000000.0);
                    latlongInfo.setText("Latitude : " + param_latitude + " ," + " Longitude : " + param_longitude);
                    latlongInfo.setGravity(Gravity.CENTER);
                    drawable.setColor(Color.GREEN);
                } catch (SecurityException e) {
                    Log.e("Error", e.toString());
                }
            }

共 (1) 个答案

  1. # 1 楼答案

    不要使用Thread.stop()方法

    停止线程的最好方法是完成它的工作

    创建volatile变量,比如

    public volatile boolean threadIsStopped;
    

    替换你的

    while (!isInterrupted())
    

    while (!threadIsStopped)
    

    然后把它变成现实

    public void onBackPressed() {
        super.onBackPressed();
        threadIsStopped = true;
        Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class);
        startActivity(intent);
        finish();
    }  
    

    因为你的背压开始了另一项活动并完成了当前的任务,所以最好是这样做:

    @Override
    protected void onResume() {
        super.onResume();
        threadIsStopped = false;
        //start thread here
    } 
    
    @Override
    protected void onPause() {
        super.onResume();
        threadIsStopped = true;
    } 
    

    所以s no need to stop thread in根本就没有人反对

    请注意,在设置threadIsStopped之后,线程可能会停止

    关于恢复线程-在您的情况下,您只需创建新线程并启动它

    还请注意,如果更改设备的方向,将再次调用onPauseonResume。这就是为什么强烈建议使用IntentService来做这些事情的原因