I am developing a very simple flashlight application, while I have successfully achieved what I was looking for, I would like to perform it that way I want it to. Currently my flashlight remains on while my activity is active, as soon as I hit the home button to minimize the activity flashlight turns off. I want the flashlight to stay on and turn off only when I click the turn off button in my activity.
public class FlashLightActivity extends Activity {
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
/*
* First check if device is supporting flashlight or not
*/
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(FlashLightActivity.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) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
/*
* Switch button click event to toggle flash on/off
*/
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
/*
* Get the camera
*/
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());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(FlashLightActivity.this, R.raw.light_switch_off);
}else{
mp = MediaPlayer.create(FlashLightActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.on);
}else{
btnSwitch.setImageResource(R.drawable.off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
Related
I'm making flashlight application with handling Activity Life Cycle. The application is running fine but the problem occurs when i call onStop(); while flashlight is on ,when I return from the onStop();, the application should turn on flash light but it doesn't.
I have tried all the methods but the flashOn(); is not enabling the flashlight. I had checked from debugging that the application do nothing if the flashlight was on after returning from onStop();
public class MainActivity extends AppCompatActivity {
private ImageButton imagebtn;
ImageView img;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash = false;
private Camera.Parameters params;
private boolean flag= false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagebtn = (ImageButton) findViewById(R.id.button);
img = findViewById(R.id.torchimage);
isFlashOn = false;
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// If device doesn't support flash
// Show alert message and close the application
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();//Close application
}
});
alert.show();
}
imagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
flashOff();
} else {
flashOn();
}
}
});
}
protected void checkCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Toast.makeText(getApplicationContext(), "Camera not found", Toast.LENGTH_SHORT).show();
}
}
}
**protected void flashOn() {
if (!isFlashOn) {
{
if (camera == null || params == null) {
return;
}
/*if (flag==true) {
flag=false;
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
*/}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleImages();
btnSound();
}
}**
protected void flashOff() {
if (isFlashOn)
{
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleImages();
btnSound();
}
}
protected void btnSound() {
final MediaPlayer mp = MediaPlayer.create(this, R.raw.button_sound);
mp.start();
}
public void toggleImages() {
if (isFlashOn) {
imagebtn.setImageResource(R.drawable.button_on);
img.setImageResource(R.drawable.torch_on);
} else {
imagebtn.setImageResource(R.drawable.button_off);
img.setImageResource(R.drawable.torch_off);
}
}
#Override
protected void onDestroy() {
// Toast.makeText(this,"OnDestroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
if (isFlashOn)
flashOn();
else
flashOff();
}
#Override
protected void onRestart(){ super.onRestart();
if (isFlashOn==true)
flashOn();
else
flashOff();
}
#Override
protected void onResume() {
super.onResume();
if (isFlashOn == true)
flashOn();
else
flashOff();
}
#Override
protected void onStart() {
super.onStart();
// Toast.makeText(this,"OnStart",Toast.LENGTH_SHORT).show();
// if (hasFlash)
checkCamera();
}
#Override
protected void onStop() {
// Toast.makeText(this, "OnStop", Toast.LENGTH_SHORT).show();
super.onStop();
if (camera != null) {
camera.release();
camera = null;
flag= true;
}
}
Please look again at the Android lifecycle https://developer.android.com/guide/components/activities/activity-lifecycle.html
It goes onStop -> onRestart -> onStart -> onResume
You have an awful lot of crap spread all over the place making what should be easy to see, rather difficult.
So... the flash is on ie isFlashOn = true;
Remove the boolean == true from the if while you're at it. Just if (boolean) works and is much better.
onStop... camera = null; flag= true;
But isFlashOn is still true
Returned to Activity...
onRestart... if (isFlashOn==true) flashOn(); <--- It is, so going to flashOn()
flashOn() {
if (!isFlashOn) { <------------- No the boolean is still true so this isn't run... camera is null anyway.
onStart... checkCamera() {
if (camera == null) { <------ Yes, OK
onResume... if (isFlashOn == true) <----- Again same problem, so camera never starts.
Set isFlashOn = false in onStop
Also remove code from resume or restart... its just duplicated and going through the same thing twice.
Hopefully this teaches you how to debug better. Learn from it.
hello i try to develop an app which i should be able to scan in main activity and with intent i get the result in a textbox. My only problem is that when i scan the barcode SOMETIMES it opens the result activity 2-3 times.. Maybe someone could help me i dont know what to do
i dont know how i should help you
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 200);
}
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
cameraPreview = (SurfaceView) findViewById(R.id.cameraPreview);
cameraPreview.setZOrderMediaOverlay(true);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(24)
.setRequestedPreviewSize(1600, 1024)
.setAutoFocusEnabled(true)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
cameraSource.start(cameraPreview.getHolder());
}
}
catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#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> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0)
{
Intent intent = new Intent(MainActivity.this, finish.class);
intent.putExtra("barcode", barcodes.valueAt(0));
startActivityForResult(intent, 100);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
barcodeDetector.release();
}
FINISH ACTIVITY
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finish);
result = (TextView) findViewById(R.id.editText1);
final Barcode barcode = getIntent().getParcelableExtra("barcode");
result.setText(barcode.displayValue);
You probably don't want to setup in onCreate and teardown in onDestroy. If you do, the camera will still be active and scanning even after your activity has moved to the background. Use onResume and onPause instead.
The other issue you may be experiencing is that receiveDetections is called every time it detects a barcode (even if it's the same barcode). If the barcode detector can detect barcodes faster than the system can start an activity, the callback will be called multiple times before you release the camera and barcode detector. To prevent this, you can use a flag to prevent startActivity from being called more than once or you can release the barcode detector (and camera) from inside receiveDetections
What you can do is release barcode detector immediately after your barcode data is received.
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcode = detections.getDetectedItems();
if (barcode.size() != 0) {
barcodeDetector.release();
//......put your code here.....//
}
}
});
I am new in android development and learning android apps development. I have created a very basic and simple Flashlight for android device. I am facing the issue when i run the app it takes some time to run like if i press turn on flash light it will take some time (half sec or less but it take some time), i didn't use wait() method in my app. How to run it really fast like user click on it flash turn on or turn off?
public class MainActivity extends AppCompatActivity {
private ImageButton imageButton;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
private Camera.Parameters params;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.switch_btn);
//Check that Device has supports flash or not
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash){
//If device does not supports Flash
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your current device does not support to Little Flashy! ops");
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Close application
finish();
}
});
alert.show();
return;
}
//Get the Camera
getCamera();
//Display button image
toggleButtonImage();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else
{
turnOnFlash();
}
}
});
}
private void toggleButtonImage() {
if (isFlashOn){
imageButton.setImageResource(R.drawable.btn_switch_on);}
else {imageButton.setImageResource(R.drawable.btn_switch_off);}
}
private void getCamera() {
if (camera == null){
try{
camera = camera.open();
params = camera.getParameters();
}catch (RuntimeException e){
Log.d("Camera Error.", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
private void playSound() {
if (isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);}
else {
mp= MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
//turn off flash when on Pause called
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;
}
}
}
Before you turn the flash on and off, you call the playSound method, which uses the MediaPlayer. this method is slow and causes your delay. First try to remove it (by commenting it out) and see the difference. Next, you can try to run it from a thread.
Yes, you can ignore the sound feature for current time. Or if you really want this feature than use it through Thread it will show no lag or delay in your app while user turn on or turn off flash.
I want to update the changes when I uncheck and check the checkbox in the preference activity but when I press the back button it doesn't work. It only works when I close the activity and then open it
Main activity
public class MainActivity extends ActionBarActivity {
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
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) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake == true ){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake()
{ if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
}
else{
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
} }
});
}
}
private void getCamera() {
// TODO Auto-generated method stub
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;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Preference activity
public class Prefsetting extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefset);
}
}
You access SharedPreferences in the onCreate() of your MainActivity, which is only called when that activity is created from scratch (i.e. when you first start your app). As you (presumably) navigate to and from your Prefsetting Activity fairly quickly, MainActivity is likely only in a paused or stopped state when it is resumed. Take a look at the diagram here to see what happens to Activity classes as they move into and out of the foreground.
You have a couple of options. Either place this:
#Override
public void onResume() {
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
} else {
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
Into somewhere like onResume().
Or, use an EventBus like LocalBrodcastManager to update your Preferences when onPause() is called in your PreferenceActivity.
From the code snippet it appears that you never actually commit your changes to the SharedPreferences of the application. Somewhere in the code when that boolean is flipped you need to do something like this:
prefs.put("checkbox", currentBooleanState).commit();
I have created demo for media player in Android.I'm facing the problem while start to run my application.When my app is run song is playing but not playing the full song it just start and immediately finish means it just start activity and immediately goes to resume() state.And when song is get over the i again restart my activity song is not playing from beginning it start from middle.I'm facing this problem last 1 week and i don't understand how to solve it .Please can any one help me.Here is my code.Thanks in advanced.
public class Audio_Activity extends Activity
{
private MediaPlayer mp = null;
PhoneStateListener phListener;
int length;
SharedPreferences prefs;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences. Editor prefsEdit = prefs.edit();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.issaq_tera_by_vishu);
Log.e("Song is playing","in Mediya Player ");
mp.start();
mp.setLooping(false);
System.out.println("Media Plyer Is Start !!!");
prefsEdit.putBoolean("mediaplaying", true);
prefsEdit.commit();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
System.out.println("Media Plyer Is Complete !!!");
//mp.release();
prefsEdit.putBoolean("mediaplaying", false);
prefsEdit.commit();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener()
{
#Override
public void onCallStateChanged(int state, String incomingNumber)
{
if (state == TelephonyManager.CALL_STATE_RINGING)
{
if(mp!=null)
{
setPlayerButton(true, false, true);
if(mp.isPlaying())
{
mp.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null)
{
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void setPlayerButton(Boolean play, Boolean pause, Boolean stop){
btnStartStop.setEnabled(play);
if(play==true)
btnStartStop.setEnabled(true);
else
btnStartStop.setEnabled(false);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onPause()
{
super.onPause();
SharedPreferences. Editor prefsEdit = prefs.edit();
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = mp.getCurrentPosition();
Log.e("Current ","Position -> " + position);
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
mp.start();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onStop();
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
System.out.println("Media Player is Pause/Stop click on Back button on Emulator!!!");
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
the starting from middle of the song problem is because you store the current progress of song in SharedPreferences and then at onResume() you start the player from the progressed position that stored at SharedPreferences
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
Official guide:
http://developer.android.com/guide/topics/media/mediaplayer.html
Please try to use bellow code.
void play() {
mediaPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.keytone);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
private void pause()
{
mediaPlayer.release();
}