Music player - activity lifecycle - android

I have really hard time with background music in my app. I just want to play music in all activities - when I press home button I want to stop music. I want "stop or play" music button in all activities, but couldnĀ“t make it work.
So I decided to make embarassing choice - play it only in 1 activitiy by
onCreate
backgroundmusic = MediaPlayer.create(StoryActivity.this, R.raw.creepy_music);
backgroundmusic.start();
onPause
#Override
protected void onPause() {
super.onPause();
backgroundmusic.release();
finish();
}
Can you please help me with easy activity lifecycle? So when a user presses home button - music will stop. When he will come back to app - music will be restored and this activity too (it is not MainActivity)
Thank you, guys

Here are the different LifeCycle states. Now to your answer,
#Override
protected void onStop() {
super.onStop();
backgroundmusic.pause();
length = backgroundmusic.getCurrentPosition();
}
#Override
protected void onResume() {
super.onResume();
backgroundmusic.seekTo(length);
backgroundmusic.start();
}
In public class MainActivity extends AppCompatActivity, It's the AppCompatActivity that is the main source of an Activity's functionality, hence in the above methods like super.onResume(); and super.onStop(); super refers to the AppCompatActivity class

assume that you can get the music service in the Application ,you may be looking for this :
public class MyApp extends Application{
MusicService musicService;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
if(musicService==null) return;
if(!musicService.isPlaying()){
musicService.play();
}
}
#Override
public void onActivityPaused(Activity activity) {
if(musicService==null) return;
if(musicService.isPlaying()){
musicService.pause();
}
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
}
Hope this helps

Related

FLAG_SECURE Not preventing Screen shot in Android 12

FLAG_SECURE Not Working with Android 12.
Code is given below which is used in my APP. It work till Android 11 but on Android 12 I can Take screen shots(when app is either in foreground or while App is in the(displayed in Task list) background . Please Suggest If there is any other work around available.
No one should be able to take screen shot while App is Background but displayed in open Apps List.
public class MyApplicationContext extends Application {
private Context context;
public void onCreate() {
super.onCreate();
context = getApplicationContext();
setupActivityListener();
}
private void setupActivityListener() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); }
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
}

how to check if android going to recreate activity or destroy?

I have an android studio project. When I am rotating screen, android destroys and recreates main activity. How can I check during the destruction, if android going to recreate activity?
You can determine if the activity is finishing by user choice (user chooses to exit by pressing back for example) using isFinishing() in onDestroy.
#Override
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
// wrap stuff up
} else {
//It's an orientation change.
}
}
Another alternative (if you're only targeting API>=11) is isChangingConfigurations.
#Override
protected void onDestroy() {
super.onDestroy();
if (isChangingConfigurations()) {
//It's an orientation change.
}
}
Override the Activity lifecycle methods to see the flow.And then use the appropriate method to check activity current state like isChangingConfigurations()
Example code snippet.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Log.i(MainActivity.class.getSimpleName(),"OnStart Called");
}
#Override
protected void onRestart() {
super.onRestart();
Log.i(MainActivity.class.getSimpleName(),"OnRestart Called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i(MainActivity.class.getSimpleName(),"OnDestroy Called");
}
#Override
protected void onPause() {
super.onPause();
Log.i(MainActivity.class.getSimpleName(),"OnPause Called");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i(MainActivity.class.getSimpleName(),"OnConfiguration Changed Called");
}
}
For more details see the official page activity-lifecycle

How Sign out to loginActivity when user inactive using common method for all activities in Android

In my application i want to sign out to loginActivity after 3 min when user inactive
i am currently use this code to do that but in my application there is more than 20 activities
so without pasting this bunch of code every activity i want common method to do that,
please help me
Here is the my code
public class HomeActivity extends AppCompatActivity {
private Handler handler;
private Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
handler = new Handler();
r = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
Toast.makeText(HomeActivity.this, "Logged out after 3 minutes on inactivity.", Toast.LENGTH_SHORT).show();
}
};
startHandler();
}
public void stopHandler() {
handler.removeCallbacks(r);
}
public void startHandler() {
handler.postDelayed(r, 3 * 60 * 1000);
}
#Override
public void onUserInteraction() {
super.onUserInteraction();
stopHandler();
startHandler();
}
#Override
protected void onPause() {
stopHandler();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
startHandler();
Log.d("onResume", "onResume_restartActivity");
}
#Override
protected void onDestroy() {
super.onDestroy();
stopHandler();
}
}
Define a class like
public class BaseActivity extends AppCompatActivity {
// Write logic of logout same as what you wrote in HomeActivity
}
Now extend this BaseActivity to each activities which meant to show after login. like
public class HomeActivity extends BaseActivity {
// Remove code related to logout from this class.
}
You can make a BaseActivity Class here you can implement your functionality.
And then extend this activity with all your Activities.
Also you can use Application Class to control over the app

How to play music only in foreground

I have trouble to play music across all activity, I had implement service and handle onPause to stop the music when going to background (not visible to user).
The problem is when i navigate to another activity, the onPause method is called that make my music stop. How to fix this issue? I need to play my music across all my activity in foreground only and dont wan to play it when the application in the background. Appeciate anyone know how to solve this.
This is my base activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startIntent = new Intent(getApplicationContext(), MusicService.class);
if(binder==null){
bindService(startIntent,this, Context.BIND_AUTO_CREATE);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(binder.getMyService()!=null){
stopService(startIntent);
unbindService(this);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
super.onPause();
if(binder!=null) {
binder.getMyService().pauseMusic();
}
}
#Override
protected void onResume() {
super.onResume();
if(binder!=null){
binder.getMyService().resumeMusic();
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MusicService.Binder) service;
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
this is my mainactivity extends base activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startIntent = new Intent(MainActivity.this, MusicService.class);
startService(startIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public void how(View view) {
Intent intent = new Intent(this, AboutActivity.class);
this.startActivity(intent);
}
You could implement code that will track current activity in your app. (Good example: How to get current activity)
And stop music only when "current activity" is null.
PS: depending on your implementation of tracking current activity you might want to check current activity not onPause() right away but with some delay .
Don't stop the audio play in onPause() as Harin Kaklotar suggested. You can use his method of onDestroy() or you can have it in an asynchronous task and turn off the sound by using surfaceDestroyed(). You can refer the android documentation of AudioManager if you need anything else of the sort.
https://developer.android.com/reference/android/media/AudioManager.html
Hope I Helped :D
UPDATE
You can create a system to check if your app is in the foreground or background. This involves counting how many activities are paused. Add this to all your activities:
#Override
protected void onPause() {
super.onPause();
MainActivity.Pause++;
}
#Override
protected void onResume() {
super.onResume();
MainActivity.Pause--;
}
And in your MainActivty,
if (Pause == NUMBER_OF_ACTIVITIES) {
//PAUSE MUSIC HERE
}
You have to use ActivityLifecycleCallbacks to tell if you app is in the foreground or background.
For example:
public class DummyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
#Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { }
#Override public void onActivityStarted(Activity activity) { }
#Override public void onActivityResumed(Activity activity) { }
#Override public void onActivityPaused(Activity activity) { }
#Override public void onActivityStopped(Activity activity) { }
#Override public void onActivityDestroyed(Activity activity) { }
#Override public void onActivitySaveInstanceState(Activity activity, Bundle savedInstanceState) { }
}
public class OnApplicationForegroundBackgroundEnterCallbacks extends DummyActivityLifecycleCallbacks {
private Listener listener;
private int activityStartStopCounter = 0;
public interface Listener {
public void onEnterForeground();
public void onEnterBackground();
}
public OnApplicationForegroundBackgroundEnterCallbacks(Listener listener) {
this.listener = listener;
}
#Override public void onActivityStarted(Activity activity) {
if(++activityStartStopCounter == 1) listener.onEnterForeground();
}
#Override public void onActivityStopped(Activity activity) {
if(--activityStartStopCounter == 0) listener.onEnterBackground();
}
}
Then in Application.onCreate call:
registerActivityLifecycleCallbacks(new OnApplicationForegroundBackgroundEnterCallbacks(this));

Killing process in onPause()

I want to kill my Activity process when I pause it by answering a call or something like that
but when i try to start my app it closes instantly. Any solutions? Sample code below
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Things to do
}
//#Override
public void onPause() {
super.onPause();
android.os.Process.killProcess(android.os.Process.myPid());
}
You should implement a logical scenario based on activity's lifecycle methods.
update your code with
#Override
public void onPause() {
super.onPause();
this.finish();
}

Categories

Resources