Well i have created a Google+ Signin successfully.
And i'm trying to signout the g+ from the other activity.
I tried the below code it's not working as per my expectation.
what I wanted is the app signin from LoginActivity & signout from MainActivity.
Below is my LoginActivity Code.
import java.util.ArrayList;
import java.util.List;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
//import android.app.LoaderManager.LoaderCallbacks;
//import android.content.CursorLoader;
//import android.content.Loader;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends FragmentActivity implements LoaderCallbacks<Cursor>, OnClickListener, com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener {
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
public static GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress;
/* Track whether the sign-in button has been clicked so that we know to resolve
* all issues preventing sign-in without waiting.
*/
private boolean mSignInClicked;
/* Store the connection result from onConnectionFailed callbacks so that we can
* resolve them when the user clicks sign-in.
*/
private ConnectionResult mConnectionResult;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[] {
"foo#example.com:hello", "bar#example.com:world" };
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mGoogleApiClient.connect();
}
/*
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
*/
public void disconnect(){
if (mGoogleApiClient.isConnected()) {
Log.e("LoginActivity()","before signout" + mGoogleApiClient.isConnected());
mGoogleApiClient.disconnect();
Log.e("LoginActivity()","after signout" + mGoogleApiClient.isConnected());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
/* Button signin = (Button)findViewById(R.id.sign_in_button);
signin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInErrors();
}
}
}); */
findViewById(R.id.sign_in_button).setOnClickListener(this);
Button signout = (Button)findViewById(R.id.signout_in_button);
signout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("LoginActivity()","before signout" + mGoogleApiClient.isConnected());
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
Log.e("LoginActivity()","After signout" + mGoogleApiClient.isConnected());
}
});
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
//result.getResolution().getIntentSender()
/* A helper method to resolve the current ConnectionResult error. */
private void resolveSignInError() {
// if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution().getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
// }
}
private void populateAutoComplete() {
if (VERSION.SDK_INT >= 14) {
// Use ContactsContract.Profile (API 14+)
//getLoaderManager().initLoader(0, null, this);
getSupportLoaderManager().initLoader(0, null, this);
} else if (VERSION.SDK_INT >= 8) {
// Use AccountManager (API 8+)
new SetupEmailAutoCompleteTask().execute(null, null);
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
// TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isPasswordValid(String password) {
// TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE },
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY, };
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Use an AsyncTask to fetch the user's email addresses on a background
* thread, and update the email text field with results on the main UI
* thread.
*/
class SetupEmailAutoCompleteTask extends
AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... voids) {
ArrayList<String> emailAddressCollection = new ArrayList<String>();
// Get all emails from the user's contacts and copy them to a list.
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null, null, null);
while (emailCur.moveToNext()) {
String email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailAddressCollection.add(email);
}
emailCur.close();
return emailAddressCollection;
}
#Override
protected void onPostExecute(List<String> emailAddressCollection) {
addEmailsToAutoComplete(emailAddressCollection);
}
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
// Create adapter to tell the AutoCompleteTextView what to show in its
// dropdown list.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
LoginActivity.this,
android.R.layout.simple_dropdown_item_1line,
emailAddressCollection);
mEmailView.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (!mIntentInProgress) {
// Store the ConnectionResult so that we can use it later when the user clicks
// 'sign-in'.
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
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
//TODO Auto-generated method stub
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
Log.e("LoginActivity()","onconnected status :" + mGoogleApiClient.isConnected());
Intent i = new Intent(this,MainActivity.class);
LoginActivity.this.startActivity(i);
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
}
And Layout for this activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.dotncube.gmailtest.LoginActivity" >
<!-- Login progress -->
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="#+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in"
android:textStyle="bold" />
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/signout_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Signout from google"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
And in MainActivity I'm calling signout function of LoginActivity.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void signout(View v){
LoginActivity obj = new LoginActivity();
obj.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);
}
}
What does "sign out" mean to you? Should the user expect to re-select their account? Or do you want to completely deauthorize your app so the next time they use it they'll see the account picker and sign-in dialog?
If you just want them to see the account picker next time, call Plus.AccountApi.clearDefaultAccount(...). If you want your app deauthorized, call Plus.AccountApi.revokeAccessAndDisconnect(...) and wait for the response.
https://developer.android.com/reference/com/google/android/gms/plus/Account.html
Related
I am writing an Android app to fetch the latest email from a folder and play it using TTS. I want to be able to use it whilst driving so it has to be mostly automatic. Everything so far is working fine until I attempt to capture when the TextToSpeech has finished speaking so we can move on to the next email.
Here is the complete MainActivity.java file:
package uk.co.letsdelight.emailreader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
public TextToSpeech tts;
private Bundle ttsParam = new Bundle();
public UtteranceProgressListener utListener;
private boolean isPlaying = false;
private Properties imap = new Properties();
private String textToSpeak = "";
#Override
public void onInit(int ttsStatus) {
if (ttsStatus == TextToSpeech.SUCCESS) {
utListener = new UtteranceProgressListener() {
#Override
public void onStart(String s) {
TextView status = findViewById(R.id.status);
status.setText("started reading (Listener)");
}
#Override
public void onDone(String s) {
Toast.makeText(getApplicationContext(), "Done Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("finished reading (Listener)");
/*ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);*/
isPlaying = false;
}
#Override
public void onStop(String s, boolean b) {
Toast.makeText(getApplicationContext(), "Stop Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("stopped reading (Listener)");
/*ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);*/
isPlaying = false;
}
#Override
public void onError(String s) {
Toast.makeText(getApplicationContext(), "Error Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("Error reading email");
ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);
isPlaying = false;
}
};
tts.setOnUtteranceProgressListener(utListener);
TextView status = findViewById(R.id.status);
status.setText("initialised");
} else {
TextView status = findViewById(R.id.status);
status.setText("failed to initialise");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imap.setProperty("mail.store.protocol", "imap");
imap.setProperty("mail.imaps.port", "143");
tts = new TextToSpeech(this,this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void restartPressed(View v) {
if (isPlaying) {
tts.stop();
speak();
}
}
public void playPressed(View v) {
ImageButton i = (ImageButton) v;
if (isPlaying) {
isPlaying = false;
i.setImageResource(R.drawable.button_play);
TextView status = findViewById(R.id.status);
status.setText("");
if (tts != null) {
tts.stop();
}
} else {
isPlaying = true;
i.setImageResource(R.drawable.button_stop);
new Reader().execute();
}
}
class Reader extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
TextView status = findViewById(R.id.status);
status.setText("fetching email");
}
#Override
protected String doInBackground(String... params) {
String toRead = "nothing to fetch";
try {
Session session = Session.getDefaultInstance(imap, null);
Store store = session.getStore();
store.connect(getText(R.string.hostname).toString(), getText(R.string.username).toString(), getText(R.string.password).toString());
Folder inbox = store.getFolder("INBOX.Articles.listen");
if (inbox.exists() && inbox.getMessageCount() > 0) {
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount() - 6);
if (msg.getContentType().contains("multipart")) {
Multipart multiPart = (Multipart) msg.getContent();
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(multiPart.getCount() - 1);
toRead = part.getContent().toString();
} else {
toRead = msg.getContent().toString();
}
} else {
toRead = "The folder is empty or doesn't exist";
}
} catch (Throwable ex) {
toRead = "Error fetching email - " + ex.toString();
}
return toRead;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String body;
TextView status = findViewById(R.id.status);
status.setText("");
try {
Document doc = Jsoup.parse(s);
body = doc.body().text();
} catch (Throwable ex) {
body = "Error parsing email - " + ex.toString();
}
status.setText("email successfully fetched");
textToSpeak = body;
if (isPlaying) {
speak();
}
}
}
private void speak() {
int maxLength = TextToSpeech.getMaxSpeechInputLength();
if (textToSpeak.length() > maxLength) {
textToSpeak = "The email text is too long! The maximum length is " + maxLength + " characters";
}
ttsParam.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "EmailReader");
tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, ttsParam, "EmailReader");
}
#Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
The inner class Reader works fine. doInBackground fetches the email and onPostExec strips out any HTML to leave the actual text content of the email. This is passed to the speak() method which does the actual speaking and works.
The issue is with the onUtteranceProgressListener.
Sometimes the onStart(String s) method is called, sometimes it isn't! It seems to never be called the first time the email read out. Mostly it is called for subsequent calls to speak() but not always. About 1 in 5 times it fails to get called. If the listener is called the status displays 'started reading (Listener)' otherwise it shows 'email successfully fetched'.
onDone, onError and onStop are never called.
I have tried using different utteranceID and Bundle values in the tts.speak() call but this makes to difference.
When the app is started, the first status display is 'initialised' which means that the onUtteranceListener must have been set within the onInit method. The TextToSpeech object is instantiated within the activity's onCreate method.
I have looked through all the information I can find which has mostly suggested getting the utteranceID correct. What else can I try in order to get a better understanding of this problem please?
The problem is that the onDone() method (and in fact any of the progress callbacks) is run on a background thread, and therefore the Toast is not going to work, and any code that accesses your UI such as setText(...) may or may not work.
So... the methods probably are being called, but you just can't see that.
The solution to this would be to surround the code in your callbacks with runOnUiThread() like this:
#Override
public void onDone(String s) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Done Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("finished reading (Listener)");
/*ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);*/
isPlaying = false;
}
});
}
Note: It's probably best to initialize your TextView in onCreate() along with everything else instead of in the progress callbacks.
Also, the purpose of the utteranceID is to give each call to speak() a unique identifier that is then passed back to you as the "String s" argument in the progress callbacks.
It's a good idea to give each call to speak a new ("most recent") ID using some kind of random number generator, and then checking it in the progress callbacks.
You can see a similar question and answer regarding this here.
Side note:
Since you have a "restart" button, you should know that on APIs <23, calls to TextToSpeech.stop() will cause the onDone() in your progress listener to be called. On APIs 23+, it calls onStop() instead.
First, make sure you actually have a problem and not a race between who sets the text in what order. Use log statements to make sure it is not actually called.
Try setting queueMode to QUEUE_ADD like:
tts.speak(textToSpeak, TextToSpeech.QUEUE_ADD, ttsParam, "EmailReader");
maybe subsequent calls are cancelling the listener's events from previous texts inputs, as QUEUE_FLUSH suggests.
Also the bundle isn't really needed there, you can set it to null.
Hope any of these helps.
When I'm trying to use other RFID SDK to get Tag Code. And send to the server to fetch the tag information. But I only can get the RFID SDK demon working. So I just try to add HTTP request method into the demon. but I always get an error about I'm calling a null object reference. when I use
IAcitivity.IMakeHttpCall();
Inventory Activity
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.uk.tsl.rfid.ModelBase;
import com.uk.tsl.rfid.TSLBluetoothDeviceActivity;
import com.uk.tsl.rfid.WeakHandler;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import com.uk.tsl.rfid.asciiprotocol.DeviceProperties;
import com.uk.tsl.rfid.asciiprotocol.commands.FactoryDefaultsCommand;
import com.uk.tsl.rfid.asciiprotocol.enumerations.QuerySession;
import com.uk.tsl.rfid.asciiprotocol.enumerations.TriState;
import com.uk.tsl.rfid.asciiprotocol.parameters.AntennaParameters;
import com.uk.tsl.rfid.asciiprotocol.responders.LoggerResponder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InventoryActivity extends TSLBluetoothDeviceActivity {
// Debug control
private static final boolean D = BuildConfig.DEBUG;
private RequestQueue mVolleyQueue;
// OkHttpClient httpClient = new OkHttpClient();
// The list of results from actions
private ArrayAdapter<String> mResultsArrayAdapter;
private ListView mResultsListView;
private ArrayAdapter<String> mBarcodeResultsArrayAdapter;
private ListView mBarcodeResultsListView;
// The text view to display the RF Output Power used in RFID commands
private TextView mPowerLevelTextView;
// The seek bar used to adjust the RF Output Power for RFID commands
private SeekBar mPowerSeekBar;
// The current setting of the power level
private int mPowerLevel = AntennaParameters.MaximumCarrierPower;
// Error report
private TextView mResultTextView;
// Custom adapter for the session values to display the description rather than the toString() value
public class SessionArrayAdapter extends ArrayAdapter<QuerySession> {
private final QuerySession[] mValues;
public SessionArrayAdapter(Context context, int textViewResourceId, QuerySession[] objects) {
super(context, textViewResourceId, objects);
mValues = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getView(position, convertView, parent);
view.setText(mValues[position].getDescription());
return view;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getDropDownView(position, convertView, parent);
view.setText(mValues[position].getDescription());
return view;
}
}
// The session
private QuerySession[] mSessions = new QuerySession[] {
QuerySession.SESSION_0,
QuerySession.SESSION_1,
QuerySession.SESSION_2,
QuerySession.SESSION_3
};
// The list of sessions that can be selected
private SessionArrayAdapter mSessionArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
mVolleyQueue = Volley.newRequestQueue(this);
mResultsArrayAdapter = new ArrayAdapter<String>(this,R.layout.result_item);
mBarcodeResultsArrayAdapter = new ArrayAdapter<String>(this,R.layout.result_item);
mResultTextView = (TextView)findViewById(R.id.resultTextView);
// Find and set up the results ListView
mResultsListView = (ListView) findViewById(R.id.resultListView);
mResultsListView.setAdapter(mResultsArrayAdapter);
mResultsListView.setFastScrollEnabled(true);
mBarcodeResultsListView = (ListView) findViewById(R.id.barcodeListView);
mBarcodeResultsListView.setAdapter(mBarcodeResultsArrayAdapter);
mBarcodeResultsListView.setFastScrollEnabled(true);
// Hook up the button actions
Button sButton = (Button)findViewById(R.id.扫描开始);
sButton.setOnClickListener(mScanButtonListener);
Button cButton = (Button)findViewById(R.id.清除按钮);
cButton.setOnClickListener(mClearButtonListener);
// The SeekBar provides an integer value for the antenna power
mPowerLevelTextView = (TextView)findViewById(R.id.powerTextView);
mPowerSeekBar = (SeekBar)findViewById(R.id.powerSeekBar);
mPowerSeekBar.setOnSeekBarChangeListener(mPowerSeekBarListener);
// Set the seek bar current value to maximum and to cover the range of the power settings
setPowerBarLimits();
mSessionArrayAdapter = new SessionArrayAdapter(this, android.R.layout.simple_spinner_item, mSessions);
// Find and set up the sessions spinner
Spinner spinner = (Spinner) findViewById(R.id.sessionSpinner);
mSessionArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mSessionArrayAdapter);
spinner.setOnItemSelectedListener(mActionSelectedListener);
spinner.setSelection(0);
// Set up Fast Id check box listener
CheckBox cb = (CheckBox)findViewById(R.id.fastIdCheckBox);
cb.setOnClickListener(mFastIdCheckBoxListener);
//
// An AsciiCommander has been created by the base class
//
AsciiCommander commander = getCommander();
// Add the LoggerResponder - this simply echoes all lines received from the reader to the log
// and passes the line onto the next responder
// This is added first so that no other responder can consume received lines before they are logged.
commander.addResponder(new LoggerResponder());
// Add a synchronous responder to handle synchronous commands
commander.addSynchronousResponder();
//Create a (custom) model and configure its commander and handler
mModel = new InventoryModel();
mModel.setCommander(getCommander());
mModel.setHandler(mGenericModelHandler);
}
#Override
public synchronized void onPause() {
super.onPause();
mModel.setEnabled(false);
// Unregister to receive notifications from the AsciiCommander
LocalBroadcastManager.getInstance(this).unregisterReceiver(mCommanderMessageReceiver);
}
#Override
public synchronized void onResume() {
super.onResume();
mModel.setEnabled(true);
// Register to receive notifications from the AsciiCommander
LocalBroadcastManager.getInstance(this).registerReceiver(mCommanderMessageReceiver,
new IntentFilter(AsciiCommander.STATE_CHANGED_NOTIFICATION));
displayReaderState();
UpdateUI();
}
//----------------------------------------------------------------------------------------------
// Menu
//----------------------------------------------------------------------------------------------
private MenuItem mReconnectMenuItem;
private MenuItem mConnectMenuItem;
private MenuItem mDisconnectMenuItem;
private MenuItem mResetMenuItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reader_menu, menu);
mResetMenuItem = menu.findItem(R.id.reset_reader_menu_item);
mReconnectMenuItem = menu.findItem(R.id.reconnect_reader_menu_item);
mConnectMenuItem = menu.findItem(R.id.insecure_connect_reader_menu_item);
mDisconnectMenuItem= menu.findItem(R.id.disconnect_reader_menu_item);
return true;
}
/**
* Prepare the menu options
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean isConnecting = getCommander().getConnectionState() == AsciiCommander.ConnectionState.CONNECTING;
boolean isConnected = getCommander().isConnected();
mResetMenuItem.setEnabled(isConnected);
mDisconnectMenuItem.setEnabled(isConnected);
mReconnectMenuItem.setEnabled(!(isConnecting || isConnected));
mConnectMenuItem.setEnabled(!(isConnecting || isConnected));
return super.onPrepareOptionsMenu(menu);
}
/**
* Respond to menu item selections
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reconnect_reader_menu_item:
Toast.makeText(this.getApplicationContext(), "重新连接中...", Toast.LENGTH_LONG).show();
reconnectDevice();
UpdateUI();
return true;
case R.id.insecure_connect_reader_menu_item:
// Choose a device and connect to it
selectDevice();
return true;
case R.id.disconnect_reader_menu_item:
Toast.makeText(this.getApplicationContext(), "断开连接中...", Toast.LENGTH_SHORT).show();
disconnectDevice();
displayReaderState();
return true;
case R.id.reset_reader_menu_item:
resetReader();
UpdateUI();
return true;
}
return super.onOptionsItemSelected(item);
}
//
private void UpdateUI() {
//boolean isConnected = getCommander().isConnected();
//TODO: configure UI control state
}
private void scrollResultsListViewToBottom() {
mResultsListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
mResultsListView.setSelection(mResultsArrayAdapter.getCount() - 1);
}
});
}
private void scrollBarcodeListViewToBottom() {
mBarcodeResultsListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
mBarcodeResultsListView.setSelection(mBarcodeResultsArrayAdapter.getCount() - 1);
}
});
}
//----------------------------------------------------------------------------------------------
// AsciiCommander message handling
//----------------------------------------------------------------------------------------------
//
// Handle the messages broadcast from the AsciiCommander
//
private BroadcastReceiver mCommanderMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (D) { Log.d(getClass().getName(), "AsciiCommander state changed - isConnected: " + getCommander().isConnected()); }
String connectionStateMsg = intent.getStringExtra(AsciiCommander.REASON_KEY);
Toast.makeText(context, connectionStateMsg, Toast.LENGTH_SHORT).show();
displayReaderState();
if( getCommander().isConnected() )
{
// Update for any change in power limits
setPowerBarLimits();
// This may have changed the current power level setting if the new range is smaller than the old range
// so update the model's inventory command for the new power value
mModel.getCommand().setOutputPower(mPowerLevel);
mModel.resetDevice();
mModel.updateConfiguration();
}
UpdateUI();
}
};
//----------------------------------------------------------------------------------------------
// Reader reset
//----------------------------------------------------------------------------------------------
//
// Handle reset controls
//
private void resetReader() {
try {
// Reset the reader
FactoryDefaultsCommand fdCommand = FactoryDefaultsCommand.synchronousCommand();
getCommander().executeCommand(fdCommand);
String msg = "Reset " + (fdCommand.isSuccessful() ? "succeeded" : "failed");
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
//----------------------------------------------------------------------------------------------
// Power seek bar
//----------------------------------------------------------------------------------------------
//
// Set the seek bar to cover the range of the currently connected device
// The power level is set to the new maximum power
//
private void setPowerBarLimits()
{
DeviceProperties deviceProperties = getCommander().getDeviceProperties();
mPowerSeekBar.setMax(deviceProperties.getMaximumCarrierPower() - deviceProperties.getMinimumCarrierPower());
mPowerLevel = deviceProperties.getMaximumCarrierPower();
mPowerSeekBar.setProgress(mPowerLevel - deviceProperties.getMinimumCarrierPower());
}
//
// Handle events from the power level seek bar. Update the mPowerLevel member variable for use in other actions
//
private OnSeekBarChangeListener mPowerSeekBarListener = new OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Nothing to do here
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Update the reader's setting only after the user has finished changing the value
updatePowerSetting(getCommander().getDeviceProperties().getMinimumCarrierPower() + seekBar.getProgress());
mModel.getCommand().setOutputPower(mPowerLevel);
mModel.updateConfiguration();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePowerSetting(getCommander().getDeviceProperties().getMinimumCarrierPower() + progress);
}
};
private void updatePowerSetting(int level) {
mPowerLevel = level;
mPowerLevelTextView.setText( mPowerLevel + " dBm");
}
//----------------------------------------------------------------------------------------------
// Button event handlers
//----------------------------------------------------------------------------------------------
// Scan action
private OnClickListener mScanButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
mResultTextView.setText("");
// Perform a transponder scan
IMakeHttpCall();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Clear action
private OnClickListener mClearButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
// Clear the list
mResultsArrayAdapter.clear();
mBarcodeResultsArrayAdapter.clear();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//----------------------------------------------------------------------------------------------
// Handler for changes in session
//----------------------------------------------------------------------------------------------
private AdapterView.OnItemSelectedListener mActionSelectedListener = new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if( mModel.getCommand() != null ) {
QuerySession targetSession = (QuerySession)parent.getItemAtPosition(pos);
mModel.getCommand().setQuerySession(targetSession);
mModel.updateConfiguration();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
//----------------------------------------------------------------------------------------------
// Handler for changes in FastId
//----------------------------------------------------------------------------------------------
private OnClickListener mFastIdCheckBoxListener = new OnClickListener() {
public void onClick(View v) {
try {
CheckBox fastIdCheckBox = (CheckBox)v;
mModel.getCommand().setUsefastId(fastIdCheckBox.isChecked() ? TriState.YES : TriState.NO);
mModel.updateConfiguration();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
public void IMakeHttpCall(){
String url = "http://192.168.1.76:4300/lottem/query/toolsstockInventory/";
Uri.Builder builder = Uri.parse(url).buildUpon();
builder.appendQueryParameter("barCode", "1121212121");
JsonArrayRequest jsonObjRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
try {
JSONObject person;
for (int i = 0; i < response.length(); i++) {
person = response.getJSONObject(i);
String name = person.getString(("toolsName"));
mResultTextView.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// For ClientError, 400 & 401, Errors happening on client side when sending api request.
// In this case you can check how client is forming the api and debug accordingly.
// For ServerError 5xx, you can do retry or handle accordingly.
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
});
//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. Volley does retry for you if you have specified the policy.
mVolleyQueue.add(jsonObjRequest);
}
}
InventoryModel
//----------------------------------------------------------------------------------------------
// Copyright (c) 2013 Technology Solutions UK Ltd. All rights reserved.
//----------------------------------------------------------------------------------------------
package com.uk.tsl.rfid.samples.inventory;
import android.util.Log;
import com.uk.tsl.rfid.ModelBase;
import com.uk.tsl.rfid.asciiprotocol.commands.BarcodeCommand;
import com.uk.tsl.rfid.asciiprotocol.commands.FactoryDefaultsCommand;
import com.uk.tsl.rfid.asciiprotocol.commands.InventoryCommand;
import com.uk.tsl.rfid.asciiprotocol.enumerations.TriState;
import com.uk.tsl.rfid.asciiprotocol.responders.IBarcodeReceivedDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.ICommandResponseLifecycleDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.ITransponderReceivedDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.TransponderData;
import com.uk.tsl.utils.HexEncoding;
import java.util.Locale;
public class InventoryModel extends ModelBase
{
// Control
private boolean mAnyTagSeen;
private boolean mEnabled;
public boolean enabled() { return mEnabled; }
private InventoryActivity IAcitivity;
public void setEnabled(boolean state)
{
boolean oldState = mEnabled;
mEnabled = state;
// Update the commander for state changes
if(oldState != state) {
if( mEnabled ) {
// Listen for transponders
getCommander().addResponder(mInventoryResponder);
// Listen for barcodes
getCommander().addResponder(mBarcodeResponder);
} else {
// Stop listening for transponders
getCommander().removeResponder(mInventoryResponder);
// Stop listening for barcodes
getCommander().removeResponder(mBarcodeResponder);
}
}
}
// The command to use as a responder to capture incoming inventory responses
private InventoryCommand mInventoryResponder;
// The command used to issue commands
private InventoryCommand mInventoryCommand;
// The command to use as a responder to capture incoming barcode responses
private BarcodeCommand mBarcodeResponder;
// The inventory command configuration
public InventoryCommand getCommand() { return mInventoryCommand; }
public InventoryModel()
{
// This is the command that will be used to perform configuration changes and inventories
mInventoryCommand = new InventoryCommand();
mInventoryCommand.setResetParameters(TriState.YES);
// Configure the type of inventory
mInventoryCommand.setIncludeTransponderRssi(TriState.YES);
mInventoryCommand.setIncludeChecksum(TriState.YES);
mInventoryCommand.setIncludePC(TriState.YES);
mInventoryCommand.setIncludeDateTime(TriState.YES);
// Use an InventoryCommand as a responder to capture all incoming inventory responses
mInventoryResponder = new InventoryCommand();
// Also capture the responses that were not from App commands
mInventoryResponder.setCaptureNonLibraryResponses(true);
// Notify when each transponder is seen
mInventoryResponder.setTransponderReceivedDelegate(new ITransponderReceivedDelegate() {
int mTagsSeen = 0;
#Override
public void transponderReceived(final TransponderData transponder, boolean moreAvailable) {
mAnyTagSeen = true;
final String tidMessage = transponder.getTidData() == null ? "" : HexEncoding.bytesToString(transponder.getTidData());
final String infoMsg = String.format(Locale.US, "\nRSSI: %d PC: %04X CRC: %04X", transponder.getRssi(), transponder.getPc(), transponder.getCrc());
IAcitivity.IMakeHttpCall();
sendMessageNotification("条形码:"+transponder.getEpc());
mTagsSeen++;
if( !moreAvailable) {
sendMessageNotification("");
Log.d("扫描次数",String.format("扫描到的次数: %s", mTagsSeen));
}
}
});
}
It's probably just a silly mistake but I cannot fix it. I have a Google+ sign in a button, which is shown when the user is not logged in. I also have a sign out button, which is GONE when the user is logged in.Everything works except that when I go back to the activity (onResume) I can see the red Google+ button for about a second and than it gets hidden and the sign out button appears. How can I remove this one second during which I can still see the Google+ button ?
This is my layout:
XML code:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/startGameView"
android:src="#drawable/play"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/startGameView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp">
<!-- show achievements -->
<Button
android:id="#+id/show_achievements"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Achievements"/>
<!-- show leaderboards -->
<Button
android:id="#+id/show_leaderboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leaderboard"/>
</LinearLayout>
Code in the activity:
public class StartActivity extends BaseGameActivity implements View.OnClickListener{
private ImageView mPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mPlay = (ImageView)findViewById(R.id.startGameView);
mPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//play animations
YoYo.with(Techniques.Pulse)
.duration(200)
.playOn(findViewById(R.id.startGameView));
Intent intent = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent);
}
});
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.show_achievements).setOnClickListener(this);
findViewById(R.id.show_leaderboard).setOnClickListener(this);
//mSignOutButton = (Button)findViewById(R.id.sign_out_button);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_start, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSignInFailed() {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button) {
beginUserInitiatedSignIn();
}else if (view.getId() == R.id.sign_out_button) {
signOut();
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}else if (view.getId() == R.id.show_achievements){
Toast.makeText(StartActivity.this,"achivements",Toast.LENGTH_SHORT).show();
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), 1);
}else if(view.getId() == R.id.show_leaderboard){
Toast.makeText(StartActivity.this,"leaderboard",Toast.LENGTH_SHORT).show();
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(
getApiClient(), getString(R.string.number_of_solved_math_problems_leaderboard)), 2);
}
}
BaseActivity code:
public abstract class BaseGameActivity extends FragmentActivity implements
GameHelper.GameHelperListener {
// The game helper object. This class is mainly a wrapper around this object.
protected GameHelper mHelper;
// We expose these constants here because we don't want users of this class
// to have to know about GameHelper at all.
public static final int CLIENT_GAMES = GameHelper.CLIENT_GAMES;
public static final int CLIENT_APPSTATE = GameHelper.CLIENT_APPSTATE;
public static final int CLIENT_PLUS = GameHelper.CLIENT_PLUS;
public static final int CLIENT_ALL = GameHelper.CLIENT_ALL;
// Requested clients. By default, that's just the games client.
protected int mRequestedClients = CLIENT_GAMES;
private final static String TAG = "BaseGameActivity";
protected boolean mDebugLog = false;
/** Constructs a BaseGameActivity with default client (GamesClient). */
protected BaseGameActivity() {
super();
}
/**
* Constructs a BaseGameActivity with the requested clients.
* #param requestedClients The requested clients (a combination of CLIENT_GAMES,
* CLIENT_PLUS and CLIENT_APPSTATE).
*/
protected BaseGameActivity(int requestedClients) {
super();
setRequestedClients(requestedClients);
}
/**
* Sets the requested clients. The preferred way to set the requested clients is
* via the constructor, but this method is available if for some reason your code
* cannot do this in the constructor. This must be called before onCreate or getGameHelper()
* in order to have any effect. If called after onCreate()/getGameHelper(), this method
* is a no-op.
*
* #param requestedClients A combination of the flags CLIENT_GAMES, CLIENT_PLUS
* and CLIENT_APPSTATE, or CLIENT_ALL to request all available clients.
*/
protected void setRequestedClients(int requestedClients) {
mRequestedClients = requestedClients;
}
public GameHelper getGameHelper() {
if (mHelper == null) {
mHelper = new GameHelper(this, mRequestedClients);
mHelper.enableDebugLog(mDebugLog);
}
return mHelper;
}
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
if (mHelper == null) {
getGameHelper();
}
mHelper.setup(this);
}
#Override
protected void onStart() {
super.onStart();
mHelper.onStart(this);
}
#Override
protected void onStop() {
super.onStop();
mHelper.onStop();
}
#Override
protected void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
mHelper.onActivityResult(request, response, data);
}
protected GoogleApiClient getApiClient() {
return mHelper.getApiClient();
}
protected boolean isSignedIn() {
return mHelper.isSignedIn();
}
protected void beginUserInitiatedSignIn() {
mHelper.beginUserInitiatedSignIn();
}
protected void signOut() {
mHelper.signOut();
}
protected void showAlert(String message) {
mHelper.makeSimpleDialog(message).show();
}
protected void showAlert(String title, String message) {
mHelper.makeSimpleDialog(title, message).show();
}
protected void enableDebugLog(boolean enabled) {
mDebugLog = true;
if (mHelper != null) {
mHelper.enableDebugLog(enabled);
}
}
#Deprecated
protected void enableDebugLog(boolean enabled, String tag) {
Log.w(TAG, "BaseGameActivity.enabledDebugLog(bool,String) is " +
"deprecated. Use enableDebugLog(boolean)");
enableDebugLog(enabled);
}
protected String getInvitationId() {
return mHelper.getInvitationId();
}
protected void reconnectClient() {
mHelper.reconnectClient();
}
protected boolean hasSignInError() {
return mHelper.hasSignInError();
}
protected GameHelper.SignInFailureReason getSignInError() {
return mHelper.getSignInError();
}
If you cloned (or refreshed) the samples recently, you'll notice that GameHelper and BaseGameActivity are not longer used. There is an informative video about this change: Game On! - The death of BaseGameActivity. If you just implement the interfaces to get the callbacks for the state: GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener your problem should go away.
More specific details on how to use these interfaces is at https://developers.google.com/games/services/training/signin
As I see in GameHelper class, it disconnects from googleApiClient on onStop() and connect on onStart(). This is causing of blinking buttons.
If you don't want to change GameHelper implementation, make some UI improvement to make it less annoying.
I am trying to develop an app with in app purchases in it, simply what I want to do is to have two buttons one to make the purchase(enabled) the second button to open the activity after purchase (at first is disabled then after purchase is enabled).
Two problems the first was to save the buttons state after the purchase as they were getting reset every time I restart the app. So I did some researches and found about shared preference and I did implemented it but the second problem came out that buttons statuses doesn’t seem to work right (between disabled to enabled) after implementing shared preference.
Note that in the app I have two buttons that do the same thing one enables the other buttons but with no purchase made and they work fine with shared preference, but the buttons associated with the in app purchase stopped changing their status from disabled to enabled after the purchase is made (they stay disabled after the purchase)
Here is my xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainScreen">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1"
android:id="#+id/act1"
android:onClick="Activity1"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/buyall"
android:layout_toStartOf="#+id/buyall"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Act 1"
android:id="#+id/buyButton"
android:onClick="buyClick"
android:layout_alignTop="#+id/act1"
android:layout_toRightOf="#+id/act1"
android:layout_toEndOf="#+id/act1"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
android:id="#+id/act2"
android:layout_below="#+id/act1"
android:layout_alignLeft="#+id/act1"
android:layout_alignStart="#+id/act1"
android:onClick="Activity2"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 2"
android:id="#+id/buyact2"
android:layout_alignBottom="#+id/act2"
android:layout_alignLeft="#+id/buyButton"
android:layout_alignStart="#+id/buyButton"
android:onClick="buyAct2"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
android:id="#+id/act3"
android:layout_below="#+id/act2"
android:layout_alignLeft="#+id/act2"
android:layout_alignStart="#+id/act2"
android:onClick="Activity3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 3"
android:id="#+id/buyact3"
android:layout_alignBottom="#+id/act3"
android:layout_alignLeft="#+id/buyact2"
android:layout_alignStart="#+id/buyact2"
android:onClick="buyAct3"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy all"
android:id="#+id/buyall"
android:onClick="buyAll"
android:enabled="true"
android:layout_below="#+id/eact4"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACT 4"
android:id="#+id/act4"
android:onClick="ACT4"
android:layout_below="#+id/act3"
android:layout_alignLeft="#+id/act3"
android:layout_alignStart="#+id/act3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable ACT 4"
android:id="#+id/eact4"
android:onClick="EACT4"
android:layout_below="#+id/buyact3"
android:layout_alignLeft="#+id/buyact3"
android:layout_alignStart="#+id/buyact3"
android:enabled="true" />
And that’s my java code:
package com.aseng90_test.smiap2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.aseng90_test.smiap2.util.IabHelper;
import com.aseng90_test.smiap2.util.IabResult;
import com.aseng90_test.smiap2.util.Purchase;
public class MainScreen extends ActionBarActivity {
private static final String TAG = "com.aseng90_test.smiap2";
IabHelper mHelper;
private static final String ITEM_SKU = "com.aseng90_test.smiap2_button555";
private static final String ITEM_SKU2 = "com.aseng90_test.smiap2_buyact222";
private static final String ITEM_SKU3 = "com.aseng90_test.smiap2_buyact333";
private static final String ITEM_SKU4 = "com.aseng90_test.smiap2_buyall_11";
private Button Activity1;
private Button Activity2;
private Button Activity3;
private Button buyButton;
private Button buyAct2;
private Button buyAct3;
private Button buyAll;
private Button EAct4;
private Button Act4;
private SharedPreferences prefs;
private String prefName = "MyPref";
boolean Activity1_isEnabled;
boolean Activity2_isEnabled;
boolean Activity3_isEnabled;
boolean Act4_isEnabled;
boolean buyButton_isEnabled;
boolean buyAct2_isEnabled;
boolean buyAct3_isEnabled;
boolean buyAll_isEnabled;
boolean EAct4_isEnabled;
private static final String Activity1_state = "Activity1_state";
private static final String Activity2_State = "Activity2_state";
private static final String Activity3_State = "Activity3_state";
private static final String buyButton_State = "buyButton_state";
private static final String buyAct2_State = "buyAct2_state";
private static final String buyAct3_State = "buyAct3_state";
private static final String buyAll_State = "buyAll_state";
private static final String Act4_State = "Act4_state";
private static final String EAct4_State = "EAct4_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
buyButton = (Button) findViewById(R.id.buyButton);
buyAct2 = (Button) findViewById(R.id.buyact2);
buyAct3 = (Button) findViewById(R.id.buyact3);
buyAll = (Button) findViewById(R.id.buyall);
Activity1 = (Button) findViewById(R.id.act1);
Activity2 = (Button) findViewById(R.id.act2);
Activity3 = (Button) findViewById(R.id.act3);
EAct4 = (Button) findViewById(R.id.eact4);
Act4 = (Button) findViewById(R.id.act4);
String base64EncodedPublicKey =
"";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void EACT4(View view) {
EAct4.setEnabled(false);
Act4.setEnabled(true);
}
public void ACT4(View view) {
Toast.makeText(MainScreen.this,
"ACt4 Clicked", Toast.LENGTH_LONG).show();
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
public void buyAct2(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU2, 10002, mPurchaseFinishedListener, "buyact2");
}
public void buyAct3(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU3, 10003, mPurchaseFinishedListener, "buyact3");
}
public void buyAll(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU4, 10004, mPurchaseFinishedListener, "buyall");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
}
if (purchase.getSku().equals(ITEM_SKU)) {
Activity1.setEnabled(true);
buyButton.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU2)) {
Activity2.setEnabled(true);
buyAct2.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU3)) {
Activity3.setEnabled(true);
buyAct3.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU4)) {
Activity1.setEnabled(true);
Activity2.setEnabled(true);
Activity3.setEnabled(true);
buyAll.setEnabled(false);
buyButton.setEnabled(false);
buyAct2.setEnabled(false);
buyAct3.setEnabled(false);
}
}
};
public void Activity1(View view) {
startActivity(new Intent(MainScreen.this, Click1.class));
}
public void Activity2(View view) {
startActivity(new Intent(MainScreen.this, Activity2.class));
}
public void Activity3(View view) {
startActivity(new Intent(MainScreen.this, Activity3.class));
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
#Override
protected void onPause(){
super.onPause();
if (Act4.isEnabled()){
Act4_isEnabled = true;
}
else {
Act4_isEnabled = false;
}
if (Activity1.isEnabled()){
Activity1_isEnabled = true;
}
else {
Activity1_isEnabled = false;
}
if (Activity2.isEnabled()){
Activity2_isEnabled = true;
}
else {
Activity2_isEnabled = false;
}
if (Activity3.isEnabled()){
Activity3_isEnabled = true;
}
else {
Activity3_isEnabled = false;
}
if (buyButton.isEnabled()){
buyButton_isEnabled = true;
}
else {
buyButton_isEnabled = false;
}
if (buyAct2.isEnabled()){
buyAct2_isEnabled = true;
}
else {
buyAct2_isEnabled = false;
}
if (buyAct3.isEnabled()){
buyAct3_isEnabled = true;
}
else {
buyAct3_isEnabled = false;
}
if (buyAll.isEnabled()){
buyAll_isEnabled = true;
}
else {
buyAll_isEnabled = false;
}
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Activity1_state,this.getLocalClassName());
editor.putBoolean(Act4_State,Act4_isEnabled);
editor.putBoolean(EAct4_State,EAct4_isEnabled);
editor.putBoolean(Activity1_state,Activity1_isEnabled);
editor.putBoolean(Activity2_State,Activity2_isEnabled);
editor.putBoolean(Activity3_State,Activity3_isEnabled);
editor.putBoolean(buyButton_State,buyButton_isEnabled);
editor.putBoolean(buyAct2_State,buyAct2_isEnabled);
editor.putBoolean(buyAct3_State,buyAct3_isEnabled);
editor.putBoolean(buyAll_State,buyAll_isEnabled);
editor.apply();
}
#Override
protected void onResume(){
super.onResume();
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
Act4.setEnabled(prefs.getBoolean(Act4_State,false));
Activity1.setEnabled(prefs.getBoolean(Activity1_state,false));
Activity2.setEnabled(prefs.getBoolean(Activity2_State,false));
Activity3.setEnabled(prefs.getBoolean(Activity3_State,false));
EAct4.setEnabled(prefs.getBoolean(EAct4_State,true));
buyButton.setEnabled(prefs.getBoolean(buyButton_State,true));
buyAct2.setEnabled(prefs.getBoolean(buyAct2_State,true));
buyAct3.setEnabled(prefs.getBoolean(buyAct3_State,true));
buyAll.setEnabled(prefs.getBoolean(buyAll_State,true));
}
So Any suggestions if I have something wrong in my code?
Thanks a lot.
Try to call methods from Java part , don't call from xml using android:onClick
Use default value of the button(buy) state to false in shared preference .
and in this screen implement this if check inside oncreate() method as:
if(button(buy) state ==false)
{
//make button(buy) state enable
//make activity button state disable
}
else
{
//make button(buy) state disable
//make activity button state enable
}
And make button(buy) and activity calling button state to true/false according to result after in app purchase and also update shared prefrence state according to result
I have a problem with an android application. I want to make a login screen, and I have an async task that should run when the login button is pressed. However, it appears that the runs automatically when the application starts, and I can't figure out why.
This is my code:
package com.connect.application;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import com.connect.utils.*;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends Activity {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
// private static final String[] DUMMY_CREDENTIALS = new String[]{
// "foo#example.com:hello",
// "bar#example.com:world"
// };
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
private Boolean mLoggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
// mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
// #Override
// public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
// if (id == R.id.login || id == EditorInfo.IME_NULL) {
// attemptLogin();
// return true;
// }
// return false;
// }
// });
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("TAG/Login clicked", "Login button clicked");
attemptLogin();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!mEmail.contains("#")) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
String[] credentials = new String[2];
credentials[0] = mEmail;
credentials[1] = mPassword;
Log.v("TAG/Auth task started", "Auth task started");
mAuthTask.execute(credentials);
}
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate()
.setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate()
.setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
// TODO: attempt authentication against a network service.
// try {
// // Simulate network access.
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// return false;
// }
//
// for (String credential : DUMMY_CREDENTIALS) {
// String[] pieces = credential.split(":");
// if (pieces[0].equals(mEmail)) {
// // Account exists, return true if the password matches.
// return pieces[1].equals(mPassword);
// }
// }
Log.v("TAG/LoginAsync", "Task triggerred");
LoggedUser.getInstance().setId(1);
LoggedUser.getInstance().setmUsername("dummy#mail.com");
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
mLoggedIn = true;
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
And this is what appears in my log when I run the application:
01-16 14:36:01.593 13706-13706/com.connect.application V/TAG/Login clicked﹕ Login button clicked
01-16 14:36:01.597 13706-13706/com.connect.application V/TAG/Auth task started﹕ Auth task started
01-16 14:36:01.601 13706-13742/com.connect.application V/TAG/LoginAsync﹕ Task triggerred
, without pressing any buttons. Any help would be appreciated.