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();
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.
I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
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;
}
}
}
I'm trying to used sharedpreferences for when a user chooses a specific custom image they want in their storage for a part of a grid of images. I want the image they chose to show up even after they close the application and reopen it. The problem I'm having is that the sharedpreferences don't seem to be working. Nothing shows up as the background image for the grid item they've selected once they've closed the app or even just pressed the back button.
Do I have to create a sharedpreferences file myself? I can't figure out how to get to it or create one if so using androidstudio.
Here's my code for the class (Sorry if it's long and messy...I am new to coding and still testing things):
public class editCreations extends Activity {
public int mPosition = 0;
protected static Sounds sound = new Sounds();
private static int RESULT_LOAD_IMAGE = 1;
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String mOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
private Drawable mImageFileName;
private Button recordBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private ImageButton imgBtn;
private Drawable bg;
private String mPicturePath;
private ImageAdapter img = new ImageAdapter(this);
View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(editCreations.this, "test", Toast.LENGTH_SHORT);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(mOutputFile);
recordBtn = (Button)findViewById(R.id.create_record_button);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start(view);
}
});
stopBtn = (Button)findViewById(R.id.create_stop_record_button);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stop(view);
}
});
playBtn = (Button)findViewById(R.id.create_play_button);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play(view);
}
});
stopPlayBtn = (Button)findViewById(R.id.create_stop_button);
stopPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopPlay(view);
}
});
imgBtn = (ImageButton)findViewById(R.id.imageButton);
Intent extra = getIntent();
Bundle extras = extra.getExtras();
// gave mPosition a default int to debug and find problem -> found it
mPosition = extras.getInt("position");
getSelectedFile(mPosition);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
public void start (View view) {
try {
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recordBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(editCreations.this, mPosition + "!", Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
stopBtn.setEnabled(false);
recordBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void play(View view) {
try{
mPlayer = new MediaPlayer();
mPlayer.setDataSource(mOutputFile);
mPlayer.prepare();
mPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void getSoundPosition(int position) {
mOutputFile = mOutputFile + "/Lollatone_clip_" + mPosition + ".3gpp";
// use to get proper image and sound files and edit output file to proper name
}
public void getSelectedFile(int position) {
switch (mPosition) {
case 0:
imgBtn.setBackgroundResource(R.drawable.sample_0);
imgBtn.refreshDrawableState();
break;
case 1:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 2:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 3:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 4:
imgBtn.setBackgroundResource(R.drawable.sample_4);
imgBtn.refreshDrawableState();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_creations, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPicturePath = cursor.getString(columnIndex);
cursor.close();
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
// String picturePath contains the path of
// selected image
}
}
protected void onPause() {
super.onPause();
//need an editor object to make preference changes
// all objects are from android.context.Context
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("img_" + mPosition, mPicturePath);
editor.commit();
}
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mPicturePath = sharedPref.getString("img_" + mPosition, "img_" + mPosition);
}
}
You are using SharedPreferences correctly but you are not placing the code in the right activity lifecycle methods. You are reading the preference on onCreate() and saving on onStop() so maybe what you can do it save the preference on onPause() (to make sure it gets saved earlier) and reload on onResume() instead of onCreate() (the latter only occurs once in the life cycle of an activity).
Also, you might want to check if Context.getSharedPreferences() would be a better choice for this, since it's shared between more than just one activity.
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();
}