Thursday, 2 January 2020

Corotuine

First Add coroutine dependcies

On Android, it's essential to avoid blocking the main thread. The main thread is a single thread that handles all updates to the UI. It's also the thread that calls all click handlers and other UI callbacks. As such, it has to run smoothly to guarantee a great user experience.
For your app to display to the user without any visible pauses, the main thread has to update the screen every 16ms or more often, which is about 60 frames per second. Many common tasks take longer than this, such as parsing large JSON datasets, writing data to a database, or fetching data from the network. Therefore, calling code like this from the main thread can cause the app to pause, stutter, or even freeze. And if you block the main thread for too long, the app may even crash and present an Application Not Responding dialog.


dependencies {
  ...
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x"
}
zrrrunblocking{}
GlobalScope{}
CorotunieScope().launch
withContext()
Important: Using suspend doesn't tell Kotlin to run a function on a background thread. It's normal for suspend functions to operate on the main thread. It's also common to launch coroutines on the main thread. You should always use withContext() inside a suspend function when you need main-safety, such as when reading from or writing to disk, performing network operations, or running CPU-intensive operations.

Starting new coroutines

It’s important to note that you can’t just call a suspend function from anywhere. The suspend and resume mechanism requires that you switch from normal functions to a coroutine.
There are two ways to start coroutines, and they have different uses:
  1. launch builder will start a new coroutine that is “fire and forget” — that means it won’t return the result to the caller.
  2. async builder will start a new coroutine, and it allows you to return a result with a suspend function called await.


Sunday, 15 December 2019

Kotlin Tutorial

https://www.journaldev.com/19467/kotlin-let-run-also-apply-with

MVVM stands for Model View ViewModel and it is a design pattern that is used to build 
softwares. MVVM helps us to separate the Business Logic of our Application from the Views or UI.


Model : This is responsible for handling the data in the application. Model cannot directly interact with Views, but it interacts with ViewModels and then Views with the help of observables. (Sounds confusing right? Don’t worry in the course we will cover every step in detail).
View: This is the User Interface of our Application. It should not contain any application logic.
ViewModel: It is basically a link between Model and View.The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations. 
Architecture Components provides ViewModel helper class for the UI controller that is responsible for preparing data for the UI. ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. For example, if you need to display a list of users in your app, make sure to assign responsibility to acquire and keep the list of users to a ViewModel, instead of an activity or fragment.

LifeCylerOwener and LifeCylerobserver
android mvvm architecture

Advantages of using MVVM

Now let’s talk about what are the advantages of using MVVM in your android project.
  • If you use MVVM it will help you structuring your code in a nice way so that it is easy to understand for a new developer.
  • Using MVVM makes your project maintainable as everything is well organized and making changes are very easy.
  • Testability is easy with MVVM because all modules are independent and testable.
  • MVVM enhances the re-usability of the code.

     

       Coroutines


Sunday, 20 January 2019

Basic Question

What is Inent

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly.

Intents are a way of telling to Android what you want to do. In other words, you describe your intention. Intents can be used to signal to the Android system that a certain event has occurred. Other components in Android can register to this event via an intent filter.
Following are 2 types of intents

1.Explicit Intents

used to call a specific component. When you know which component you want to launch and you do not want to give the user free control over which component to use. For example, you have an application that has 2 activities. Activity A and activity B. You want to launch activity B from activity A. In this case you define an explicit intent targeting activityB and then use it to directly call it.

2.Implicit Intents

used when you have an idea of what you want to do, but you do not know which component should be launched. Or if you want to give the user an option to choose between a list of components to use. If these Intents are send to the Android system it searches for all components which are registered for the specific action and the data type. If only one component is found, Android starts the component directly. For example, you have an application that uses the camera to take photos. One of the features of your application is that you give the user the possibility to send the photos he has taken. You do not know what kind of application the user has that can send photos, and you also want to give the user an option to choose which external application to use if he has more than one. In this case you would not use an explicit intent. Instead you should use an implicit intent that has its action set to ACTION_SEND and its data extra set to the URI of the photo.

Explicit Android Intent is the Intent in which you explicitly define the component that needs to be called by Android System.
 Intent MoveToNext = new Intent (getApplicationContext(), SecondActivity.class);
Implicit Android Intent
Implicit Android Intents is the intent where instead of defining the exact components, you define the action you want to perform.

                              Fragment

Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

Service

Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
These are the three different types of services:
Foreground
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a status bar icon. Foreground services continue running even when the user isn't interacting with the app.
Background
A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

Friday, 24 November 2017

Object Animator

Android provides the Properties Animation API which allow to change object properties over a pre-defined time interval. It can be used for arbitrary object properties and on any object not only Android views




The superclass of the animation API is the Animator class. Typically the ObjectAnimator class is used to modify the attributes of an object.
You can also add an AnimatorListener class to your Animator class. This listener is called in the different phases of the animation. You can use this listener to perform actions before orafter a certain animation, e.g. add or remove a View from a ViewGroup.


 float scale = getResources().getDisplayMetrics().density;
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(img,
                "x", transitionsContainer.getX(), 150.0f * scale);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(img,
                "y", transitionsContainer.getY(), 150.0f * scale);
//                ObjectAnimator anim3 = ObjectAnimator.ofFloat(someImage,//                        "x", 220.0f*scale, 20.0f*scale);//                ObjectAnimator anim4 = ObjectAnimator.ofFloat(someImage,//                        "y", 220.0f*scale, 20.0f*scale);        AnimatorSet set = new AnimatorSet();
        set.play(anim2).after(500);
        // set.play(anim2).after(500);        set.setDuration(1000);
        set.setInterpolator(new LinearInterpolator());
        set.start();
        set.addListener(new Animator.AnimatorListener() {
            @Override            public void onAnimationStart(Animator animator) {

            }

            @Override            public void onAnimationEnd(Animator animator) {
                img.setVisibility(View.INVISIBLE);
                logo.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override                    public void run() {
                        sharedPreferences= getSharedPreferences("pref",MODE_PRIVATE);
                        if(sharedPreferences.getBoolean("islogin",false)){
                            Intent in = new Intent(getApplicationContext(), Home_Activity.class);
                            Sample sample= new Sample( R.color.colorPrimary, "Shared Elements");
                            in.putExtra("sample", sample);
                            in.putExtra("type", 0);
                            transitionTo(in);
                            finish();
                        }else {
                            Intent in = new Intent(Splash.this, MainActivity.class);
                            // startActivity(in);                            Sample sample= new Sample( R.color.colorPrimary, "Shared Elements");
                            in.putExtra("sample", sample);
                            in.putExtra("type", 0);
                            transitionTo(in);
                            finish();
                        }
                    }
                },1000);

            }

            @Override            public void onAnimationCancel(Animator animator) {

            }

            @Override            public void onAnimationRepeat(Animator animator) {

            }
        });


Activity animations in Android with shared views

  sharedImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //This is where the magic happens.
                // makeSceneTransitionAnimation takes a context, view,
                // a name for the target view.
                ActivityOptions options =
                        ActivityOptions.
                        makeSceneTransitionAnimation(MainActivity.this, sharedImage, "sharedImage");
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent, options.toBundle());
            }
        });

Wednesday, 24 May 2017

Content Provider



If you want to share data with other applications you can use a content provider (short provider). Provider offer data encapsulation based on URI’s. Any URI which starts withcontent:// points to a resources which can be accessed via a provider. A URI for a resource may allow to perform the basic CRUD operations (Create, Read, Update, Delete) on the resource via the content provider.



Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database.