Hi guys i am trying to study Android on my own,but stuck with the problem.There are four buttons in a page and if i click one button other button's will not work.This is a code for flashlight,I am trying to make it blink for the required time.Its blinking properly but if i click a button other button won't work.Can anybody give me the suggestion for this problem.Here is the code:
MainActivity.java
Camera camera;
boolean isFlashOn;
boolean hasFlash;
Parameters params;
Button flashOn, flashOff, button1, button2, button3, button4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFlashlight();
getCamera();
initFlashlightButton();
}
void checkFlashlight() {
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(
MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
}
private void blink(int time) {
do {
turnOnFlash();
try {
sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
turnOffFlash();
try {
sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
blink(time);
} while (time <= 10);
}
private void initFlashlightButton() {
flashOn = (Button) findViewById(R.id.buttonOn);
flashOff = (Button) findViewById(R.id.buttonOff);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
flashOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
turnOnFlash();
}
});
flashOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOffFlash();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnFlash();
blink(1000);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnFlash();
blink(500);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnFlash();
blink(300);
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
blink(100);
}
});
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) return;
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
return;
}
}
// flash OFF
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) return;
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
return;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
if (hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
getCamera();
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
activity_main.xml:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="On"
android:id="#+id/buttonOn"
android:layout_marginLeft="62dp"
android:layout_marginStart="62dp"
android:layout_marginTop="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Off"
android:id="#+id/buttonOff"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:layout_alignTop="#+id/buttonOn"
android:layout_toRightOf="#+id/buttonOn"
android:layout_toEndOf="#+id/buttonOn" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2 Seconds"
android:id="#+id/button1"
android:layout_marginTop="164dp"
android:layout_below="#+id/buttonOn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4 seconds"
android:id="#+id/button2"
android:layout_alignTop="#+id/button1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8 seconds"
android:id="#+id/button3"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="60dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="16 Seconds"
android:id="#+id/button4"
android:layout_alignBottom="#+id/button3"
android:layout_alignLeft="#+id/buttonOff"
android:layout_alignStart="#+id/buttonOff"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2" />
Instead of adding new OnClickListener() separately to each button, add implements OnClickListener to your Activity class and add the corresponding void:
#Override
Public void onClick(View v){
int id = v.getId();
switch(id){
case R.id.yourbutton1:
//do your job here
break;
case R.id.yourbutton2:
//do your second job here
break;
}
}
So instead of adding new OnClickListeners just do this for each button:
button.setOnClickListener(this);
Your blink method specify do - while loop which says it should continue blink while time is less than or equal to 10. But i believe this is not what you want to achieve. I believe you want the flash to keep blinking until you press 'stopFlash' button.
For this you have to create a boolean in your activity that lets you know maybe you should stop the flash and use it in your while loop.
Step 1 create a global boolean in your Activity:
protected boolean should_continue_flash;
Step 2 Use it in your do - while loop
private void blink(int time) {
do {
turnOnFlash();
try {
sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
turnOffFlash();
try {
sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
blink(time);
} while (should_continue_flash);
}
Step 3 Add code to make your boolean return false so you can stop blinking
Under your onClick(View v) method
case R.id.stop_blink_button:
should_continue_flash = false;
Step 4 add this to your button that initiates blink:
should_continue_flash = true;
blink(your_time_here);
Hope this helps
now my code looks like this. please check this.#Oluwatumbi
Camera camera;
boolean isFlashOn;
boolean hasFlash;
Parameters params;
Button flashOn, flashOff, button1, button2, button3, button4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flashOn = (Button) findViewById(R.id.buttonOn);
flashOff = (Button) findViewById(R.id.buttonOff);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
checkFlashlight();
getCamera();
initFlashlightButton();
}
void checkFlashlight() {
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(
MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
}
private void blink(int time) {
do {
turnOnFlash();
try {
sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
turnOffFlash();
try {
sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
blink(time);
} while (isFlashOn);
}
private void initFlashlightButton() {
flashOn.setOnClickListener(this);
flashOff.setOnClickListener(this);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) return;
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
return;
}
}
// flash OFF
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) return;
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
return;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
if (hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
getCamera();
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
#Override
public void onClick(View v) {
int id=v.getId();
switch (id){
case R.id.buttonOn:
turnOnFlash();
break;
case R.id.buttonOff:
isFlashOn=false;
turnOffFlash();
break;
case R.id.button1:
isFlashOn=true;
blink(1000);
break;
case R.id.button2:
isFlashOn=true;
blink(500);
break;
case R.id.button3:
isFlashOn=true;
blink(300);
break;
case R.id.button4:
isFlashOn=true;
blink(100);
break;
}
}
}
In your activity create a Timer object so you can use and reuse
Timer timer;
In your blink() method initialize timer and simulate blink like this:
timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
YourActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
//Do the blinking job here
}
});
}
}, 0, your_time_interval_here);
And to stop blink:
timer.cancel();
timer.purge();
This should work for you
Documentation here:
Open Declaration void java.util.Timer.schedule(TimerTask task, long
delay, long period)
public void schedule (TimerTask task, long delay, long period) Added
in API level 1 Schedule a task for repeated fixed-delay execution
after a specific delay.
Parameters
task the task to schedule.
delay amount of time in milliseconds before first execution.
period amount of time in milliseconds between subsequent executions.
Throws IllegalArgumentException if delay < 0 or period <= 0.
IllegalStateException if the Timer has been canceled, or if the task
has been scheduled or canceled.
Hope this helps
Related
I am trying to make a multiplayer (2 people) turn based game which lets users do whatever they want in 60 seconds. Added Timer and TimerTask to my project. When playing first time all is good, but when I return to main screen (previous intent) with something like exit game button and re-enter game counter seems to be running like twice. Instead of going like 60-59-58 it goes like 60-58-55-53 and so on. Should I do something to stop counter while exiting game?
Here is my code:
public class ikinciekren extends AppCompatActivity{
....
#Override
public void onBackPressed()
{
...
...
cikisonay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kullanici.status(mDatabase,"lose");
Intent intocan = new Intent(ikinciekren.this, MainActivity.class);
intocan.putExtra("firebaseuser", facebookname);
intocan.putExtra("firebaseuid", myuid);
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
startActivity(intocan);
}
});
cikisiptal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
...
...
// On button click opponents timer starts to run
btn = (Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView number = (TextView) findViewById(R.id.textView4);
String number2 = number.getText().toString();
if(number2!=null ||number2!=""){
if (number2.length()==4) {
status =false;
resetSomeTimer();
launchSomeTimer();
...
...
}
}
}
});
...
...
ValueEventListener postListener2 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
String turn = String.valueOf(dataSnapshot.getValue());
//Read a node in firebase database and acts according to that
if ("true".equals(turn)) {
status =true;
}
if ("false".equals(turn)) {
status =false;
}
resetSomeTimer();
launchSomeTimer();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Context context = getApplicationContext();
Toast.makeText(context, "Failed to load post.",
Toast.LENGTH_SHORT).show();
}
};
...
...
}
protected void onDestroy(){
super.onDestroy();
///// added this just incase
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
kullanici.status(mDatabase,"off");
finish();
}
public void cikis(View view) {
if(view.getId()==R.id.button3){
...
...
cikisonay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
...
...
///// added this just incase
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
startActivity(intocan);
}
});
cikisiptal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
...
}
}
private void launchSomeTimer() {
runstatus=true;
oppenenttimertext.setText("60");
owntimertext.setText("60");
sayac =60;
counter = new TimerTask() {
#Override
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run () {
sayac--;
if (status) {
owntimertext.setText(String.valueOf(sayac));
} else {
oppenenttimertext.setText(String.valueOf(sayac));
}
if (sayac == 0) {
myTimer.cancel();
kullanici.timenotice(mDatabase);
}
}
});
}
};
myTimer = new Timer();
myTimer.schedule(counter,1000,1000);
}
public void resetSomeTimer(){
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
}
}
I make an app to read barcode. I use surfaceview and camerasource on it. I want to show the result in activity dialog and when come back restart surfaceview and camera source so I add setTheme in the first line in onCreate Method like this
setTheme(android.R.style.Theme_DeviceDefault_Light_Dialog);
The problem is the first activity appears in black screen how to show first activity and I want to show the other parts of first activity under the dialog box
this is the whole on create method code for the first activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.cameraPreview);
txtShow = (TextView) findViewById(R.id.txtShow);
startBarcode();
}
public void startBarcode() {
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(800, 600)
.setAutoFocusEnabled(true)
.build();
//Events
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
txtShow.post(new Runnable() {
#Override
public void run() {
//stop camera
cameraSource.stop();
//create vibrate
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
//set result for Text View
txtShow.setText(qrCodes.valueAt(0).displayValue);
final String code = txtShow.getText().toString();
// surfaceView.setTop(200);
Intent intent = new Intent(MainActivity.this,InfoActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("code",code);
startActivity(intent);
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.barcode);
mp.start();
My application contains one mediaplayer with one (play/pause) button in audio.xml , but the problem is that I am not able to find right code to stop MediaPlayer before the page gets destroyed and because of that the app crashes when i log in audio page (xml) and quit without running mediaplayer , here is the code i used:
public class audio extends Langue implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
// private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
//stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
//stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.espoir);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("Play");
} else {
mp.start();
startMedia.setText("Pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
/* if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("Play");
seekBar.setProgress(0);
}
}
*/
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// stop song
#Override
protected void onPause(){
super.onPause();
mp.stop();
finish();
}
}
Do something like this into the onPause() method for preventing crash
try{
mp.stop();
} catch(Exception e) {
}
finish();
How do I pass a URL to Media player? I have this code:
public class MainActivity extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://radioo.cz/wplay/2850");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
But it doesn't work... How do I set the url if I want to play this (http://www.radioo.cz/wplay/2850) radio? What am I doing wrong?
I have to admit I never used this class before but from what i found here : http://developer.android.com/reference/android/media/MediaPlayer.html
Instead of using
MediaPlayer.setDataSource(Uri)
you should use
MediaPlayer.create(Context context, Uri uri)
Which would be in your case :
player.create(this,"http://www.radioo.cz/wplay/2850");
I hope this can help you.
I create App like-karaoke. But , When my app playing mp3/aac over 1 minute. These text i created is not display. However setText(); under 1 minute is display normally. How can i fix that. I must send teacher tomorrow. Code's be simple. Thank you very much.
public class Okkaraoke extends Activity implements MediaPlayerControl,OnClickListener {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
Handler mHandler = new Handler();
public static TextView subtitles2,subtitles21;
#SuppressLint("HandlerLeak")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.myapp2);
subtitles2 = (TextView) findViewById(R.id.subs2);
subtitles21 = (TextView) findViewById(R.id.subs21);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this)
mMediaController.setMediaPlayer(Okekaraoke.this);
mMediaController.setAnchorView(findViewById(R.id.AudioView2));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Next button clicked
Intent intent = new Intent(Okkarake.this, Show1.class);
startActivity(intent);
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
// Previous button clicked
Intent intent = new Intent(Okkaraoke.this, Main.class);
startActivity(intent);
}
});
try {
mMediaPlayer.setDataSource(this, Uri
.parse("android.resource://com.app.suadmon/raw/sorry"));
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final int currentPos = mMediaPlayer.getCurrentPosition();
if (mMediaPlayer.getCurrentPosition() < 28715) {
subtitles2.setText("Let's start");
subtitles21.setText("...................");
}else if(mMediaPlayer.getCurrentPosition()< 33134) {
subtitles2.setText("Oh my god");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition() < 39811) {
subtitles2.setText("function is green");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 44294) {
subtitles2.setText("Working..");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 50940) {
subtitles2.setText("Normally");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 55387) {
subtitles2.setText("Text can show normally");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 103807) {
subtitles2.setText("Working");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()<108173) {
subtitles2.setText("Text is not show up from here !");
subtitles21.setText("Text's not Display");
} else if(mMediaPlayer.getCurrentPosition()< 112646) {
subtitles2.setText("All text from here can't show");
subtitles21.setText("Text's not Display");
} else if(mMediaPlayer.getCurrentPosition()< 119555) {
subtitles2.setText("TextView din't show up");
subtitles21.setText("Text's not Display");
} else if (mMediaPlayer.getCurrentPosition()< 130356) {
subtitles2.setText("..................");
subtitles21.setText("Text's not Display");
} else if (mMediaPlayer.getCurrentPosition()< 138812) {
subtitles2.setText("************");
subtitles21.setText("Text's not Display");
} else if (mMediaPlayer.getCurrentPosition()< 147369) {
subtitles2.setText("Text's not Display");
subtitles21.setText("*************");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
// mMediaPlayer.reset();
mMediaPlayer.start();
}
});
}
});
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Intent newAc = new Intent(Okkaraoke.this, Show.class);
startActivity(newAc);
}
});
}
I have music 03.45 minute. In handleMassege().
I try final int/long sPos = mMediaPlayer.getCurrentPosition(); too. But, it's not work. setText is same as code above. Thank you very much.