Difficulty between intents in Java (Android Studio) - java

I am a beginner and I started by creating a radio app that has many stations but I have one problem.
When I hit "Play" for the radio, it starts playing then I come back to the precedent activity (stations list) and when I come back again to the same radio that is playing and hit "Pause" it diffuses "Not Playing". (I made a toast so that when I hit "Pause" while the radio is not playing it diffuses "Not Playing") but the radio is still "Playing".
Here is the code for the 2 buttons (Play and Pause):
btnPlayMFM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isOnline() == true) {
if (isPlaying() == false) {
Toast t = Toast.makeText(MosaiqueFM.this, "Loading \nPlease Wait", 10000);
t.show();
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(stream_url);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else if (isPlaying() == true) {
Toast t2 = Toast.makeText(MosaiqueFM.this, "Playing", 2000);
t2.show();
}
}
if (isOnline() == false){
Toast t = Toast.makeText(MosaiqueFM.this, "Internet Connection Required", 3000);
t.show();
}
}
});
btnPauseMFM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying() == true) {
mediaPlayer.stop();
} else if (isPlaying() == false){
Toast t = Toast.makeText(MosaiqueFM.this, "Not Playing", 2000);
t.show();
}
}
});
public boolean isPlaying() {
return(mediaPlayer != null && mediaPlayer.isPlaying());
}
public boolean isOnline() {
cm = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

If you have two activities - one more showing stations list and another for play/pause a particular radio station then apparently when you'll leave the second activity , your activity will get destroyed and mediaPlayer will become null and so , when you'll come back, isPlaying() will be false.
And that's why you are getting this Toast-
Toast t = Toast.makeText(MosaiqueFM.this, "Not Playing", 2000);
Suggestion - For these kind of apps, you don't want the radio to stop when the user leaves your app. So I suggest you use service for play purpose.

Related

How Can Show InterAd After X Clicks?

How can show the interstitial ads after 2 button clicks in this code java ?
"Lastes SDK Admob 20.2.0"
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"Button 1 Clicked");
if (mInterstitialAd != null) {
save_id(btn1.getId());
mInterstitialAd.show(main_activity.this);
}
else {
Log.d("TAG", "The interstitial ad wasn't ready yet");
Intent intent = new Intent(main_activity.this, getstarted.class);
startActivity(intent);
}
}
});
You can store a variable like clickCount and everytime its even value ie. modulo by 2 == 0 you could show the ad right?
int clickCount = 0;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"Button 1 Clicked");
clickCount++;
if (mInterstitialAd != null && (clickCount % 2 == 0)) {
clickCount = 0;
save_id(btn1.getId());
mInterstitialAd.show(main_activity.this);
}
else {
Log.d("TAG", "The interstitial ad wasn't ready yet or the button was only clicked once");
Intent intent = new Intent(main_activity.this, getstarted.class);
startActivity(intent);
}
}
});

Why turning on flash change the focus mode of the camera?

I have 2 AF Focus Distance can be control by button and an On Off switch for flash.
Why IF ELSE for flashligh in updatePreview() will affect focus mode to auto? When I comment out that part (IF ELSE for flashligh), AF mode and Focus distance work fine with the btnFocus.
How to solve this while still can allow user to turn on and off the flashlight?
private float focusDistance = 0;
private int flashSwitch = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = (TextureView)findViewById(R.id.textureView);
//From Java 1.4 , you can use keyword 'assert' to check expression true or false
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
btnFocus = (Button)findViewById(R.id.btnFocus);
btnFlash = (Button)findViewById(R.id.btnFlash);
btnFocus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
changeFocus();
}
});
btnFlash.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Flash();
}
});
}
private void Flash() {
if(cameraDevice == null)
return;
if(flashSwitch == 0 ) {
Toast.makeText(MainActivity.this, "Flash Turn On ", Toast.LENGTH_SHORT).show();
flashSwitch = 1;
}
else{
Toast.makeText(MainActivity.this, "Flash Turn Off ", Toast.LENGTH_SHORT).show();
flashSwitch = 0;
}
createCameraPreview();
}
private void changeFocus() {
if(cameraDevice == null)
return;
if(focusDistance == 0 )
focusDistance = 10;
else
focusDistance = 0;
Toast.makeText(MainActivity.this, "Focus Change "+ focusDistance, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
private void createCameraPreview() {
try{
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(),imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if(cameraDevice == null)
return;
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Changed", Toast.LENGTH_SHORT).show();
}
},null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
If you uncomment part the problem will come out when turn on flash and change focus.
private void updatePreview() {
if(cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
try{
// if you uncomment this part the problem will come out
// if(flashSwitch == 0){
// captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
// }
// else{
// captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
// }
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_OFF);
captureRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, focusDistance);
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),null,mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Expected Output
Can manually turn on and off flash without affecting focus mode.
I think that your problem might be on the way you set the requests.
You should create the preview first and only once, the way you have it, you are creating a preview everytime you switch flash and/or focus.
I suggest to create the preview in onStart with some defaults like:
focusDistance = 0;
flashSwitch = CaptureRequest.FLASH_MODE_OFF;
And then in Flash() and changeFocus() instead of calling createCameraPreview() you call updatePreview(), your update preview would look something like this:
private void updatePreview() {
if(cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
try{
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, flashSwitch);
captureRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, focusDistance);
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),null,mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
In updatePreview(), you're sending multiple capture requests to cameraCaptureSessions before settling all keys in captureRequestBuilder. Trying setting all keys first and then sending one repeating capture request.
private void updatePreview() {
if(cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
try{
if(flashSwitch == 0){
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
}
else{
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
}
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_OFF);
captureRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, focusDistance);
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),null,mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}

Keep user logged in but exit android app on double pressing back

I am using Firebase to sign in the user and have implemented the code to exit the app on double click. But the problem is the same screen is popping up again.
I tried a workaround setting a SharedPreference and then checking that in mAuthListner. But it did not work.
Here are the relevant sections of the code:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
SharedPreferences d= getSharedPreferences("backPressed", Context.MODE_PRIVATE);
Boolean t = d.getBoolean("back",false);
if (firebaseAuth.getCurrentUser() != null && !t) {
startActivity(new Intent(MainActivity.this, Second.class));
}
if (t) {
d.edit().putBoolean("back",false);
}
}
};
Code for back button pressed:
boolean doubleBackToExitPressedOnce = false;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
SharedPreferences d= getSharedPreferences("backPressed",Context.MODE_PRIVATE);
d.edit().putBoolean("back",true);
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
How can I exit the app on back pressed twice while keeping the user logged in?
This is not a Firebase issue as Firebase will not log out until you specifically call the "Log Out" method.
You do not need SharedPreferences. Just set an Activity level variable BackOnce to False then set it in the OnBackPressed as necessary.
boolean BackOnce = false;
#Override
public void onBackPressed() {
if (BackOnce) {
finish();
} else {
BackOnce = true;
Snackbar sb = Snackbar.make(myView, "Press back again to close app", Snackbar.LENGTH_SHORT);
sb.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
BackOnce = false;
}
});
sb.show();
}
}

How to play next song on completion of a song?

I am trying to create a media player. For that I am trying to play next song on completion of previous one. Here is my code:
int i = 0;
public void track(View view) {
while (!m1.isPlaying()) {
play(list.get(i));
while (m1.isPlaying()) ;
i++;
}
}
public void play(String T) {
try {
m1.setDataSource(T);
m1.prepare();
m1.start();
} catch (IOException e) {
Toast toast = Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT);
toast.show();
}
}
What you are looking for is setOnCompletionListener. This allows you to get a callback from the MediaPlayer when the playback is finished. You can start the next track in there:
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
void onCompletion(MediaPlayer mp){
//play next track
play(mNextTrack);
}
})
See Android documentation for more details.

Confirm closing the app on back pressed ONLY in MainAcitity?

I want the user to confirm closing my app. I use the following code for that in my MainActivity:
#Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}
In other classes I use this:
#Override public void onBackPressed() {
if (!mWebView.onBackPressed()) { return; }
// ...
super.onBackPressed(); }
Now I get the confirm event in EVERY class, but I only want it in my MainActivity. How can I do that?
Note: I have to extent my MainActivity in other classes. That should be the main problem to solve, but I still dont know how exactly?
#Vala, If your adding fragments to the Activty, then you can make use BackSackEntryCount of FragmentManager like below.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackCount == 1) {
Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG).show();
}
if backstackcount is one, it means, on pressing the back button again, remaining frgament will be popped from back stack and app will be quit.
Try using this
in your main activity
private boolean exit = false;
#Override
public void onBackPressed()
{
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
Try like this
Activity activity = this;
if (activity instanceof MainActivity) {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
Toast toast = Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
} else {
super.onBackPressed();
}
change other class to
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) { return; }
// ...
super.onBackPressed();
}

Categories

Resources