Android studio close application

How to detect Android application open and close: Background and Foreground events.

Dec 17, 2017 · 4 min read

This question seems to come up a lot. Especially if you are just starting out with Android developme n t. It’s simply because there is nothing obvious built into the Android SDK enabling developers to hook into application lifecycle events. Activities and Fragments have all the callbacks under the sun to detect lifecycle change, but there is nothing for the whole application. So how do you detect when a user backgrounds and foregrounds your app. This is an example of how your could detect Application lifecycle events. Feel free to adjust and enhance it to suit your needs, but this idea should be enough to work for most applications with one caveat, it will only work for Android API level 14+(IceCreamSandwich 🍦🥪).

Detecting App Lifecycle Evnts

Backgrounding

ComponentCallbacks2 — Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the onTrimMemory method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.

Foregrounding

ActivityLifecycleCallbacks — We can use this to detect foreground by overriding onActivityResumed and keeping track of the current application state (Foreground/Background).

Implementing a Foreground and Background Handler

First, lets create our interface that will be implemented by a custom Application class. Something as simple as this:

Next, we need a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2 we discussed earlier. So lets create an AppLifecycleHandler and implement those interfaces and override the methods required. And lets take an instance of the LifecycleDelegate as a constructor parameter so we can call the functions we defined on the interface when we detect a foreground or background event.

We outlined earlier that we could use onTrimMemory and the TRIM_MEMORY_UI_HIDDEN flag to detect background events. So lets do that now.

Add this into the onTrimMemory method callback body

So now we have the background event covered lets handle the foreground event. To do this we are going to use the onActivityResumed. This method gets called every time any Activity in your app is resumed, so this could be called multiple times if you have multiple Activities. What we will do is use a flag to mark it as resumed so subsequent calls are ignored, and then reset the flag when the the app is backgrounded. Lets do that now.

So here we create a Boolean to flag the application is in the foreground. Now, when the application onActivityResumed method is called we check if it is currently in the foreground. If not, we set the appInForeground to true and call back to our lifecycle delegate ( onAppForegrounded()). We just need to make one simple tweak to our onTrimMemory method to make sure that sets appInForeground to false.

Now we are ready to use our AppLifecycleHandler class.

AppLifecycleHandler

Now all we need to do is have our custom Application class implement our LifecycleDelegate interface and register.

And there you go. You now have a way of listening to your app going into the background and foreground.

This is only supposed to be used as an idea to adapt from. The core concept using onTrimMemory and onActivityResumed with some app state should be enough for most applications, but take the concept, expand it and break things out it to fit your requirements. For the sake of brevity I won’t go into how we might do multiple listeners in this post, but with a few tweaks you should easily be able to add a list of handlers or use some kind of observer pattern to dispatch lifecycle events to any number of observers. If anyone would like me to expand on this and provide a multi listener solution let me know in the comments and I can set something up in the example project on GitHub.

Читайте также:  Дорожные знаки 2016 для андроид

Update: Using Android Architecture Components

Thanks to Yurii Hladyshev for the comment.

If you are using the Android Architecture Components library you can use the ProcessLifecycleOwner to set up a listener to the whole application process for onStart and onStop events. To do this, make your application class implement the LifecycleObserver interface and add some annotations for onStop and onStart to your foreground and background methods. Like so:

Источник

Android studio close application

When the project is already opened in android studio and the same time Another project is opened in android studio then use the Reopen project. When the project work is done in android studio then use the Close project and When all project is complete in android studio then use the Save All.

How to Reopen, Close and Save project in Android Studio

How to Reopen the project in Android Studio perform the following steps:

Step 1: Firstly, Click on File then Click on Reopen Project and choose the file which file you want to be opened. We choose “My Application” file.


Step 2: After that a message box will be shown on your computer screen. This will show project will be opened in “This Window” or “New Window”. We open the project in “New Window” and After that your project will be opened.

How to Close project in Android Studio:

Step 1: Click on File then Click on Close Project and your project will be closed.

How to Save project in Android Studio:

Step 1: Click on File then Click on Save All and your project will be saved. You can also use ctrl+S shortcut.

Источник

Different ways to get Context in Android

Context is one of the important and most used property. You need Context to perform a lot of things on Android. Be is displaying a toast or Accessing database, you use context a lot while building Android app.

Context is property, well, which can give you the context of whats happening on the Screen/Activity it belongs to. It contains information about what Views are there, How they are laid out etc.

So, it is important to know different types of Context and methods you can call to get context. Lets get started.

The “this” Keyword

The this keyword in general sense refers to current class instance. So, when use “this” keyword inside an Activity, it refers to that Activity instance. And as Activity is subclass of “Context”, you will get context of that activity.

If you are not directly inside Activity, for example inside an OnClickListener, you can get the current context by referencing with Activity name like MainActivity.this (Java) or this@MainActivity (Kotlin)

Get current activity context : View.getContext()

This method can be called on a View like textView.getContext() . This will give the context of activity in which the view is currently hosted in.

Get App-level context : getApplicationContext()

If you need to access resources which are out of scope of specific activity, like when accessing SharedPreferences, displaying Toast message etc. you can use this.

So unlike activity context, which will be destroyed when close an activity, Application Context the application wide context which won’t get destroyed until you completely close application.

You can directly access application context by calling getApplicationContext() or by calling on activity context like context.getApplicationContext()

Читайте также:  Fm тюнер для андроид что это такое

Get Original context : getBaseContext()

This method is only useful when you are using ContextWrapper. You can get the original context which was wrapped by ContextWrapper by calling contextWrapper.getBaseContext()

( ContextWrapper is a wrapper class, using which you can override any method of Context, while still retaining the original context)

Get Context from Fragment : getContext()

When you call getContext() from an Fragment, you will get the context of the activity in which that fragment is hosted in.

Get parent Activity : getActivity()

You can get the parent activity from a Fragment by calling getActivity() .

💡Difference : Both getContext() and getActivity() are not much different in most cases, when you just need a context as both will get Parent activity context. Except for some cases, for example when using ContextWrapper, getContext() and getActivity() can point to different contexts.

Non-nullable Context : requireContext() and requireActivity()

These methods are same but “NotNull” versions of getContext() and getActivity() respectively. Usually, if a fragment is detached from Activity, you will get “null” value when you call getContext() or getActivity() . So even when you are sure the context won’t be null, you still have to add null checks (especially in Kotlin) because they return Nullable type.

But requireContext() and requireActivity() will throw IllegalStateException instead of returning null, if there is no context.

These methods are mainly useful when you using Kotlin and you need a Non-Nullable Context. So using these methods instead, is matter of personal preference.

So, did you learn something new? If you did, please clap and share the post. 😄

Источник

11 Android Studio Shortcuts every Android Developer must know

This is how you may end up if you try and take a shortcut in real life, but it’s not true for the world of software !! Here you are encouraged to take shortcuts like auto complete, code generations, snippets and what not…

A software engineer must know all the shortcuts of the IDE he is using and must have the environment BENT to his will. Given a keyboard he must be able to navigate through the IDE all around. This can increase his productivity manifolds and is also less distracting than shifting to a mouse/touchpad during typing.

As an Android Engineer I can only speak of Android Studio and here I will mention my top 11 most useful Android Studio Shortcuts ( Windows / Mac ):

This is the holy grail of the navigational shortcuts. It’s really simple. Search Android assets, navigate to the Gradle files, image resources, layouts, colors.xml and much more. There is nowhere you can’t go with the Double Shift shortcut.

Just press Shift twice and a hovering menu will po2.pup. Something like this :

As you can see I searched for “color” and it presented me with all the file with name color. This is my favorite one and I use it a lot in Android Studio.

More often than not, you’ll not be working with all the project files at once. You would be working on a specific module in a project and will be playing around some specific files of that module. The Android Studio has an option where you can browse the most recently opened files on the go. Just press CTRL + E for windows and Command + E for mac and a list of recently opened files will popup.

So did you forgot what’s the shortcut for a replace action ? You forgot what’s the shortcut for a find action ? CTRL + SHIFT + A got you !! You can find actions such as Replace, Find, Run, Instant Run etc…

I searched for the Run action and it gave me all the run options Android Studio has to offer like running the garbage collector and debug runner.

This option is particularly useful if you want to search for some variable or method names. Many a times it so happens that you have declared a variable in some local code and forgot it’s origin, or you may want to find all the places it has been initialized or assigned some value. Well, android studio makes this very easy. Just press CTRL+ALT+SHIFT+N on Windows or Command+Option+O on Mac and type/guess a part of the variable name. Android studio will present you with a list of all possible options.

Читайте также:  Миньон раш для андроид взлом

It can be time consuming to type out all the boilerplate code such as getters/setters in model classes, toString implementation, Parcelable Implementation and much more. Android Studio does all this for you. Press ALT+Insert on Windows or Command+N on Mac and android studio will list out all the options that are available such as override methods, implement interfaces, toString implementation etc…

Code Generation Android Studio Shortcut

When extending a Fragment or Activity class, you need to override certain methods such as onCreate and onCreateView. Apart from that you can also override lifecycle methods such as onPause, onResume, onDestroy. Android studio generates all this boilerplate code for you. Just press CTRL+O on Windows or Command+O on Mac and you’ll be presented with a list of methods that you can override.

You can see there are hundreds of methods which can be overridden and it is not possible to remember them all. So this shortcut comes in handy during development phase. You can also start typing a part of the name of method you want to override and the list will filter automagically.

If you want to delete the entire line, no need to select using a mouse or pressing backspace for the whole day. Just press CTRL+Y on Windows or Command+Backspace on Mac and you are good to go.

Forgot what all parameters your method requires ? Methods such as rawQuery (for SQLite) use many many parameters which are hard to remember. Here’s where Android Studio comes to the rescue. Just press CTRL+Space on Windows or Command+Space on Mac and you will be presented with a popup of all the variants of a method and the arguments that it expects.

Basic Completion Android Studio Shortcut

This feature is also demonstrated in the previous image. Notice the popup box in grey. This is the documentation box. Just like that we can view the documentation of a particular method, including the class it extends from and some links to more details. Press CTRL+Q on Windows or Command+J on Mac and the popup box will show up. It requires an active internet connection.

Every developer is familiar with the callback hell, OnClickListeners, Dialog Click Listeners etc… These are anonymous classes that have multitudes of methods that need to be overridden. If you have a large codebase, then looking at such code can be daunting. Android Studio provides this option of collapsing all the blocks of code, just showing the method names so that you can find the method you are looking for easily, or just close out all other distractions and make your IDE look neat!!

To expand or collapse code blocks press CTRL+ +/- on Windows or Command + +/- on Mac. Have a look at the image below. The file looks so neat, showing only the method names :

Collapse/Expand Android Studio Shortcut

Again this is one of the most important shortcut that you can use. No need to manually indent all the nested if blocks or the for loops. Android Studio takes care of all the formatting. Just Press CTRL+ALT+L on Windows or Command+Option+L on Mac. The android studio will reformat all the code for you.

And the good part is that it works for XML layouts as well. It takes care of ordering of the xml attributes and indenting nested layouts in your code so that you focus more on coding and less on figuring out what is nested under what.

So, this was my list of 11 most useful Android Studio Keyboard Shortcuts. These have helped me improve my productivity manifolds and hope it does for you as well.

Don’t forget to follow me on LinkedIn and Quora . If you have any questions or suggestions just drop a comment below and I’ll be happy to help.

Источник

Оцените статью