Speech Recognizer in haddler seems to open the activity again every time - java

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = (TextView) findViewById(R.id.textView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
progressBar.setVisibility(View.INVISIBLE);
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
} else {
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
speech.stopListening();
}
}
});
ttsManager = new TTSManager();
ttsManager.init(this);
Pause = (Button) findViewById(R.id.pause);
Stop = (Button) findViewById(R.id.stop);
Resume = (Button) findViewById(R.id.resume);
Pause.setVisibility(View.INVISIBLE);
Resume.setVisibility(View.INVISIBLE);
Stop.setVisibility(View.INVISIBLE);
// -------------------------------------
//----------------------------------------
handler = new android.os.Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
Log.e("TAG", sbprint);
if(sbprint.contains("ello")){
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
toggleButton.setChecked(true);
}
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
//--------------------------------------
}
I am trying to activate speech like I am pressing the toogleButton, and i copyed the code from the toogleButton to the handler.
Everything is ok, i mean if i click the toogleButton it works, but when i recive the message that cointains "ello" in the handler, the speechRecognizer starts but closes very quickly, this happens every time i send that message.
Also it seems like a new activity i created when i trigger the handler with that message, but the same functions in the toogleButton work.
Any ideea how can i make this work ? I want functionality in the toogleButton, but in the handler too, so i can trigger speechRecognition with a message or something inside handler.

I think the problem is that you're changing the toggleButton's state inside the Handler
toggleButton.setChecked(true);
And this will trigger the OnCheckedChangeListener. But this should start the speech recognition again (because you set it to true), not stop it.
Try to call only toggleButton.setChecked(true); in your Handler, see if that resolves the problem, for example:
if(sbprint.contains("ello")){
toggleButton.setChecked(true);
}

Related

.setChecked() isn't setting the state of radio button

I'm creating a security settings part in my app.
There are 3 radio buttons that allow the user to choose between a passcode, TouchID or nothing. All radio buttons are unchecked by default. When clicking on a radio button (e.g. to use passcode), the code checks to see if the user has set up a passcode. If the user hasn't, a dialog is shown and the radio button remains unchecked. The user then goes and sets up a passcode (setUpPasscode button).
Once set up, the passcode activity closes with the return case '2' and the radio button with the passcode option should be checked. It isn't however. When I re-launch the application, the button is checked though. It somehow isn't checked immediately after finishing the previous activity but it is technically checked. What am I doing wrong?
public class SecuritySettings extends AppCompatActivity
{
TextView goBackToSettings;
Button setUpPasscode;
Button setUpTouchID;
RadioButton usePasscodeSelection;
RadioButton useTouchIDSelection;
RadioButton useNeitherSelection;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Dialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.security_settings);
goBackToSettings = (TextView) findViewById(R.id.closeSettingsButtonID);
setUpPasscode = (Button) findViewById(R.id.setUpPasscodeButtonID);
setUpTouchID = (Button) findViewById(R.id.setUpTouchIDButtonID);
usePasscodeSelection = (RadioButton) findViewById(R.id.usePasscode);
useTouchIDSelection = (RadioButton) findViewById(R.id.useTouchID);
useNeitherSelection = (RadioButton) findViewById(R.id.useNothing);
myDialog = new Dialog(this);
//load state of radio buttons
loadRadioButtons();
// go back to main settings page
goBackToSettings.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent goBackToMainSettings = new Intent(getApplicationContext(), AppSettings.class);
goBackToMainSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goBackToMainSettings);
finish();
}
});
//Open new activity for setting passcode
setUpPasscode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setUpPasscodeActivity = new Intent(getApplicationContext(), SetupPasscode.class);
startActivityForResult(setUpPasscodeActivity, 2);
}
});
// Open new activity for setting up TouchID
setUpTouchID.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setupTouchIDActivity = new Intent(getApplicationContext(), SetupTouchID.class);
startActivityForResult(setupTouchIDActivity, 1);
}
});
// when clicked, all other buttons become unchecked and the state of the buttons are saved
usePasscodeSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForPasscode = doesUserHavePasscode();
// If true, user has a passcode setup
if (bCheckForPasscode)
{
usePasscodeSelection.setChecked(true);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up a passcode to enable this option.");
}
}
});
useTouchIDSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForTouchID = doesUserHaveTouchIDSetup();
// If true, user has TouchID setup
if (bCheckForTouchID)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(true);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up TouchID to enable this option.");
}
}
});
useNeitherSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(true);
saveRadioButtons();
}
});
}
// Open sharedpreferences and get the value that was saved there after setting up passcode using the same key 'string'
public boolean doesUserHavePasscode()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
String checkHashString = sharedPreferences.getString("hashed_password", null);
if (checkHashString == null)
{
return false;
}
else
{
return true;
}
}
// Open sharedpreferences and get the value that was saved there after setting up TouchID using the same key 'string'
public boolean doesUserHaveTouchIDSetup()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean bDoesUserHaveTouchIDSetup = sharedPreferences.getBoolean("doesUserHaveTouchIDSetup", false);
return bDoesUserHaveTouchIDSetup;
}
public void NoOptionSetPopup(View v, String message)
{
TextView closePopup;
TextView contents;
myDialog.setContentView(R.layout.no_option_setup_popup);
closePopup = (TextView) myDialog.findViewById(R.id.closePopupButtonID);
contents = (TextView) myDialog.findViewById(R.id.theMessageID);
contents.setText(message);
closePopup.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Close popup
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
myDialog.show();
}
// Callback method to get the boolean from SetupPasscode/SetupTouchID activity & override the method
// What is being done here is that after a passcode/TouchID has been setup, we automatically assume that the newly set-up authentication will want to be used by the user.
// The values being returned from the activities only happen when they're successfully done (passed all validation checks).
// We then automatically make the corresponding radio button selected (if passcode setup, then select the 'use passcode on startup' radio button)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
// Case for returning from SetupPasscode class
case 2:
// fetch the boolean value
boolean isDone = data.getBooleanExtra("isDone", false);
usePasscodeSelection.setChecked(isDone);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
// Case for returning from SetupTouchID class
case 1:
// fetch the boolean value
boolean isTouchIDSetup = data.getBooleanExtra("isTouchIDDone", false);
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(isTouchIDSetup);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
}
public void saveRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = sharedPreferences.edit();
editor.putBoolean("usePasscodeOption", usePasscodeSelection.isChecked());
editor.putBoolean("useTouchIDOption", useTouchIDSelection.isChecked());
editor.putBoolean("useNeitherOption", useNeitherSelection.isChecked());
}
public void loadRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
usePasscodeSelection.setChecked(sharedPreferences.getBoolean("usePasscodeOption", false));
useTouchIDSelection.setChecked(sharedPreferences.getBoolean("useTouchIDOption", false));
useNeitherSelection.setChecked(sharedPreferences.getBoolean("useNeitherOption", false));
}
}
I would suggest to overload the onResume method and checking the state of your radio buttons as that will be the last control where the flow will leave your activity.

Is it good practice or necessary to use a Service to use a Media Player in the backgound

Hello StackOverflow's users,
I'm developing a Music Player App for android. In my main activity when the user clicks on a song I start a new intent that displays PlayerActivity. In there, I initialize a MediaPlayer and all the other UI elements. When the user clicks the back button, I bring them back to the main activity and the song continues to play in the background. The same thing happens if they exit the application. Now I was wondering if it's fine to do something like this or if I should instead start a new Service for the MediaPlayer from the PlayerActivity class instead of doing it in there.
PlayerActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Bundle extras = getIntent().getExtras();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getWindow().setNavigationBarDividerColor(getResources().getColor(R.color.white));
}
playBtn = findViewById(R.id.btn_play);
artImage = findViewById(R.id.art);
remainingTimeLabel = findViewById(R.id.current_song_duration);
totalTimeLabel = findViewById(R.id.total_duration);
manager = MainActivity.getManager();
Song song = manager.getCurrentSong();
boolean wasCall = extras != null && extras.containsKey("call");
if (!wasCall && manager.hasStarted()) {
MediaPlayer mediaPlayer = manager.getMediaPlayer();
mediaPlayer.pause();
mediaPlayer.stop();
}
if (!wasCall) {
mp = MediaPlayer.create(this, Uri.parse(song.getPath()));
mp.setLooping(true);
mp.seekTo(0);
mp.setVolume(0.5f, 0.5f);
} else {
mp = manager.getMediaPlayer();
mp.setLooping(true);
mp.setVolume(0.5f, 0.5f);
}
totalTime = mp.getDuration();
artImage.setImageBitmap(Bitmap.createScaledBitmap(song.getIcon(), 250, 250, true));
totalTimeLabel.setText(createTimeLabel(totalTime));
songName = findViewById(R.id.songName);
songName.setText(song.getName());
songAuthor = findViewById(R.id.songAuthor);
songAuthor.setText(song.getArtist());
Toolbar toolbar = findViewById(R.id.player_top_bar);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
assert toolbar.getNavigationIcon() != null;
toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>MySound</font>"));
positionBar = findViewById(R.id.seek_song_progressbar);
positionBar.setMax(totalTime);
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
positionBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
LinearLayout layout = findViewById(R.id.player_control);
layout.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
new Thread(() -> {
while (mp != null) {
try {
Message msg = new Message();
msg.what = mp.getCurrentPosition();
handler.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
this.action = SongEndAction.REPEAT;
mp.start();
manager.setMediaPlayer(mp);
}
Here is a Music Service that I implemented in my book.
https://github.com/Wickapps/Practical-Android-MusicService
This implementation includes play, stop, and seek forward, but you could add other functions.
Service is the best architecture for future scalability.
There is a MainActivity.java which starts the service.
MusicService.java is the service implementation.
Hope this helps.
If you want your app to keep playing audio while it's in background ( like spotify ), then yes, it is a must to use a foreground service.
Unfortunately it's more complex than your current implementation.
This is a nice starting point : https://developer.android.com/guide/topics/media-apps/audio-app/building-an-audio-app

Wait for text to speech and music to complete before registering next onClick

I have several buttons that respond to an onClick. When the buttons are pressed, it triggers a text to speech that says the name of the button and some music that corresponds to the button. However, the app glitches because you can press a different button while the music and text to speech for one button are still running. Is there a way to wait for the text to speech and music to stop playing before allowing another click? Any help would be greatly appreciated!! Thanks a lot!!!
public void onClick(View view) {
Resources res = getResources();
Button btn = (Button) view;
final TextView tv = (TextView) findViewById(R.id.color_text);
textViewString = tv.getText().toString();
switch (view.getId()) {
case R.id.green_button:
String greenString = res.getString(R.string.Green);
tv.setText(greenString);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
tts.speak(greenString, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(greenString, TextToSpeech.QUEUE_FLUSH, null, null);
}
MediaPlayer green = MediaPlayer.create(this, R.raw.green);
green.start();
break;
case R.id.red_button:
String redString = res.getString(R.string.Red);
tv.setText(redString);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
tts.speak(redString, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(redString, TextToSpeech.QUEUE_FLUSH, null, null);
}
MediaPlayer red = MediaPlayer.create(this, R.raw.red);
red.start();
break;
It seems that you must invoke tts.shutdown() in onClick() and then create the other tts object.
public void onClick(View view) {
tts.shutdown();
tts = new TextToSpeech(context, listener)
/* your code */
}
you can put if statement that checks if tts object is playing , tts.isSpeaking() return boolean true if speaking.

togglebutton.isChecked() is not working?

I am working with an Arduino and trying use two toggle buttons to connect and enable the Arduino. I don't want to be able to press the enable button until I have connected the robot. Here is my main activity:
public class MainActivity extends Activity {
Arduino arduino = null;
ToggleButton enable, connect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton connect = (ToggleButton) findViewById(R.id.buttonConnect);
ToggleButton enable = (ToggleButton) findViewById(R.id.buttonEnable);
}
public void onToggleClicked(View view) {
switch(view.getId()) {
case R.id.buttonConnect:
boolean on = ((ToggleButton) view).isChecked();
if(on){
//Take the text from editText1 and make it the IP Address
EditText text = (EditText)findViewById(R.id.editText1);
String ip = text.getText().toString();
arduino = new Arduino(ip);
arduino.connect();
arduino.disable();
} else {
arduino.disable();
arduino.disconnect();
enable.setChecked(false);
}
break;
case R.id.buttonEnable:
boolean click = ((ToggleButton) view).isChecked();
if(click && connect.isChecked()) {
arduino.enable();
}else {
System.out.println("Not Connected");
enable.setChecked(False);
arduino.disable();
}
break;
default:
break;
}
}
I know the program is not reaching the else statement in the buttonEnable case because it is not printing out "Not Connected." I have also tried to use connect.isEnabled()in my if statement but that doesn't work either. Does anybody have answer? Thank you!
Try to set on click listener to attach the code execution to you button

Showing a message without closing actual dialog in Android

I've to do a pair of fixes to an Android app although I don't really know about Android, but I'm getting problems in something that I don't think should be that difficult, I just want that when an OK button is pressed and some conditions haven't been fulfilled it displays a message and keeps on the same screen until data is correct or the user cancels, but I've tried it for some time and whatever I try it always displays the message and after that a white screen appears, even trying to search for examples on the internet.
This is my code:
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(parms);
layout.setGravity(Gravity.CLIP_VERTICAL);
layout.setPadding(2, 2, 2, 2);
TextView tv = new TextView(this);
tv.setText("Es necesario rellenar los datos solicitados a continuación para poder realizar su primer canje");
tv.setPadding(40, 40, 40, 40);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(20);
EditText et = new EditText(this);
String etStr = et.getText().toString();
TextView tv1 = new TextView(this);
tv1.setText("Nombre completo");
EditText et2 = new EditText(this);
String etStr2 = et2.getText().toString();
TextView tv2 = new TextView(this);
tv2.setText("Teléfono");
final EditText et3 = new EditText(this);
String etStr3 = et3.getText().toString();
TextView tv3 = new TextView(this);
tv3.setText("Correo electrónico");
LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
tv1Params.bottomMargin = 5;
layout.addView(tv1,tv1Params);
layout.addView(et, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tv2,tv1Params);
layout.addView(et2, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tv3,tv1Params);
layout.addView(et3, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
alertDialogBuilder.setView(layout);
alertDialogBuilder.setTitle("hola");
// alertDialogBuilder.setMessage("Input Student ID");
alertDialogBuilder.setCustomTitle(tv);
// alertDialogBuilder.setMessage(message);
alertDialogBuilder.setCancelable(true);
// Setting Negative "Cancel" Button
alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
[more code here]
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
matcher = pattern.matcher(et3.getText().toString());
if (matcher.matches())
{
[more code here]
}
else
{
Toast.makeText( contexto, "Por favor, introduzca un e-mail válido", Toast.LENGTH_LONG).show();
}
Hope you can help me with this thing, as I would find pretty annoying to have to learn android from the beginning to make something that I've been able to do in another programming languages in 5 minutes or less without knowing them at all.
Create two instance variables or class varibles like this
private Toast toast;
private boolean stop = false;
Write a method called this
private void showInfiniteToast() {
stop = false;
Thread t = new Thread() {
public void run() {
try {
while (true) {
if (!stop) {
toast.show();
} else {
toast.cancel();
return;
}
sleep(1850);
}
} catch (Exception e) {
Log.e("Infinite Toast", "Error "+ e.getLocalizedMessage());
}
}
};
t.start();
}
Now in the oncreate create the toast and call this method
toast = Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG);
showInfiniteToast();
Now if you want to change the toast message use this
toast.setText("message");
To stop the toast call any of these
//Call anyone of them
stop = true;
toast.cancel();
To implement your own custom view use this
View mView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(R.layout.mylayout, null);
toast.setView(mView);
Here is the complete file
public class MainActivity extends Activity implements OnClickListener {
Button btnChange, btnStop, btnShow;
private Toast toast;
private boolean stop = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
btnChange = (Button) findViewById(R.id.btnChange);
btnChange.setOnClickListener(this);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(this);
toast = Toast.makeText(getApplicationContext(), "Test",
Toast.LENGTH_LONG);
showInfiniteToast();
}
private void showInfiniteToast() {
stop = false;
Thread t = new Thread() {
public void run() {
try {
while (true) {
if (!stop) {
toast.show();
} else {
toast.cancel();
return;
}
sleep(1850);
}
} catch (Exception e) {
Log.e("Infinite Toast", "Error "+ e.getLocalizedMessage());
}
}
};
t.start();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnShow:
showInfiniteToast();
break;
case R.id.btnChange:
toast.setText("Added");
break;
case R.id.btnStop:
stop = true;
toast.cancel();
break;
default:
break;
}
}
}
First of all create your layouts using xml and inflate the view like this:
LayoutInflater li = (LayoutInflater) <ACTIVITY_NAME>.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.<LAYOUT_NAME>, parent, false);
or
View view = li.inflate(R.layout.<LAYOUT_NAME>, null);
If there is no parent view to attach the inflated view to. Then you can edit objects in your view by doing:
EditText edit = (EditText) findViewById(R.id.edit1);
edit.setText("example");
Doing so just makes your code much more cleaner.
The methods: setPositiveButton, setNeutralButton and setNegativeButton are coded so that when they are pressed, the dialog will close after it has finished executing the code in the listener.
If your Android app is running on the main thread for over 5 seconds then the app will throw an error saying that the app is no longer responding. If you wished to do a long action then you should use an AsyncTask or a Service.
I believe you are wanting to have a progress bar of some kind. I will link you to a
tutorial that will show you how to acheive that side of things. Check here
Hopefully this points you in the right direction.
create a dialogBuilder, and override the negative and positive buttons, and on the click listeners do whatever you want. This will prevent the dialog from closing.
Like this:
Create the builder, intialize it, set it for eg:
builder.setView(view);
builder.setCancelable(false);
override the ondismiss listener, and onshow listener like:
builder.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(!errorFlag) {
dialog.dismiss();
}
}
});
builder.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = builder.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// write the logic here, and maintain a flag.
// if the flag is true then only dismiss the dialog else show another one
}
Override the negative button also.
show the builder using builder.show()

Categories