Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android-第二次使用后禁用按钮_Android_User Interface_Handler_Runnable_Updating - Fatal编程技术网

Android-第二次使用后禁用按钮

Android-第二次使用后禁用按钮,android,user-interface,handler,runnable,updating,Android,User Interface,Handler,Runnable,Updating,我很难找到一个错误,显然我应该在某个地方。可能是我不知道的逻辑错误 我有一个按钮,点击后启动locationManager定位我的位置。在扫描我的位置时,我希望禁用我的按钮。我设法做到了(耶),不过在第一次检索位置并第二次单击按钮之后,为了第二次接收位置,按钮不再被禁用。这使我能够多次点击该按钮,启动越来越多的locationListeners侦听位置。这正是我试图通过在扫描时禁用按钮来阻止的 这是我的密码。解释如下 主要活动: public class MainActivity extends

我很难找到一个错误,显然我应该在某个地方。可能是我不知道的逻辑错误

我有一个按钮,点击后启动locationManager定位我的位置。在扫描我的位置时,我希望禁用我的按钮。我设法做到了(耶),不过在第一次检索位置并第二次单击按钮之后,为了第二次接收位置,按钮不再被禁用。这使我能够多次点击该按钮,启动越来越多的locationListeners侦听位置。这正是我试图通过在扫描时禁用按钮来阻止的

这是我的密码。解释如下

主要活动:

public class MainActivity extends FragmentActivity {

// Setting layout dependent variables
...
private Button btn_scan;

// Setting several variables
...

// Setting default values
...

private boolean locationReceived = false;
private boolean gsmReceived = false;
private boolean isBusy = false;

private int counter = 0;
private Handler handler;
private Runnable runnable = new Runnable() {

    public void run() {

        counter ++;
        handler.postDelayed(runnable, 1000);

        if (locationReceived && gsmReceived) {

            // SAVE DATA TO DB HERE! //
            displayInformation();
            handler.removeCallbacks(runnable);

        } else if (counter >= (TIME_TO_WAIT_FOR_RESPONSE+1)) {

            displayInformation();
            handler.removeCallbacks(runnable);

        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Application context
    context = getApplicationContext();

    // Handler
    handler = new Handler();

    // initializing layout dependent variables
    ...
    btn_scan = (Button) findViewById(R.id.btn_scan);

    // Initialize GoogleMap
    ...

    // Get the LocationManager for checking, if providers are enabled
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    // Get the PhoneStateListener and telephony service to receive the signal strength
    myListener = new MyPhoneStateListener();
    tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    // Ask for the current location in here.
    locationResult = new LocationResult() {

        @Override
        public void gotLocation(final Location location) {

            // If location given, do something with it. If not, return some message.
            if (location != null) {

                updateGeoData(location);

            }

        }
    };

    btn_scan.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            if (!isBusy) {
                toogleButton();

                // if GPS is enabled in phone settings
                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

                    postGPSAlert();
                    toogleButton();

                } else {

                    // If GPS enabled, get info
                    getInformation();
                }
            }
        }
    });
}

/*
 * wrapper method for getting informations
 */
private void getInformation() {

    // start informationfetcher. 
    runnable.run();
    // get geo location, longitude & latitude
    getGeoLocation();
    // get signal strength and its' other parameters
    getSignalStrength();
    // get internet connectivity quality string
    getConnectivityQuality();
    // get internet connectivity type
    getConnectivityType();
}

/*
 * get signal strength. only starts the listener, which does the rest of the job.
 */
public void getSignalStrength() {

    tel.listen(myListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}

/*
 * get connectivity type and update the variable internetType
 */
private void getConnectivityType() {

   ... nothing important
}

/*
 * Gets internet quality string
 */
private void getConnectivityQuality() {

    ... nothing important
}

/*
 * Gets the geo location
 */
public void getGeoLocation() {

    MyLocation myLocation = new MyLocation(context, TIME_TO_WAIT_FOR_RESPONSE);
    if (!myLocation.getLocation(locationResult)) {
        String message = "To make use of localization, please enable GPS or mobile networking.";
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }
}

/*
 * Updates retrieved GeoData
 */
private void updateGeoData(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();    
    locationReceived = true;
}

/*
 * Updates GUI with all received values
 */
private void displayInformation() {

    ... only updating textViews here

    if (gsmReceived) {

        ... only updating textViews here

    }

    if (locationReceived) {

        ... only updating textViews here and moving googleMapCamera to some spot

    } 

    // Post Error messages, if location and/or GSM could not be obtained.
    ... just Toasting some error messages, if no signal or GPS received.

    toogleButton();
}

/*
 * Posts an alert saying u gotta enable GPS
 */
private void postGPSAlert() {
    // Prompt alert
    AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

    // Title and message values
    alert.setTitle(getString(R.string.prompt_titleProviderFail));
    alert.setMessage(getString(R.string.prompt_messageProviderFail));

    // If OK was clicked, redirect to settings to enable GPS
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {

            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    });

    // If ABORT was clicked, redirect back to activity
    alert.setNegativeButton("Abort", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {

            // Canceled.
        }
    });

    // Show dialog
    alert.show();
}

/*
 * Method for disabling and enabling the button on pressure/update
 */
private void toogleButton() {

    if (btn_scan.isEnabled()) {

        isBusy = true;
        btn_scan.setText("SCANNING ...");
        btn_scan.setEnabled(false);
    } else if (!btn_scan.isEnabled()) {

        isBusy = false;
        btn_scan.setText("SCAN");
        btn_scan.setEnabled(true);
    }
}

/*
 * (non-Javadoc)
 * Listener, to listen on signalStrength of your phone. It'll set all the variables declared above and update the info you'll see.
 */
private class MyPhoneStateListener extends PhoneStateListener {

    @Override
    public void onSignalStrengthsChanged(SignalStrength signalStrength) {

        super.onSignalStrengthsChanged(signalStrength);

        ... just updating some String variables here

        gsmReceived = true;

        tel.listen(myListener, PhoneStateListener.LISTEN_NONE);
    }
}  

}
现在来解释一下: 单击按钮后,我将检查是否已在运行操作,并通过方法toogleButton()禁用该按钮。因此,触发了几种方法来收集有关网络、信号强度和我的位置的信息。收集我的位置通常需要大部分时间,但这并不重要。如果收集了所有信息,我将使用handler+runnable每秒检查60秒。如果是这样,我将通过用户界面上的displayInformation()显示所有信息,并通过toogleButton()再次启用按钮。另外,我正在设置变量isBusy=true。如果我没有收集所有信息并且60秒过去了,我仍然会显示所有(直到那时)收集的信息并再次按下按钮(到启用状态)

所有这些都很好,这是第一次。当我在收到所有信息后第二次按下该按钮时,该按钮不再被禁用,尽管该应用程序仍按其应有的方式收集信息。这里唯一的问题是,我现在可以多次按下按钮并启动多个请求来收集信息。那不是我想要的。我要一个接一个


你知道我做错了什么吗?

使用Asynctask线程-在onPreExecute中禁用按钮,在doInBackground()中写入位置搜索代码OnPostExecute中启用按钮

您的代码有点乱。您不应该在toggleButton方法中更改isBusy字段。移除这些部件,并将它们放在您知道定位过程开始和结束的位置。我认为Button.isEnabled()和isBusy之间发生冲突,这是逻辑错误。

好的,也是第一次工作。尽管我不能第二次或第三次重用asynctask。现在是使用服务的时候了,不是吗?Nvm,让它开始工作。对于那些想知道如何将我的代码移植到某个AsyncTask中并在按钮上启动的人,请单击:new MyAsynctask().execute();这样,您就可以创建MyAsyncTask()的匿名实例,并可以反复运行“相同”操作