Verify if there is video signal in videoview - android

I have a project in which it plays IPTV. I would like to identify if there is video signal in order to show an alertdialog if there isn't signal. I could set a timer to wait for the signal to return, but I don't know how to identify if there is a signal or not. Could you please help me. I leave the code with which I am working. SdkVersion 22.
public class Television extends Activity {
VideoView videoView;
ImageView volmas, volmenos, voloff;
SeekBar seekbar;
TextView textview, tvvolumen;
AudioManager audioManager;
int i = 50;
int volumen = 7;
int volumenporcentaje;
Toast toast;
Exception e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_television);
try {
String canal = getIntent().getStringExtra("Canal");
volmas = (ImageView) findViewById(R.id.volmas);
volmenos = (ImageView) findViewById(R.id.volmenos);
voloff = (ImageView) findViewById(R.id.voloff);
tvvolumen = (TextView) findViewById(R.id.tvvolumen);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
e = null;
videoView = (VideoView) this.findViewById(R.id.videoViewTV);
videoView.setVideoURI(Uri.parse(canal));
videoView.requestFocus();
videoView.start();
voloff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
volumen = 0;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
}
});
volmas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (volumen < 15) {
volumen = volumen + 1;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
}
if (volumen >= 15) {
Toast.makeText(Television.this, "Volumen al máximo", Toast.LENGTH_SHORT).show();
}
}
});
volmenos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (volumen > 0) {
volumen = volumen - 1;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
}
if (volumen == 0) {
Toast.makeText(Television.this, "Volumen al mínimo", Toast.LENGTH_SHORT).show();
}
}
});
seekbar = (SeekBar) findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
} catch (Exception e) {
Errores.exception(e, this.getApplicationContext());
}
}

I recommend you to change your approach! Use Exomedia or Exoplayer library. They are very simple.
Depend on your choice, you can use their function to solve your problem :)

Related

counter timer is not stop even after finish the activity

I have a quiz app which has a timer for the whole game-activity where in you should answer as 20 questions and every qustion have 10 sec ..
after the assigned 20 is over, it will take you to the results activity which shows your score. even after calling score activity toast from main activty will show and score activity will open agian and again.
int score = 0;
int unanswer = 0;
int questionasked = 1;
int maxquestion = 20;
TextView first, operator, second, timeview;
Button A, B, C, D;
int ans = 0;
String t;
DecimalFormat df;
CountDownTimer mCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeview = findViewById(R.id.time);
A = findViewById(R.id.A);
A.setOnClickListener(this);
B = findViewById(R.id.B);
B.setOnClickListener(this);
C = findViewById(R.id.C);
C.setOnClickListener(this);
D = findViewById(R.id.D);
D.setOnClickListener(this);
first = findViewById(R.id.first);
second = findViewById(R.id.second);
operator = findViewById(R.id.operator);
df = new DecimalFormat("###.##");
starTimer();
fillValue();
}
main activity code
private void fillValue() {
if (questionasked > maxquestion)
showscore();
questionasked++;
int a = (int) (Math.random() * 50 + 1);
int b = (int) (Math.random() * 50 + 1);
int op = (int) (Math.random() * 4 + 1);
int buttonoption = (int) (Math.random() * 4 + 1);
char operatorcharter = '+';
switch (op) {
case 1:
ans = a + b;
operatorcharter = '+';
break;
case 2:
ans = a - b;
operatorcharter = '-';
break;
case 3:
ans = a * b;
operatorcharter = 'X';
break;
case 4:
ans = (a) / b;
operatorcharter = '/';
break;
//default:
//Toast.makeText(this,op+"",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(this,a+" "+operatorcharter+" "+b+" "+ans+" "+buttonoption,Toast.LENGTH_LONG).show();
operator.setText(operatorcharter + "");
first.setText(a + "");
second.setText(b + "");
t = df.format(ans);
int temp = 0;
switch (buttonoption) {
case 1:
A.setText(t);
break;
case 2:
B.setText(t);
break;
case 3:
C.setText(t);
break;
case 4:
D.setText(t);
break;
//default:
// Toast.makeText(this,buttonoption+" butt",Toast.LENGTH_SHORT).show();
}
for (int i = 1; i <= 4; i++) {
if (i == buttonoption)
continue;
temp = (int) (Math.random() * ans + 1);
if (temp == ans) ;
temp += 5;
String temp1 = df.format(temp);
if (i == 1)
A.setText(temp1 + "");
else if (i == 2)
B.setText(temp1 + "");
else if (i == 3)
C.setText(temp1 + "");
else if (i == 4)
D.setText(temp1 + "");
}
mCountDownTimer.start();
}
private void showscore() {
Intent i = new Intent(this, final_activity.class);
i.putExtra(Contact.maxquestion, maxquestion);
i.putExtra(Contact.score, score);
i.putExtra(Contact.unanswer, unanswer);
mCountDownTimer.cancel();
Toast.makeText(this, "new activity open", Toast.LENGTH_LONG).show();
startActivity(i);
this.finish();
}
#Override
public void onClick(View v) {
Button b = (Button) v;
String clickbuttonvalue = (String) b.getText();
if (clickbuttonvalue.equals(t))
score++;
//Toast.makeText(this,score+" "+clickbuttonvalue ,Toast.LENGTH_LONG).show();
mCountDownTimer.cancel();
fillValue();
}
public void starTimer() {
mCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timeview.setText("seconds remaining: " + millisUntilFinished / 1000);
Toast.makeText(MainActivity.this, "new" + millisUntilFinished / 1000, Toast.LENGTH_LONG).show();
}
public void onFinish() {
unanswer++;
fillValue();
}
}.start();
}
}
this is my code even after opening new activity and open new activity check method showscore()
plz, help!
You need to override the onDestroy method which will be triggered when the activity is finished(don't forget to add finish() after the startActivty()).
#Override
public void onDestroy() {
super.onDestroy();
mCountDownTimer.cancel();
}

Android Media Player did not open

I am developing an android application that opens a PDF file and extract its content using itext then convert the results to an audio file using TTS engine and finally open the audio file using Media Player.
The app works fine for me and I am able to view PDF files but I can't view the Media player. I need a way to view media player upon the PDF file like this pdf_activity.xml
here is my code for PDF Activity:
public class PDF_Activity extends AppCompatActivity {
private Button b1,b2,b3,b4;
private MediaPlayer mediaPlayer;
private double startTime = 0;
private double finalTime = 0;
private Handler myHandler = new Handler();;
private int forwardTime = 5000;
private int backwardTime = 5000;
private SeekBar seekbar;
private TextView tx1,tx2,tx3;
public static int oneTimeOnly = 0;
private TextToSpeech mTts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
//PDFVIEW SHALL DISPLAY OUR PDFS
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
//UNPACK OUR DATA FROM INTENT
Intent i = this.getIntent();
String path = i.getExtras().getString("PATH");
//GET THE PDF FILE
File file = new File(path);
if (file.canRead()) {
//LOAD IT
pdfView.fromFile(file).defaultPage(1).onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
Toast.makeText(PDF_Activity.this, String.valueOf(nbPages), Toast.LENGTH_LONG).show();
}
}).load();
try {
String parsedText = "";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
for (int page = 0; page < n; page++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, page + 1).trim() + "\n"; //Extracting the content from the different pages
}
reader.close();
HashMap<String, String> myHashRender = new HashMap();
String destFileName = path.concat(".wav");
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, parsedText);
mTts.synthesizeToFile(parsedText, myHashRender, destFileName);
} catch (Exception e) {
e.printStackTrace();
}
}
String pdfMediaPalyer = path.concat(".wav");
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
tx1 = (TextView) findViewById(R.id.textView2);
tx2 = (TextView) findViewById(R.id.textView3);
tx3 = (TextView) findViewById(R.id.textView4);
tx3.setText(file.getName());
try {
mediaPlayer.setDataSource(pdfMediaPalyer);
} catch (IOException e) {
e.printStackTrace();
}
seekbar = (SeekBar) findViewById(R.id.seekBar);
seekbar.setClickable(false);
b2.setEnabled(false);
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if (oneTimeOnly == 0) {
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
tx2.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
finalTime)))
);
tx1.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
startTime)))
);
seekbar.setProgress((int) startTime);
myHandler.postDelayed(UpdateSongTime, 100);
b2.setEnabled(true);
b3.setEnabled(false);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
b2.setEnabled(false);
b3.setEnabled(true);
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = (int) startTime;
if ((temp + forwardTime) <= finalTime) {
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(), "You have Jumped forward 5 seconds", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();
}
}
});
b4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = (int) startTime;
if ((temp - backwardTime) > 0) {
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(), "You have Jumped backward 5 seconds", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show();
}
}
});
}
private Runnable UpdateSongTime = new Runnable() {
public void run() {
startTime = mediaPlayer.getCurrentPosition();
tx1.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime)))
);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(this, 100);
}
};
}

Android playing video fullscreen in a new activity on button click

I'm streaming a video in my app, and it works fine.
The problem is that when I try to make it full screen (in a new activity or otherwise), the screen is blank.
I have tried doing it without starting a new activity, as suggested here:
In my main activity:
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isFS)
setContentView(R.layout.activity_full_screen_video);
else
setContentView(R.layout.activity_starting_point);
}
});
I've also tried opening it in a new activity (which I prefer):
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(StartingPoint.this, FullScreenVideo.class);
StartingPoint.this.startActivity(myIntent);
}
});
Where FullScreenVideo:
public class FullScreenVideo extends StartingPoint{
//private VideoView vv;
public FullScreenVideo(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
vv.start();
}
}
And activity_full_screen_video:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:background="#ff000000">
<VideoView
android:id="#+id/vv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And in my manifest:
<activity
android:name=".FullScreenVideo"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize" />
It doesn't show any error or crash, just a blank screen. Also, I'm not using the media controller, so answers without that would be appreciated :)
Edit::
StartingPoint:
public class PlayVid extends ActionBarActivity {
int play = -1;
int k;
int m = 0;
int where;
int pausePressed = 0;
int displaySub = 0;
String curSub = " ";
ArrayList<Stime> timeArray = new ArrayList<Stime>();
Button but;
Button butStop;
Button butSub;
Button butFS;
TextView subs, log;
VideoView vv;
ProgressBar pBar;
int isFS, space;
String srt = "00:00:01,478 --> 00:00:04,020\n" +
"VimeoSrtPlayer Example\n" +
"\n" +
"00:00:05,045 --> 00:00:09,545\n" +
"Support for <i>italic</i> font\n" +
"\n" +
"00:00:09,378 --> 00:00:13,745\n" +
"Support for <b>bold</b> font\n" +
"\n" +
"00:00:14,812 --> 00:00:16,144\n" +
"Multi\n" +
"Line\n" +
"Support ;)\n" +
"\n" +
"00:00:18,211 --> 00:00:21,211\n" +
"Fonts: DejaVu\n" +
"http://dejavu-fonts.org\n" +
"\n" +
"00:00:22,278 --> 00:00:25,678 \n" +
"END OF EXAMPLE FILE";
subParse sp = new subParse(this, srt);
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
pBar = (ProgressBar) findViewById(R.id.progressBar);
subs = (TextView) findViewById(R.id.subtitleBox);
log = (TextView) findViewById(R.id.logBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
vv.setVideoPath("#string/video_link");
String[] lines = {" \n", " \n"};
sp.parseSub(srt);
subs.setText("--Click Play to start--\n--Click on SUB to view subtitles--");
final String[] sub2 = log.getText().toString().split(System.getProperty("line.separator"));
final subHelper sob = new subHelper(this, sub2);
final onPauseHelper oph = new onPauseHelper();
final fsHelper fsh = new fsHelper(this);
final playHelper ph = new playHelper();
timeArray.add(new Stime(vv.getDuration(), 0));
but.setOnClickListener(new View.OnClickListener() {
long startTime = 0, trop = 0;
int space = 0;
public void onClick(View v) {
subs.setText(curSub);
fsh.space = space;
if (fsh.isFS == 1) {
//Chill
} else if (play == 0 || play == -1) {
vv.start();
pBar.setVisibility(View.VISIBLE);
if (vv.isPlaying()) {
startTime = Calendar.getInstance().getTimeInMillis();
pBar.setVisibility(View.INVISIBLE);
//Play
if (play == -1) {
sob.setDefaults();
}
oph.putAttr(3, startTime);
but.setText("||");
but.setTextColor(Color.parseColor("#ffaaaaaa"));
if (k < m) {
play = 1;
final Handler handler = new Handler();
final Runnable run = new Runnable() {
#Override
public void run() {
if (k < m && play == 1 && fsh.isFS == 0) {
if (pausePressed == 0) {
oph.putAttr(0, Calendar.getInstance().getTimeInMillis());
} else {
oph.putAttr(0, startTime);
where--;
}
//oph.nextPressed=Calendar.getInstance().getTimeInMillis();
if (space == 0) {
space = 1;
fsh.space = space;
play = sob.subPlay(startTime, 0);
fsh.play = play;
trop = (timeArray.get(k).getTime(1) - timeArray.get(k).getTime(0));
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
} else if (space == 1) {
space = 0;
fsh.space = space;
play = sob.subPlay(startTime, 1);
fsh.play = play;
trop = timeArray.get(k + 1).getTime(0) - timeArray.get(k).getTime(1);
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
k++;
}
oph.putAttr(1, Calendar.getInstance().getTimeInMillis());
pausePressed = 0;
sob.pp = 0;
oph.reset();
oph.done = 0;
} else if (k >= m && fsh.isFS == 0) {
final Runnable run = new Runnable() {
#Override
public void run() {
but.setText("↻");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
subs.setText("Play Again?");
handler.removeCallbacks(this);
play = -1;
fsh.play = play;
//ph.saveState(play,0,k,0,curSub,displaySub);
curSub = " ";
}
};
while (vv.isPlaying()) {
}
handler.postDelayed(run, 0);
}
}
};
if (k == 0)
handler.postDelayed(run, (timeArray.get(0).getTime(0)));
else if (k < m) handler.postDelayed(run, 0);
}
}
} else if (play == 1) {
//Pause
vv.pause();
oph.reset();
oph.putAttr(2, Calendar.getInstance().getTimeInMillis());
subs.setText(curSub);
pausePressed = 1;
oph.done = +oph.getProg();
sob.pp++;
but.setText("▶");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
if (k < m) {
if (space == 0) {
space = 1;
fsh.space = space;
} else if (space == 1) {
space = 0;
fsh.space = space;
}
play = sob.subPause(oph.getAttr(2));
fsh.play = play;
}
}
}
});
butStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vv.stopPlayback();
sob.setDefaults();
play = 0;
fsh.play = play;
but.setText("▶");
subs.setText("--Click Play to start--");
curSub = " ";
}
});
butSub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (displaySub == 0) {
displaySub = 1;
subs.setText(curSub);
butSub.setTextColor(Color.parseColor("#ffaaaaaa"));
} else if (displaySub == 1) {
displaySub = 0;
subs.setText(" ");
butSub.setTextColor(Color.parseColor("#ffcdcdcd"));
}
}
});
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(PlayVid.this, TwoFullScreenVideo.class);
PlayVid.this.startActivity(myIntent);
}
});
}
}
FullScreenVideo:
public class FullScreenVideo extends StartingPoint {
fsHelper fsh;
onPauseHelper oph;
subHelper sob;
playHelper ph;
protected PlayVid context;
TextView subs;
Button but, butStop, butSub, butFS;
public FullScreenVideo(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
subs = (TextView) findViewById(R.id.subtitleBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FullScreenVideo.this.finish();
}
});
}
}

My activity won't pause when dialog is shown

I have been working on application that displays a problem and 4 possible answers. Answer correctly, and the next problem appears. A wrong answer or letting the timer run out results in a popup that tells the correct answer and that you just lost a "life". Everything works well except that when the popup appears, the countdown timer continues and generates another popup. I can't find a way to get the activity to wait for the button on the dialog to be pressed before continuing to the next problem. I have read many questions/answers here and combed through many pages on the android developers site. Any help with this problem would be greatly appreciated.
public class MainActivity extends Activity {
String problems[][] = {{},{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"},
{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"}};
String answers[][] = {{},{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"},
{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"}};
public int level;
private int lister[] = {1,1,2,3,4};
Random rand = new Random();
int holder, probcount = 0, score = 0, lives = 5;
String problem, answer1, answer2, answer3, answer4, corrAnswer, l1, l2, l3;
boolean correct = false, changeBG = false, timeup = false, nolives = false, inpopup = false;
MyCount counter;
View lv, lf1, lf2, lf3, lf4, lf5;
MediaPlayer soundright, soundwrong;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
lv = findViewById(R.id.quizshow);
lf1 = findViewById(R.id.Life1);
lf2 = findViewById(R.id.Life2);
lf3 = findViewById(R.id.Life3);
lf4 = findViewById(R.id.Life4);
lf5 = findViewById(R.id.Life5);
Log.v("Events","onCreate");
soundright = MediaPlayer.create(this, R.raw.correct1);
soundwrong = MediaPlayer.create(this, R.raw.correct2);
Button btnAnswer1 = (Button)findViewById(R.id.Answer1);
btnAnswer1.setOnClickListener(onAnswer1);
Button btnAnswer2 = (Button)findViewById(R.id.Answer2);
btnAnswer2.setOnClickListener(onAnswer2);
Button btnAnswer3 = (Button)findViewById(R.id.Answer3);
btnAnswer3.setOnClickListener(onAnswer3);
Button btnAnswer4 = (Button)findViewById(R.id.Answer4);
btnAnswer4.setOnClickListener(onAnswer4);
Button btnExit = (Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(onExit);
Log.v("Events","onCreate2");
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
level = 1;
doNext();
}
protected void onResume() {
Log.d("Events", "onResume");
super.onResume();
}
protected void onPause() {
Log.d("Events", "onPause");
super.onPause();
counter.cancel();
}
protected void onDestroy() {
Log.d("Events", "onDestroy");
super.onDestroy();
}
private View.OnClickListener onAnswer1=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer1");
if (lister[1] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer2=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer2");
if (lister[2] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer3=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer3");
if (lister[3] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer4=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer4");
if (lister[4] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onExit = new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onExit");
finish();
};
};
private void doNext() {
if (changeBG == true) {
l1 = getResources().getString(R.string.LevelDone1);
l2 = getResources().getString(R.string.LevelDone2)+" "+String.valueOf(level);
l3 = getResources().getString(R.string.LevelDone3);
doPopup();
changeBG = false;
level = level + 1;
score = 0;
probcount = 0;
}
Log.v("Events", "DoNext1");
probcount = probcount + 1;
lister[0] = rand.nextInt(9);
holder = rand.nextInt(3);
lister[holder+1] = lister[0];
This is where I have boring code that makes sure that the 4 answers are different.
problem = problems[level][lister[0]];
TextView pr = (TextView) findViewById(R.id.Problem);
pr.setText(problem);
answer1 = answers[level][lister[1]];
TextView a1 = (TextView) findViewById(R.id.Answer1);
a1.setText(answer1);
answer2 = answers[level][lister[2]];
TextView a2 = (TextView) findViewById(R.id.Answer2);
a2.setText(answer2);
answer3 = answers[level][lister[3]];
TextView a3 = (TextView) findViewById(R.id.Answer3);
a3.setText(answer3);
answer4 = answers[level][lister[4]];
TextView a4 = (TextView) findViewById(R.id.Answer4);
a4.setText(answer4);
corrAnswer = answers[level][lister[0]];
if (probcount < 6){
counter = new MyCount(4000, 1);
} else if (probcount < 11) {
counter = new MyCount(3000, 1);
} else if (probcount < 21) {
counter = new MyCount(2500, 1);
} else if (probcount < 31) {
counter = new MyCount(2000, 1);
} else if (probcount < 41) {
counter = new MyCount(1500, 1);
} else if (probcount < 51) {
counter = new MyCount(1000, 1);
} else {
counter = new MyCount(750, 1);
}
counter.start();
}
private void doRight() {
Log.v("Events", "DoRight");
counter.cancel();
soundright.start();
if (probcount < 6){
score = score +10;
} else if (probcount < 11) {
score = score + 20;
} else if (probcount < 21) {
score = score +30;
} else if (probcount < 31) {
score = score +40;
} else if (probcount < 41) {
score = score + 50;
} else if (probcount < 51) {
score = score + 100;
} else {
score = score + 200;
}
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
if (score > 590) {
changeBG = true;
}
doNext();
}
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
private void doPopup() {
Log.v("Events", "DoPopup");
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
TextView ln1 = (TextView) dialog.findViewById(R.id.Line1);
TextView ln2 = (TextView) dialog.findViewById(R.id.Line2);
TextView ln3 = (TextView) dialog.findViewById(R.id.Line3);
ln1.setText(l1);
ln2.setText(l2);
ln3.setText(l3);
inpopup = true;
dialog.show();
Button dialogButton = (Button) dialog.findViewById(R.id.btnPopup);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inpopup = false;
dialog.dismiss();
}
});
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
timeup = true;
doWrong();
}
#Override
public void onTick(long millisUntilFinished) {
double TimeLeft = millisUntilFinished;
TextView timer1 = (TextView) findViewById(R.id.Timer);
timer1.setText(String.valueOf(TimeLeft/1000));
}
}
}
You have a repetitive loop insisde a timer...
Let say, when your timer is is finished, it will call onFinish() and you are calling doWrong() in onFinish(). and doWrong() is calling doPopUp() which will open a Dialog again.(repetitively). To avoid, maintain some flags(like boolean or int) and based on the value of the flag, you decide whether to show PopUp Dialog when timer is finished or cancel the Timer when you are dismissing Diaog...
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
// change here
if(!timeup)
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
I'm adding this answer to be able to mark the question as answered. Please read the comment I left after the question.
Thanks to all that provide help on this site. I have gained much knowledge here.

Stop Watch doesn't work in background mode

I have a stop watch, it work right, but when i press home button or button closing bell and reopen it after some time, I see wrong time in my stop watch. Tell me please what I can do to solve this problem ?
public class Stopwatch extends Activity {
Timer mTimer;
int second_f_p = 0, second_s_p = 0, millisecond = 0;
int minute_f_p = 0, minute_s_p;
int hour_f_p = 0, hour_s_p = 0;
int numberOfLap = 0;
TextView tv;
TextView TVlap;
Button btn_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
btn_start = (Button) this.findViewById(R.id.button1);
tv = (TextView) this.findViewById(R.id.tvTime);
btn_start.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View arg0) {
btn_start.setClickable(false);
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 100);
}
});
Button btn_stop = (Button) this.findViewById(R.id.button2);
btn_stop.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
btn_start.setClickable(true);
mTimer.cancel();
}
});
Button btn_reset = (Button) this.findViewById(R.id.button4);
btn_reset.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
second_f_p = 0;
second_s_p = 0;
minute_f_p = 0;
minute_s_p = 0;
millisecond = 0;
hour_f_p = 0;
hour_s_p = 0;
numberOfLap = 0;
TVlap.setText("");
tv.setText(String.valueOf(hour_f_p) + String.valueOf(hour_s_p) + ":" + String.valueOf(minute_f_p) + String.valueOf(minute_s_p) + ":" + String.valueOf(second_f_p) + String.valueOf(second_s_p) + "." + String.valueOf(millisecond));
}
});
TVlap = (TextView) this.findViewById(R.id.tvLap);
Button btn_lap = (Button) this.findViewById(R.id.button3);
btn_lap.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
numberOfLap++;
TVlap.setText(TVlap.getText() + String.valueOf(numberOfLap) + ". " + String.valueOf(hour_f_p) + String.valueOf(hour_s_p) + ":" + String.valueOf(minute_f_p) + String.valueOf(minute_s_p) + ":" + String.valueOf(second_f_p) + String.valueOf(second_s_p) + "." + String.valueOf(millisecond) + "\n");
}
});
}
private void timerMethod() {
this.runOnUiThread(doSomething);
}
private final Runnable doSomething = new Runnable() {#Override
public void run() {
millisecond++;
if (millisecond == 10) {
second_s_p++;
millisecond = 0;
}
if (second_s_p == 10) {
second_f_p++;
second_s_p = 0;
}
if (second_f_p == 6) {
minute_s_p++;
second_f_p = 0;
}
if (minute_s_p == 10) {
minute_f_p++;
minute_s_p = 0;
}
if (minute_f_p == 6) {
hour_s_p++;
minute_f_p = 0;
}
if (hour_s_p == 10) {
hour_f_p++;
hour_s_p = 0;
}
if (hour_f_p == 9 && hour_s_p == 9) {
second_f_p = 0;
second_s_p = 0;
minute_f_p = 0;
minute_s_p = 0;
hour_f_p = 0;
hour_s_p = 0;
}
tv.setText(String.valueOf(hour_f_p) + String.valueOf(hour_s_p) + ":" + String.valueOf(minute_f_p) + String.valueOf(minute_s_p) + ":" + String.valueOf(second_f_p) + String.valueOf(second_s_p) + "." + String.valueOf(millisecond));
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_stopwatch, menu);
return true;
}
}

Categories

Resources