Android method is not running - java

It has been a long time since I stopped by this problem: my FileObserver's onEvent method is not triggered, tested, and not even the "method entered" toast is being displayed.
FileObserver fileObserver = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "method entered", Toast.LENGTH_SHORT).show();
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
Help me please! Thanks in advance.

Check existence of file prev, it should cause issue.
public void startWatching ()
Added in API level 1 Start watching for events. The monitored file or
directory must exist at this time, or else no events will be reported
(even if it appears later). If monitoring is already started, this
call has no effect.

Related

UtteranceProgressListener not called

I'm trying to take some action after a TextToSpeech object in my Android app finishes speaking a sentence, but my UtteranceProgressListener.onDone() method is never called. I tried many things, including the suggestions from this post, but nothing has worked. Relevant code from my app is posted below. The TextToSpeech object correctly speaks the sentence I give it, but none of the callback functions in UtteranceProgressListener are called. Can someone please help me identify what's wrong? For example, should the utterance ID I provide to the TextToSpeech.speak() function need to be in some special format that I'm missing?
mtts = new TextToSpeech(myAct, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
mtts.setLanguage(Locale.US);
}
}
});
mtts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onDone(String utteranceId) {
Toast.makeText(myAct, "OnDone called", Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
Toast.makeText(myAct, "OnError called", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(String utteranceId) {
Toast.makeText(myAct, "OnStart called", Toast.LENGTH_LONG).show();
}
});
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
myAct.mtts.speak(myText, TextToSpeech.QUEUE_FLUSH, params, "MyID");
Look at logcat, your code has probably fired: android.view.ViewRootImpl$CalledFromWrongThreadException
If you want to do some GUI-thread stuff, use handler and runnable like this:
public void onDone(String utteranceId) {
Log.v(TAG, "Speaking done"); // this is OK
// This is GUI-thread part
final View v = findViewById(R.id.txtStatus);
v.getHandler().post(new Runnable() {
#Override
public void run() {
txtStatus.setText("Speaking done");
}
});
}
And to start TTS speaking:
tts.speak("bla bla bla", TextToSpeech.QUEUE_FLUSH, null, "1");
If you want to add the call back UtteranceProgressListener, you have to give TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID as the utteranceId
It would look like this:
myAct.mtts.speak(myText, TextToSpeech.QUEUE_FLUSH, null, TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
See this post:
UtteranceProgressListener does not return error message
and check the engine web site: TTS Engine

Is there such a thing as too many chromecast devices on one network?

I have an app that uses the CastCompanionLibrary and I'm having a weird issue. On a small network with one chromecast device my application is able to detect it and show the MediaRouterItem.
Although, I had a beta tester say that they were not able to get any of their devices detected, so the icon never shows up for them. Come to find out they are connected to a larger, shared network with multiple chromecast devices connected to it. They said that they are able to detect all of the chromecast devices with other apps such as YouTube and Localcast though. Which is weird because that leads me to believe that maybe I'm not doing something right with the discovery process.
Unfortunately, I am not in a position where I can have a network with multiple chromecast devices to debug this issue, so I was just wondering if anyone else had a similar issue? Or is there a certain method that you have to call with the CastCompanionLibrary that I'm missing?
EDIT
I am using the APP_ID that has been published, so I know that it isn't a whitelisting issue.
The code I use for discovery is completed by the CastCompanionLibrary. This is what I use once the onCastDeviceDetected() callback is called:
mCastConsumer = new VideoCastConsumerImpl() {
#Override
public void onFailed(int resourceId, int statusCode) {
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended() was called with cause: " + cause);
}
#Override
public void onConnectivityRecovered() {
}
#Override
public void onCastDeviceDetected(final MediaRouter.RouteInfo info) {
if (!MyApplication.isFtuShown(Home.this)) {
MyApplication.setFtuShown(Home.this);
Log.d(TAG, "Route is visible: " + info);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mediaRouteMenuItem.isVisible()) {
Log.d(TAG, "Cast Icon is visible: " + info.getName());
//showFtu();
}
}
}, 1000);
}
}
};
MyApplication.class:
public static boolean isFtuShown(Context ctx) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
return sharedPref.getBoolean(FTU_SHOWN_KEY, false);
}
public static void setFtuShown(Context ctx) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
sharedPref.edit().putBoolean(FTU_SHOWN_KEY, true).commit();
}

Waiting for X time in loop using JAVA/Android

In my code i want to check longitude and latitude value. If values are empty, code will check for 15 seconds. If values are received , while loop will break and will show "You win". If they are still empty, it should show "error in gps" after 15 seconds.
The problem is that code is waiting perfectly but Progress Bar is not showing in the screen because screen got stuck during wait time. After 15 seconds screen is free. Please tell me how to resolve this issue. Thanks
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), longitude.getText(), Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), latitude.getText(), Toast.LENGTH_LONG).show();
pBar = new ProgressDialog(oproprietor.this);
pBar.setCanceledOnTouchOutside(false);
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pBar.setMessage("Waiting 15 seconds");
pBar.show();
long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
if(!longitude.getText().equals("") || !latitude.getText().equals("") ){
pBar.dismiss();
break;
}
else continue;
}
if(longitude.getText().equals("") || latitude.getText().equals("")){
pBar.dismiss();
Toast.makeText(oproprietor.this, "Error in gps", Toast.LENGTH_LONG).show();
}
else if(!longitude.getText().equals("") || !latitude.getText().equals("") ){
pBar.dismiss();
Toast.makeText(oproprietor.this, "You win", Toast.LENGTH_LONG).show();
}
}
});
Since this is Android, I would definitely recommend using an AsyncTask over a thread. This question has all the relevant details on how to do this safely. Using a Java thread/Runnable introduces some UI issues in android when you are interacting with the UI thread from the external thread.
Try running it in a thread.
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
#Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
}
});
}
}).start();

Use UI thread to display toast messages?

I have a listener that is getting updates from a separate process. (I'm using IPC.)
Log.i("Test1", Thread.currentThread().toString()); // Thread[Binder_3,5,main]
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("Test2", Thread.currentThread().toString()); // Thread[main,5,main]
switch (taskId) {
case Constants.DOWNLOAD_TASK_EXECUTED: {
long time = prefs.getLong(Constants.LAST_UPDATED_KEY, System.currentTimeMillis());
String msg = Utils.getLastUpdatedString(res, time, Locale.getDefault(), false);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
break;
}
case Constants.DELETED_TASK_EXECUTED: {
String msg = res.getString(R.string.delete_success);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
break;
}
}
}
});
Is it necessary to call the runOnUiThread method and pass in a Runnable to display toast messages when I get updates? Or is it okay to just display them in the same thread (Binder_3)? I'm not modifying anything in the UI.
Tost Or Log Work in thread or other processes (but it's better to NOT Risk ! ) but Changing the UI must always Run in UI thread as you told with runOnUiThread or using handler
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
My Professional Android 4 Application Development book states, "Toasts must be created and shown on the GUI thread; otherwise, you risk throwing a cross-thread exception."

Unexpected behavior: immediate completion of media player

I am trying to restore audio to the position it was and the file it was when the user left the fragment. To do this I save the location of the audio file, and the seek position using personal prefs, along with a boolean for whether or not the audio was playing when the user left. I save this info first thing in onPause().
When I resume, I initialize the views etc. and the very last thing I do in onResume is read from personal prefs and play the audio stored there is appropriate.
However when I try to play from onResume, the media completion listener gets called immediately and the file gets skipped.
I have been running tests and I know that the media player is handed the right data, is prepared correctly and set to play.
The way I am trying to play the audio is the same way I do it if a user clicks manually to play audio, and that works flawlessly.
Only when trying to 'restore' the audio to where it was when a user left does the completion listener get called immediately.
Has anyone seen this before?
public void setAudioURLAndPLay(Context context, String url)
{
Log.d(TAG, "setAudioURLAndPLay");
CacheQueue.getInstance().addImmediateTaskToQueue(CacheQueue.AUDIO_TASK, context, url, 0, handler);
}
private void playCahcedFile(String location)
{
Log.d(TAG, "playCahcedFile");
try
{
this.reset();
this.setAudioStreamType(AudioManager.STREAM_MUSIC);
this.setDataSource(location);
this.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
setPlay();
}
});
this.prepareAsync();
}
catch (Exception e)
{
Log.d(TAG, "Exception", e);
}
}
public void setPlay()
{
Log.d(TAG, "setPlay");
this.start();
this.setProgressHandler(this.listener);
}
and where the calls are being made
public void initializeFromResume()
{
PersonalPrefs prefs = new PersonalPrefs(getActivity());
if (!prefs.isPLaying())
{
return;
}
else
{
playNewAudio(prefs.getURL());
// ((ActivityMain) getActivity()).getMediaManager().setSeek(prefs.getSeek());
}
}
private void playNewAudio(String url)
{
getMediaManager().setAudioURLAndPLay(getActivity(), url)
mediaState = MediaState.playing;
initializeSeekBar();
getMediaManager().setOnCompletionListener(this);
mediaController.togglePlayButton(mediaState);
}
I figured it out and will post the answer to anyone who has similar troubles in the future.
Just need to run a post delayed. Not exactly amazing, but it works.
h.postDelayed(new Runnable()
{
#Override
public void run()
{
PersonalPrefs prefs = new PersonalPrefs(getActivity());
playNewAudio(prefs.getURL());
}
}, 1000);

Categories