Related
Currently i'm implementing the in app update feature from android. I'm using the immediate update method, the problem that I'm facing is that when the UI prompting the user to update shows and the user does not click the update button instead they click the cross button. The UI for the app update just closes and user can continue using the app.
What I want is that when user click the cross button the app immediately closes, until user updates the app then they can use the app as usual. I also uses the java code for the android development.
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
public static final String MyPREFERENCES = "LoginPrefs" ;
public static final String Name = "nameKey";
public static final String User = "userKey";
public static final String con = "closed";
public static String error = "";
public static int userFlag = 0;
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
public TextInputEditText usernameEditText;
public TextInputEditText passwordEditText;
private AppUpdateManager mAppUpdateManager;
private int RC_APP_UPDATE = 999;
private int inAppUpdateType;
private com.google.android.play.core.tasks.Task<AppUpdateInfo> appUpdateInfoTask;
private InstallStateUpdatedListener installStateUpdatedListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory())
.get(LoginViewModel.class);
usernameEditText = findViewById(R.id.user);
passwordEditText = findViewById(R.id.pass);
final Button loginButton = findViewById(R.id.submitBTN);
final TextInputLayout userL = findViewById(R.id.userL);
final TextInputLayout passL = findViewById(R.id.passL);
final JellyToggleButton jtb = findViewById(R.id.jtb);
// Creates instance of the manager.
mAppUpdateManager = AppUpdateManagerFactory.create(this);
// Returns an intent object that you use to check for an update.
appUpdateInfoTask = mAppUpdateManager.getAppUpdateInfo();
//lambda operation used for below listener
//For flexible update
installStateUpdatedListener = installState -> {
if (installState.installStatus() == InstallStatus.DOWNLOADED) {
popupSnackbarForCompleteUpdate();
}
};
mAppUpdateManager.registerListener(installStateUpdatedListener);
inAppUpdateType = AppUpdateType.IMMEDIATE; //1
inAppUpdate();
if(userFlag==1){
jtb.setChecked(true);
}
userL.setHint("Enter username");
sharedpreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
#Override
public void onChanged(#Nullable LoginFormState loginFormState) {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError()));
loginButton.startAnimation(AnimationUtils.loadAnimation(LoginActivity.this,R.anim.shake));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError()));
loginButton.startAnimation(AnimationUtils.loadAnimation(LoginActivity.this,R.anim.shake));
}
}
});
loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
#Override
public void onChanged(#Nullable LoginResult loginResult) {
if (loginResult == null) {
return;
}
if (loginResult.getError() != null) {
showLoginFailed(loginResult.getError());
}
if (loginResult.getSuccess() != null) {
updateUiWithUser(loginResult.getSuccess());
Intent i = new Intent(LoginActivity.this, user_dashboard.class);
startActivity(i);
}
setResult(Activity.RESULT_OK);
//Complete and destroy login activity once successful
}
});
TextWatcher afterTextChangedListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ignore
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ignore
}
#Override
public void afterTextChanged(Editable s) {
loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
};
usernameEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
return false;
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(userFlag==0) {
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
getStaffData();
}
else if(userFlag==1){
loginWorker();
}
}
});
jtb.setOnStateChangeListener(new JellyToggleButton.OnStateChangeListener() {
#Override
public void onStateChange(float process, State state, JellyToggleButton jtb) {
if (state.equals(State.LEFT)) {
userL.setHint("Enter username");
error = "Username cannot be empty";
userFlag = 0;
}
if (state.equals(State.RIGHT)) {
userL.setHint("Enter badge ID");
error = "Badge ID cannot be empty";
userFlag = 1;
}
}
});
}
#Override
protected void onDestroy() {
mAppUpdateManager.unregisterListener(installStateUpdatedListener);
finishAndRemoveTask();
super.onDestroy();
}
#Override
protected void onResume() {
try {
mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() ==
UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
// If an in-app update is already running, resume the update.
try {
mAppUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
inAppUpdateType,
this,
RC_APP_UPDATE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});
mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
//For flexible update
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
popupSnackbarForCompleteUpdate();
}
});
} catch (Exception e) {
e.printStackTrace();
}
super.onResume();
}
#Override //For flexible update
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_APP_UPDATE) {
//when user clicks update button
if (resultCode == RESULT_OK) {
Toast.makeText(LoginActivity.this, "App download starts...", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
//if you want to request the update again just call checkUpdate()
Toast.makeText(LoginActivity.this, "App download canceled.", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_IN_APP_UPDATE_FAILED) {
Toast.makeText(LoginActivity.this, "App download failed.", Toast.LENGTH_LONG).show();
}
}
}
private void updateUiWithUser(LoggedInUserView model) {
String welcome = getString(R.string.welcome);
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
private void showLoginFailed(#StringRes Integer errorString) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
}
private void getStaffData() {
String username = usernameEditText.getText().toString();
APIInterface apiInterface3 = APIClient.getClient().create(APIInterface.class);
Call<loginList> call3 = apiInterface3.staffData(username);
call3.enqueue(new Callback<loginList>() {
#Override
public void onResponse(Call<loginList> call, Response<loginList> response) {
loginList list = response.body();
if (list!=null && list.getStatusCode()==1) { //response received.
if(list.getStaffList().size()>0){
Log.d("check-in", list.getStatusCode() + " " + list.getStaffList().get(0).getName());
Toast.makeText(LoginActivity.this,"Logged in",Toast.LENGTH_SHORT).show();
final String name = list.getStaffList().get(0).getName();
final String badge = list.getStaffList().get(0).getBadge();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name,name);
editor.putString(User,badge);
editor.putInt(con,1);
editor.apply();
}
else if(list.getStaffList().size()==0){
}
}
}
#Override
public void onFailure(Call<loginList> call, Throwable t) {
Log.d("fail",t.toString());
}
});
}
private void loginWorker(){
String username = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
APIInterface apiInterface3 = APIClient.getClient().create(APIInterface.class);
Call<loginList> call3 = apiInterface3.loginWorker(username,password);
call3.enqueue(new Callback<loginList>() {
#Override
public void onResponse(Call<loginList> call, Response<loginList> response) {
loginList list = response.body();
Log.d("response", response.body().toString());
if (list!=null && list.getStatusCode()==1) { //response received.
if(list.getLoginList().size()>0){
Log.d("check-in", list.getStatusCode() + " " + list.getLoginList().get(0).getName());
Toast.makeText(LoginActivity.this,"Logged in",Toast.LENGTH_SHORT).show();
List<login> item = response.body().getLoginList();
final String name = list.getLoginList().get(0).getName();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name,name);
editor.putInt(con,1);
editor.apply();
}
String welcome = getString(R.string.welcome);
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this, user_dashboard.class);
startActivity(i);
}
else
Toast.makeText(LoginActivity.this, "wrong ID or password",Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<loginList> call, Throwable t) {
Log.d("fail",t.toString());
}
});
editor = sharedpreferences.edit();
editor.putString(User, username);
editor.commit();
}
#Override
public void onBackPressed() {
new MaterialAlertDialogBuilder(LoginActivity.this,R.style.MyDialogTheme)
.setTitle("Exit")
.setMessage("Confirm to exit?")
.setBackground(getDrawable(R.drawable.alert_dialog))
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete
finishAffinity();
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
private void inAppUpdate() {
try {
// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener(new OnSuccessListener<AppUpdateInfo>() {
#Override
public void onSuccess(AppUpdateInfo appUpdateInfo) {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
// For a flexible update, use AppUpdateType.FLEXIBLE
&& appUpdateInfo.isUpdateTypeAllowed(inAppUpdateType)) {
// Request the update.
try {
mAppUpdateManager.startUpdateFlowForResult(
// Pass the intent that is returned by 'getAppUpdateInfo()'.
appUpdateInfo,
// Or 'AppUpdateType.FLEXIBLE' for flexible updates.
inAppUpdateType,
// The current activity making the update request.
LoginActivity.this,
// Include a request code to later monitor this update request.
RC_APP_UPDATE);
} catch (IntentSender.SendIntentException ignored) {
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void popupSnackbarForCompleteUpdate() {
try {
Snackbar snackbar =
Snackbar.make(
findViewById(R.id.coordinatorL),
"An update has just been downloaded.\nRestart to update",
Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("INSTALL", view -> {
if (mAppUpdateManager != null){
mAppUpdateManager.completeUpdate();
}
});
snackbar.setActionTextColor(getResources().getColor(R.color.orange));
snackbar.show();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
}
The image I borrowed from google, on the left image as can be seen there is a cross button on top right user can click to close the update process
The most important point I will emphasize is that you should not force users to update the app until it is absolutely necessary (like some security issues etc). Forcing updates to users is considered a very bad user experience.
To the question you asked, you have the answer in your question itself. If you check the code you have something like this in your onActivityResult method-
if (requestCode == RC_APP_UPDATE) {
//when user clicks update button
if (resultCode == RESULT_OK) {
Toast.makeText(LoginActivity.this, "App download starts...", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
//if you want to request the update again just call checkUpdate()
Toast.makeText(LoginActivity.this, "App download canceled.", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_IN_APP_UPDATE_FAILED) {
Toast.makeText(LoginActivity.this, "App download failed.", Toast.LENGTH_LONG).show();
}
}
In case when the user cancels resultCode == RESULT_CANCELED or the update fails resultCode == RESULT_IN_APP_UPDATE_FAILED, you can take whatever action you want. You can finish the activity or whatever is suitable in your situation.
I'm having a weird problem in my Android app when casting a Activity to my MainActivity. I'm using GeoFences to broadcasts events to a base activity called NotificationActivity. The NotificationActivity is used in all the other activities I use so when a GeoFence triggers an AlertDialog pops up. Now when a GeoFence triggers and I'm in an activity other than MainActivity, I need to finish the current activity and do a certain action on the MainActivity (switch to a certain tab). In my Application class I'm implementing the Application.ActivityLifeCycleCallbacks, in the onActivityResumed callback I set my currentActivity to the resumed activity (I know a static reference causes memory leaks but I need to fix this).
Here's my application class:
private static Activity currentActivity;
#Override
public void onCreate() {
super.onCreate();
// Setup Fabric
if (AppConfig.getEnvironment() != AppConfig.Environment.Development) {
Fabric.with(this, new Crashlytics(), new Answers());
}
// Init realm
Realm.init(this);
// Init Firebase
FirebaseApp.initializeApp(this);
if (AppConfig.getEnvironment() == AppConfig.Environment.Development) {
// Init Stetho with realm plugin
Stetho.initialize (
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
}
registerActivityLifecycleCallbacks(this);
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.d(Constants.DEBUG, "Activity created: " + activity.toString());
}
#Override
public void onActivityStarted(Activity activity) {
Log.d(Constants.DEBUG, "Activity started: " + activity.toString());
}
#Override
public void onActivityResumed(Activity activity) {
Log.d(Constants.DEBUG, "Activity resumed: " + activity.toString());
currentActivity = activity;
}
#Override
public void onActivityPaused(Activity activity) {
Log.d(Constants.DEBUG, "Activity paused: " + activity.toString());
}
#Override
public void onActivityStopped(Activity activity) {
Log.d(Constants.DEBUG, "Activity stopped: " + activity.toString());
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.d(Constants.DEBUG, "Activity SaveInstanceState: " + activity.toString());
}
#Override
public void onActivityDestroyed(Activity activity) {
Log.d(Constants.DEBUG, "Activity Destroyed: " + activity.toString());
}
public static Activity getCurrentActivity() {
return currentActivity;
}
And here's my NotificationActivity (base) activity:
public abstract class NotificationActivity extends AppCompatActivity {
private BroadcastReceiver onNoticeWithinPoi = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Realm realm = Realm.getDefaultInstance();
Poi poi = realm.where(Poi.class).equalTo("ref", bundle.getString(Constants.POI_KEY_REF)).findFirst();
showAlertWithinPoi(context, poi);
}
}
};
private BroadcastReceiver onNoLocationProviderSet = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
warnUserNoLocationProviderSet();
}
};
private BroadcastReceiver onNoticeOutOfRange = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
alertNoticeOutOfRange();
}
};
public Fragment getActiveFragment() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getFragmentManager().getBackStackEntryAt(getFragmentManager().getBackStackEntryCount() - 1).getName();
return getFragmentManager().findFragmentByTag(tag);
}
private void showAlertWithinPoi(final Context context, final Poi poi) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.poi_popup_title));
builder.setMessage(getString(R.string.poi_popup_subtitle));
builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Game currentGame = Helper.getCurrentGame(context);
Game poiGame = null;
Realm realm = Realm.getDefaultInstance();
for (Game game : realm.where(Game.class).findAll()) {
for (Tag tag : game.tags) {
if (tag.poi.ref.equals(poi.ref)) {
poiGame = game;
break;
}
}
if (poiGame != null) {
break;
}
}
if (poiGame != null && poiGame.ref.equals(currentGame.ref)) {
realm.beginTransaction();
currentGame.lastSeenPoi = poi.ref;
realm.commitTransaction();
checkCurrentActivity();
} else if (poiGame != null && !poiGame.ref.equals(currentGame.ref)) {
showAlertDifferentGame(context, poiGame, poi);
}
}
});
builder.setNegativeButton(getString(R.string.later), null);
builder.setIcon(R.drawable.poi_unvisited);
builder.create().show();
}
private void showAlertDifferentGame(final Context context, final Game game, final Poi poi) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.game_switch_title));
builder.setMessage(getString(R.string.game_switch_message) + " " + LanguageHelper.getGameTitle(game) + " ?");
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
game.lastSeenPoi = poi.ref;
realm.commitTransaction();
SharedPreferencesHelper.saveString(context, Constants.PREF_SELECTED, game.ref);
GeofenceService.updateGeoFences(game, context);
checkCurrentActivity();
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkCurrentActivity();
}
});
builder.create().show();
}
private void checkCurrentActivity() {
final Activity currentActivity = GeoFortApplication.getCurrentActivity();
if (currentActivity instanceof MainActivity) {
((MainActivity) currentActivity).switchTab();
} else {
currentActivity.finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.d(Constants.DEBUG, "CurrentActivity: " + currentActivity.toString());
((MainActivity) currentActivity).switchTab();
} catch (ClassCastException e) {
Log.e(Constants.EXCEPTION, e.getLocalizedMessage());
}
}
}, 5000);
}
}
private void alertNoticeOutOfRange() {
new AlertDialog.Builder(this)
.setTitle(R.string.error_location_not_close_enough_title)
.setMessage(R.string.error_location_not_close_enough_alert)
.setPositiveButton(R.string.ok, null)
.setIcon(R.drawable.ic_launcher)
.show();
}
private void warnUserNoLocationProviderSet() {
new AlertDialog.Builder(this)
.setTitle(R.string.error_location_not_available_title)
.setMessage(R.string.error_location_services_not_available_text)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO no user location set?
}
})
.setIcon(null)
.show();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filterWithinPoi = new IntentFilter(Constants.NOTIFICATION_WITHIN_POI);
filterWithinPoi.setPriority(2);
registerReceiver(onNoticeWithinPoi, filterWithinPoi);
IntentFilter filterOutOfRange = new IntentFilter(Constants.NOTIFICATION_LOCATION_OUT_OF_RANGE);
filterOutOfRange.setPriority(2);
registerReceiver(onNoticeOutOfRange, filterOutOfRange);
IntentFilter filterLocationProviderOff = new IntentFilter(Constants.NOTIFICATION_LOCATION_PROVIDER_OFF);
registerReceiver(onNoLocationProviderSet, filterLocationProviderOff);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(onNoticeWithinPoi);
unregisterReceiver(onNoticeOutOfRange);
unregisterReceiver(onNoLocationProviderSet);
}
}
you are doing something wrong on else
private void checkCurrentActivity() {
final Activity currentActivity = GeoFortApplication.getCurrentActivity();
if (currentActivity instanceof MainActivity) {
((MainActivity) currentActivity).switchTab();
} else {
currentActivity.finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.d(Constants.DEBUG, "CurrentActivity: " + currentActivity.toString());
((MainActivity) currentActivity).switchTab();
} catch (ClassCastException e) {
Log.e(Constants.EXCEPTION, e.getLocalizedMessage());
}
}
}, 5000);
}
}
Within run method the activity is not a MainActivity, as you do check it before.
Fist check
if (activity instanceOf MainActivity){
// do typecast here
}else{
// you should which which instance you have
}
This way you will get rid of classCastException
I have 2 classes:
TelaCadastroRestaurante (extends Activity) and Metodos (doesn't extends Activity).
On my first class i have this: http://i.imgur.com/N0jrjc1.png
On my second class i have this: http://i.imgur.com/PimEoxr.png
So, What do i want to? In my method caixaCerteza(), i want pass the method mandarNuvem() through/as PARAMETER 3.
public class TelaCadastroRestaurante extends Activity {
private EditText nomeRestaurante, emailRestaurante, telefoneRestaurante;
private Button buttonProximo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_cadastro_restaurante);
incializarComponentes();
acaoBotoes();
}
public void incializarComponentes() {
nomeRestaurante = (EditText) findViewById(R.id.editTextNomeRestauranteTelaCadastroRestaurante);
emailRestaurante = (EditText) findViewById(R.id.editTextEmailRestauranteTelaCadastroRestaurante);
telefoneRestaurante = (EditText) findViewById(R.id.editTextTelefoneRestauranteTelaCadastroRestaurante);
buttonProximo = (Button) findViewById(R.id.buttonProximoTelaCadastroRestaurante);
}
public void acaoBotoes() {
buttonProximo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pegarValores();
callMandarNuvem();
}
});
}
public void pegarValores(){
final Restaurante rest = new Restaurante();
rest.setNomeRest(nomeRestaurante.getText().toString());
rest.setEmailRest(emailRestaurante.getText().toString());
rest.setTelefoneRest(Integer.parseInt(telefoneRestaurante.getText().toString()));
}
public void callMandarNuvem(){
Metodos.caixaCerteza(TelaCadastroRestaurante.this,
"Você tem certeza que deseja cadastrar o restaurante " + nomeRestaurante.getText().toString() + "?",
Metodos.mandarNuvem(TelaCadastroRestaurante.this));
}
}
public class Metodos {
private static ProgressDialog dialog;
// Metodo que mostra o Aguarde a verificação
public static void taskInProgres(boolean mostrar, Context context) {
if (dialog == null) {
dialog = new ProgressDialog(context);
dialog = ProgressDialog.show(context, "","Espere um momento...", true);
}
if (mostrar) {
dialog.show();
} else {
dialog.dismiss();
}
}
// Metodo que mostra a caixa de certeza
public static void caixaCerteza(final Context context, final String texto, final Metodos metodo) {
AlertDialog.Builder builderaction = new AlertDialog.Builder(context);
builderaction.setTitle("Atenção!");
builderaction.setMessage(texto);
builderaction.setPositiveButton("Sim",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builderaction.setNegativeButton("Não",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builderaction.create();
alert.setIcon(R.drawable.ic_stop);
alert.show();
}
public static void mandarNuvem(final Context context){
Metodos.taskInProgres(true, context);
Restaurante rest = new Restaurante();
ParseObject restauranteParse = new ParseObject("Restaurante");
restauranteParse.put("nomeRestaurante", rest.getNomeRest());
restauranteParse.put("emailRestaurante", rest.getEmailRest());
restauranteParse.put("telefoneRestaurante", rest.getTelefoneRest());
restauranteParse.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(context,"Salvo com sucesso!", Toast.LENGTH_SHORT).show();
Metodos.taskInProgres(false, context);
} else {
Toast.makeText(context, e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
You can't pass a method, but an object containing a method. This means maybe slightly more code. Call caixaCerteza with something like
caixaCerteza(..., ..., new Callable() {
#Override
public void call() {
mandarNuvem();
}
});
In method caixaCerteza(..., ..., Callable callable), execute the method with
callable.call();
EDIT:
This can even be simplified if the method mandarNuvem can be put in a class that implements some interface/extends a superclass (for example, Callable) that can then serve as a third parameter of caixaCerteza directly (instead of wrapping it in an anonymous Callable object).
The title it's not clear i think. In my project i want a service that runs in background and when the user says "hello phone" or some word/phrase my app starts to recognize the voice. Actually it "works" but not in right way... I have a service and this service detect the voice.
public class SpeechActivationService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static String TAG = "Icaro";
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
private int mBindFlag;
private Messenger mServiceMessenger;
#Override
public void onCreate()
{
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
protected static class IncomingHandler extends Handler
{
private WeakReference<SpeechActivationService> mtarget;
IncomingHandler(SpeechActivationService target)
{
mtarget = new WeakReference<SpeechActivationService>(target);
}
#Override
public void handleMessage(Message msg)
{
final SpeechActivationService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d(TAG, "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d(TAG, "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
try
{
Message msg = new Message();
msg.what = MSG_RECOGNIZER_START_LISTENING;
mServerMessenger.send(msg);
}
catch (RemoteException e)
{
}
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer)
{
String sTest = "";
}
#Override
public void onEndOfSpeech()
{
Log.d("TESTING: SPEECH SERVICE", "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mIsListening = false;
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("TESTING: SPEECH SERVICE", "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Log.d(TAG, (String) data.get(0));
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "onResults"); //$NON-NLS-1$
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And i start service in my MainActivity just to try:
Intent i = new Intent(context, SpeechActivationService.class);
startService(i);
It detect the voice input...and TOO MUCH!!! Every time it detects something it's a "bipbip". Too many bips!! It's frustrating.. I only want that it starts when i say "hello phone" or "start" or a specific word!! I try to look at this https://github.com/gast-lib/gast-lib/blob/master/library/src/root/gast/speech/activation/WordActivator.java but really i don't know how use this library. I try see this question onCreate of android service not called but i not understand exactly what i have to do.. Anyway, i already import the gast library.. I only need to know how use it. Anyone can help me step by step? Thanks
Use setStreamSolo(AudioManager.STREAM_VOICE_CALL, true) instead of setStreamMute. Remember to add setStreamSolo(AudioManager.STREAM_VOICE_CALL, false) in case MSG_RECOGNIZER_CANCEL
I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}