2014-09-12 4 views
0

Я новичок в программировании android, и у меня есть две проблемы в классе AsyncTask с именем RetrieveTokenTask(), в этом классе я получаю токен для доступа к учетной записи электронной почты в gmail, когда я вызываю Класс AsyncTask создает бесконечный цикл, и сообщение для апробации открыто и закрыто для приложения.У меня есть проблема с классом AsyncTask

Другая проблема заключается в том, когда я нажимаю кнопку отменить доступ к данным, когда повторите попытку входа в приложение, не покажите макет с данными.

Я сделал это после некоторых уроков.

Любая помощь поможет.

Спасибо и прошу прощения за любую ошибку в моем письме, но мой английский не очень хорош.

Этот код мили приложения является следующим:

`protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

` ...

//Initializing google plus api client 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
    .addConnectionCallbacks(this) 
    .addOnConnectionFailedListener(this).addApi(Plus.API) 
    .addScope(Plus.SCOPE_PLUS_LOGIN).build(); 

} 

protected void onStart(){ 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 

protected void onStop(){ 
    super.onStop(); 
    if(mGoogleApiClient.isConnected()){ 
     mGoogleApiClient.disconnect(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onClick(View v) { 
    switch(v.getId()){ 
    case R.id.btn_sign_in: 
     signInWithGplus(); 
     break; 
    case R.id.btn_sign_out: 
     signOutFromGplus(); 
     break; 
    case R.id.btn_revoke_access: 
     revokeGplusAccess(); 
     break; 
    } 
} 

@Override 
public void onConnectionFailed(ConnectionResult result) { 
    if(!result.hasResolution()){ 
     GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 
       0).show(); 
     return; 
    } 

    if(!mIntentInProgress){ 
     //Store the connection for later usage 
     mConnectionResult = result; 

     if(mSignInClicked){ 
      // The user has already clicked 'sign-in' so we attempt to 
      // resolve all 
      // errors until the user is signed in, or they cancel. 
      resolveSignInError(); 
     } 
    } 

} 

@Override 
public void onConnected(Bundle arg0) { 
    mSignInClicked = false; 
    Toast.makeText(this, "User is connected", Toast.LENGTH_LONG).show(); 

    // Get User's information 
    getProfileInformation(); 

    // Update the UI after sign-in 
    updateUI(true);  
} 

@Override 
public void onConnectionSuspended(int arg0) { 
    mGoogleApiClient.connect(); 
    updateUI(false); 
} 

private void updateUI(boolean isSignedIn){ 
    if(isSignedIn){ 
     btnSignIn.setVisibility(View.GONE); 
     btnSignOut.setVisibility(View.VISIBLE); 
     btnRevokeAccess.setVisibility(View.VISIBLE); 
     llProfileLayout.setVisibility(View.VISIBLE); 
    } 
    else { 
     btnSignIn.setVisibility(View.VISIBLE); 
     btnSignOut.setVisibility(View.GONE); 
     btnRevokeAccess.setVisibility(View.GONE); 
     llProfileLayout.setVisibility(View.GONE); 
    } 
} 

/* 
* Sign-in into google 
*/ 
private void signInWithGplus(){ 
    if(!mGoogleApiClient.isConnecting()){ 
     mSignInClicked = true; 
     resolveSignInError(); 
    } 
} 

/* 
* Method to resolve any sign-in errors 
*/ 
private void resolveSignInError(){ 
    if(mConnectionResult.hasResolution()){ 
     try{ 
      mIntentInProgress = true; 
      mConnectionResult.startResolutionForResult(this, RC_SIGN_IN); 
     } 
     catch(SendIntentException e){ 
      mIntentInProgress = false; 
      mGoogleApiClient.connect(); 
     } 
    } 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == RC_SIGN_IN) { 
     mIntentInProgress = false; 
     if (resultCode == RESULT_OK) { 
      // Make sure the app is not already connected or attempting to connect 
      if (!mGoogleApiClient.isConnecting() && 
        !mGoogleApiClient.isConnected()) { 
       mGoogleApiClient.connect(); 
      } 
     } 
    } 
} 

/* 
* User's information name, email, profile pic 
*/ 
private void getProfileInformation(){ 
    try{ 
     if(Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null){ 
      Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); 

      String personName = currentPerson.getDisplayName(); 
      String perosnPhotoUrl = currentPerson.getImage().getUrl(); 
      String personGooglePlusProfile = currentPerson.getUrl(); 
      String email = Plus.AccountApi.getAccountName(mGoogleApiClient); 

      Log.e(TAG, "Name: " + personName + ", plusProfile: " 
        + personGooglePlusProfile + ", email: " + email 
        + ", Image: " + perosnPhotoUrl); 

      txtName.setText(personName); 
      txtEmail.setText(email); 
      perosnPhotoUrl = perosnPhotoUrl.substring(0, 
        perosnPhotoUrl.length() - 2) 
        + PROFILE_PIC_SIZE; 

      new LoadProfileImage(imgProfilePic).execute(perosnPhotoUrl); 

      new RetrieveTokenTask(txtToken).execute(email); 
     } 
     else{ 
      Toast.makeText(getApplicationContext(), 
        "Person informations is null", Toast.LENGTH_LONG).show(); 
     } 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 

/* 
* Background Async task to load user profile picture from url 
*/ 
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap>{ 
    ImageView bmImage; 

    public LoadProfileImage(ImageView bmImage){ 
     this.bmImage = bmImage; 
    } 

    @Override 
    protected Bitmap doInBackground(String... urls) { 
     String urldisplay = urls[0]; 
     Bitmap mIcon11 = null; 

     try{ 
      InputStream in = new java.net.URL(urldisplay).openStream(); 
      mIcon11 = BitmapFactory.decodeStream(in); 
     } 
     catch(Exception e){ 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return mIcon11; 
    } 

    protected void onPostExecute(Bitmap result){ 
     bmImage.setImageBitmap(result); 
    } 
} 

/* 
* Sign-out from google 
*/ 
private void signOutFromGplus(){ 
    if(mGoogleApiClient.isConnected()){ 
     Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); 
     mGoogleApiClient.disconnect(); 
     mGoogleApiClient.connect(); 
     updateUI(false); 
    } 
} 

/* 
* Revoking access from google 
*/ 
private void revokeGplusAccess(){ 
    if(mGoogleApiClient.isConnected()){ 
     Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); 
     Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient) 
      .setResultCallback(new ResultCallback<Status>() { 

       @Override 
       public void onResult(Status arg0) { 
        Log.e(TAG, "User acces revoked!"); 
        mGoogleApiClient.connect(); 
        updateUI(false); 
       } 
      }); 
    } 
} 

private class RetrieveTokenTask extends AsyncTask<String, Void, String> { 
    TextViewTkn Tkn; 

    private RetrieveTokenTask(TextView tkn){ 
     this.Tkn = tkn; 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     String accountName = params[0]; 
     String scopes = "oauth2:https://www.googleapis.com/auth/gmail.compose"; 
     String token = null; 
     try { 
      token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes); 
     } catch (IOException e) { 
      Log.e(TAGTKN, e.getMessage()); 
     } catch (UserRecoverableAuthException e) { 
      startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED); 
     } catch (GoogleAuthException e) { 
      Log.e(TAGTKN, e.getMessage()); 
     } 
     return token; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     txtToken.setText(result); 
    } 
} 

ответ

0

Для вашего второго вопроса, AsyncTask не работает более чем один раз. Если вы пытаетесь повторно выполнить экземпляр, он не будет запущен. Вы должны создать новый экземпляр AsyncTask каждый раз, когда хотите выполнить.

Лучше установить точку останова в методе doBackground и проверить его.

Смежные вопросы