I just want to make a quiz-kind of application where questions are asked & shown.
I am using the Android's default Text to Speech engine, instead of mediaplayer(I have no choice except tts plz...) .I am initializing tts & using it in mainmethod("switchingLogic()").
Now, My problem is : The sound of first question should be played on start of the activity.But tts is not playing that sound if I place my SWITCHINGLOGIC() in onCreate().So, I have Placed it in the onInit() of tts , Desired output is coming, but "when the screen is locked & Unlocked, it is starting from the first question again."
Now, how can I make my app to start from there only if app goes background or phone is Locked automatically.
public void playQuestions(String sound) {
tts.speak(sound, TextToSpeech.QUEUE_FLUSH, null);
}
public void switchingLogic() {
playQuestion(item.getSounds(1));
--------------------
--------------------
}
#Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
if (arg0 == TextToSpeech.SUCCESS) {
Log.d("Yes", "SUCCESS");
switchingLogic();
}
}
Disastrous Situation Please help me, this is new issue & wanna submit the app in 10 hours...
This is happening because android supports only one thread in foreground, so when you lock the screen and unlock, your application goes to background and the present state of your application will be lost... as you have used
playQuestion(item.getSounds(1));
It makes ur application to open again and start from 1st Question.
Related
I have an application that according to some events, changes a normal notification to text-to-speech in order to since sometimes the phone isn't available to users, and it'll be safer not to handle the phone.
For example, when you're driving, this is dangerous, so i want to turn the notifications to text-to-speech.
I've looked for a long time some explanation for turning text-to-speech when driving, but i can't find any reference for that no where i search.
For generating text-to-speech, i have this part, which works fine :
private TextToSpeech mTextToSpeech;
public void sayText(Context context, final String message) {
mTextToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
try {
if (mTextToSpeech != null && status == TextToSpeech.SUCCESS) {
mTextToSpeech.setLanguage(Locale.US);
mTextToSpeech.speak(message, TextToSpeech.QUEUE_ADD, null);
}
} catch (Exception ex) {
System.out.print("Error handling TextToSpeech GCM notification " + ex.getMessage());
}
}
});
}
But, i don't know how to check if i'm currently driving or not.
As Ashwin suggested, you can use Activity recognition Api, but there's a downside of that, the driving samples you'll receive, has a field of 'confidence' which isn't always accurate, so you'll have to do extra work(such as check locations to see if you actually moved) in order to fully know if the user moved.
You can use google's FenceApi which allows you to define a fence of actions such as driving, walking, running, etc. This api launched recently. If you want a sample for using it, you can use this answer.
You can pull this git project (everything free), which does exactly what you want : adds to the normal notification a text-to-speech when you're driving.
In order to know whether you are driving or not you can use Activity Recognition API
Here is a great tutorial that might help you out Tutorial and Source Code
I developed an android turn based game and so far I can make the first move but when I want the user would wait for the second player to play the app crashes.
What I tried to do is when the player finishes his move I call a function like this:
public void TheThread()
{
boolean fy=false;
while(!fy)
{
if(CheckMove2())
fy=true;
}
}
The checkmove2 function connects the parse table and check if is there a turn and return boolean.
I beleive this is not the right way to do it,thanks for your help.
Edit:
ChecKmove2() function:
private boolean CheckMove2() {
fx=false;
ParseQuery query = new ParseQuery("serverturn");
query.whereEqualTo("Receiver", Sender);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject updatePO, ParseException ParseError) {
if(ParseError == null){
fx=true;
String objID;
x=updatePO.getInt("x");
y=updatePO.getInt("y");
try {
updatePO.delete();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
///here comes the game algorithm.
if(fx)
return true;
return false;
}
Edit: the app not crashes its just stop and alert: "The app is not responding" and then asks if I want to wait or close the app.The checkmove function works perfectly I checked it with other devices,the problem is to use this checkmove function in a while loop so the user would wait for the opponent turn.
Your application is crashing because in that scenario you've caused an endless loop (if there are no other moves waiting). So the OS will, most likely force close your application because it thinks its become unresponsive.
What you're better off doing is this:
Create a background service with an AyncTask to check for other players moves at specific intervals (10 - 15 mins maybe?)
Once a move is found. Alert the player to it by using a Notification which would link to your app via an Intent
As a side note, you should always use background threads/async tasks etc to talk to networks.
On your place i would do next:
In parse cloudCode afterSave or beforeSave of the object you are waiting for, send a socket message to your app when the needed object is updated. For example using pubnub.com
I think this is a decent solution, but running some loopy checking logic seemes so unprofessional.
In general it works like this:
two players subscribe to a channel
when one finishes move, from cloud code send a message to this
channel
catch it in your app.
The message can trigger update from parse or can contain the needed data itself.
This question already has an answer here:
How to detect that music play in background
(1 answer)
Closed 4 years ago.
I need a simple demo, In which I want to check whether the music is running in the background or not? And also does not effected on the music which is running in Background
I read from here study Link
and made a demo code
Demo code is here but this is not giving me the O/P:
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
int result = am.requestAudioFocus(new OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
if(//background Music is running )
{}
else{
//background Music is not running
}
}
},AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
What is need to be add for what I want. Please help to make it east this thing.
The current code you've posted appears to be that you are actually requesting to use the STREAM_MUSIC stream rather than detecting it. I believe you may have two options for this.
I haven't tried is this method, but it sounds like AudioManager.isMusicActive() may work for you.
From this page, it says
Checks whether any music is active.
Returns true if any music tracks are active.
Your other option is to use AudioManager.OnAudioFocusChangeListener. You must first create this listener and then register it to detect changes. This means your app would need to be running in the background before another app started using the stream.
Create a listener (examples from http://developer.android.com/training/managing-audio/audio-focus.html)
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
// another app took the stream temporarily
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// another app let go of the stream
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// another app took full control of the stream
}
}
};
Now you can register the listener and detect changes
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// You successfully took control of the stream and can detect any future changes
}
This isn't a terribly elegant solution since you will most likely take away the music stream from other apps. It depends on your use case, but it may be a starting point.
all I am new to Android and now I am facing a strange problem, the problem in short is
"Receive TCP message and then change background color of GUI has no effect once screen has been rotated."
What I want to archive:
Have a APP running on Android device, connect to a PC via TCP.
PC can send a string to APP, the APP will then do something base on string received.
In this case a string, "change back ground color to red(with phone vibrates)/black" is send to APP via TCP, so Android user will see a blinding effect with vibration.
What is the problem:
I can archive what I want. But once the screen has been rotated, the color cannot be changed, only vibration remain.
What I had tried:
I put a button on the APP which will manually trigger color change event(with vibration). It works fine even if I rotate the screen.
Further test shows that UI operation such as change background color and animation triggered by TCP read are vanished, however ringtone and vibration remain unchanged.
I upload a video to Youtube http://youtu.be/n0gxXzzf-bo
Below are java code ,the button and TCP call same method: ChangeColor()
public void ChangeColor(){
Thread t= new Thread(new ChangeColorTest());
t.start();
}
public class ChangeColorTest implements Runnable{
public void run() {
try {
for(int i=0;i<3;i++){
mBlinkHandler.sendEmptyMessageDelayed(1, 0);
Thread.sleep(300);
mBlinkHandler.sendEmptyMessageDelayed(2, 0);
Thread.sleep(300);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Handler mBlinkHandler = new Handler(){
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
// mScreen = (LinearLayout)findViewById(R.id.mylinerlayout);
if(msg.what==1){
mScreen.setBackgroundColor(Color.RED);
Vibratoration();
}else if(msg.what==2){
mScreen.setBackgroundColor(Color.BLACK);
}
}
};
What I want to know?
If someone could possible figure out a solution, it would be much appreciated.
What is my platform?
Server PC: Win7 64bits VS2010 C#
Android platform: 4.0 Samsung S2
Development IDE:Motodev
SDK API: Android 3
One solution would be to lock the screen so it can't be rotated? (Or at least lock it during this functionality.)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Android will recreate the whole activity when you rotate the screen - so probably your variable "mScreen" won't point to the instance actually visible on the screen after rotation.
You can avoid, that android recreates the activity as explained here:
http://developer.android.com/guide/topics/resources/runtime-changes.html
I have been trying to get a bitmap screenshot of a SurfaceView for days but the more I look into it, there doesn't seem to be a solution at present for Android OS 2.3.4 based OSs my device from HTC.
So on to Plan B, where I just found out another blog: "On my HTC Evo 3d, all I have to do is hold the power button for 1-2 sec and then hit the home button and it takes a screen shot. No app required." Turns out this works perfectly on my tablet.
I also know from digging around there are these intents: android.intent.action.SCREEN_OFF & android.intent.category.HOME
(So I tried a bunch of code experiments to try to mimic the 2-key combo in code to get a screenshot in this brute force manor. Unfortunately without success).
So my ? -- Does anyone have any insights into a method to invoke this 'screenshot sequence' for my HTC device from java code? (Presume I need to fool the OS into thinking I am holding down the power key AND tap the Home key, simultaneously)...
More: Here is a snip of the code I am attempting:
Button click for test... ...
Thread t = new Thread() {
public void run() {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);
Instrumentation inst2 = new Instrumentation();
inst2.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
} // run
}; // thread t
Doesnt work as the inst.sendKeyDownUpSync is wrong as I need a sendKeyDown (& hold) behavior or its equivel
Many thanks for any advise. If I do get this working, I will post the solution here. Cheers GH
PS; I presume there is some custom intent under the hood doing this? Is there a system log somewhere to trey to peek at the call tree to find out what it is ?
EDIT (MORE)... 9/24/11
More. Still not working but I am heading down this path & think it is closer...
// Attempt to SIMULATE A Long press (DOWN) + HOME to tell the HTC to invoke the 'Screenshot' command (WARNING: HTC Tablet specific behavior!)
Thread tt = new Thread() {
public void run() {
final KeyEvent dapowerkey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER);
Handler onesecondhandler = new Handler();
onesecondhandler.postDelayed(new Runnable() {
public void run() {
// fpr about 1 second send power down keystrokes (DOWN ONLY)
while (true) { dispatchKeyEvent(dapowerkey); }
} // we are done running on the timer past time point
}, 750); // 3/4 second key press
// send the HOME keystroke
Instrumentation inst1 = new Instrumentation();
inst1.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
} // outer thread run tp mpt block the GUI
}; // outer thread t
tt.start();
...
Also thought if I can send the right intent directly to the proper place on the device that I might be able to kick off a screen capture function directly (which is what I really want. Through some log examinations (when you Long-Power + Home click on HTC) a program called 'com.htc.mysketcher' (FlashActivity) is being called...
Again, if I figure this out then I will post to the group... Cheers GH