Vivek Beladiya

Vivek Beladiya's Posts

Mobile Development Head

Android UI Design: Tips and Best Practices

A visually appealing and user-friendly user interface (UI) is key to creating successful Android apps. Mastering Android UI design requires a combination of creativity, usability principles, and knowledge of best practices. In this blog post, we will delve into valuable tips and best practices to help you create exceptional UI designs for your Android apps, ensuring an engaging and intuitive user experience.

Understand Material Design Guidelines:

Google's Material Design guidelines serve as a foundation for creating visually consistent and intuitive UIs across Android devices. Familiarize yourself with these guidelines, which cover aspects such as layout, typography, color schemes, and iconography. By adhering to Material Design principles, you can create UIs that feel native to the Android platform while offering a modern and visually pleasing experience.

Prioritize Consistency:

Consistency plays a vital role in UI design. Maintain a consistent visual style, including color schemes, typography, and spacing, throughout your app. Consistent UI elements and interactions create a sense of familiarity, enabling users to navigate your app with ease. Ensure that your app's UI aligns with the overall branding and design language to establish a cohesive experience.

Keep it Simple and Minimalistic:

Simplicity is key to effective UI design. Strive for a clean and uncluttered interface that focuses on essential elements. Avoid overwhelming users with excessive information or complex layouts. Use whitespace strategically to enhance readability and highlight important elements. Embrace minimalistic design principles, such as flat or material design, to create a visually pleasing and intuitive UI.

Optimize for Different Screen Sizes:

Android devices come in various screen sizes and resolutions, so it's crucial to ensure your UI design adapts seamlessly to different form factors. Design responsive layouts that can adjust to different screen sizes, orientations, and aspect ratios. Utilize relative sizing and scalable elements to accommodate various screen densities. Test your app on different devices to ensure a consistent and user-friendly experience across the board.

Use Intuitive Navigation Patterns:

Efficient navigation is key to a user-friendly app. Utilize intuitive navigation patterns such as bottom navigation bars, hamburger menus, and tabs to provide easy access to different sections of your app. Follow established navigation patterns that users are already familiar with, but also consider the specific needs and context of your app to provide a tailored and intuitive navigation experience.

Pay Attention to Typography:

Typography plays a crucial role in UI design, affecting readability and overall aesthetic appeal. Choose legible fonts that align with your app's branding and style. Ensure appropriate font sizes for different text elements, considering factors such as readability on various screen sizes and accessibility for users with visual impairments. Use typography to guide users and emphasize important information within your app.

Utilize Meaningful and Consistent Icons:

Icons are powerful visual elements that aid in navigation and convey meaning. Use icons consistently throughout your app, adhering to recognized iconography standards. Ensure that icons are visually clear, easily recognizable, and aligned with their intended actions or functionalities. Combine icons with text labels when necessary to provide clarity and improve usability.

Employ Color Strategically:

Color choices can evoke emotions and influence user perception. Select a color palette that aligns with your app's branding and purpose. Use colors purposefully to differentiate elements, convey hierarchy, and provide visual cues. Ensure color contrast for text and important elements to maintain accessibility for all users. Leverage color to create a visually engaging and cohesive UI design.

Test and Iterate:

Regular testing and iteration are crucial in UI design. Gather feedback from users, conduct usability tests, and analyze user behavior to identify areas for improvement. Iterate your design based on user feedback and insights, refining the UI to enhance usability, address pain points, and optimize the overall user experience. Embrace an iterative design process to continuously improve your app's UI.

Stay Updated and Inspired:

UI design trends evolve over time, so it's essential to stay updated with the latest design trends, techniques, and emerging patterns. Explore design inspiration from other successful Android apps, industry resources, and design communities. Keep an eye on Google's updates to Material Design and Android design patterns to ensure your UI remains relevant and appealing.

Conclusion:

Mastering Android UI design involves a combination of creativity, adherence to best practices, and a deep understanding of user needs. By following these tips and best practices, such as understanding Material Design guidelines, prioritizing consistency, keeping the UI simple and minimalistic, optimizing for different screen sizes, using intuitive navigation patterns, paying attention to typography and color, testing and iterating, and staying updated with design trends, you can create compelling and user-friendly UIs that enhance the overall user experience of your Android apps. Strive for excellence in UI design, and your apps will stand out in the crowded Android marketplace.

July 17, 20234 minutesVivek BeladiyaVivek Beladiya
How should your app be updated for Android 13 given the changes to permissions?

The Android 13 version was just released. Because your audience will progressively switch to this new version, you as an app developer must support newer versions. Yes, it takes longer to adjust to new versions than it does for IOS, but you still need to do it.

Changes with the new version come in 3 categories:

  1. New Features and APIs.The overview of the new functionality and APIs can be found here. These modifications consist of brand-new APIs and functionality that were not present in earlier iterations. The Per-app language choices are the new feature that I loved the most. Users can now choose a language other than the system language for an app thanks to this functionality.

  2. Behaviour changes in all apps. The details about those adjustments are available here. No matter if your app targets API level 33 or not, these changes apply to all apps. You must test your app on Android 13 and make the necessary adjustments to make it suitable.

  3. Behavior changes Apps targeting Android 13 or higher. These changes can be found here. Only apps that target API level 33 or higher are impacted by these changes. You must make the necessary adjustments in order to work with Android 13.

In Android 13, there are some changes that are worth checking which could affect your app. These are mostly changes in permission behaviors.

NEARBY_DEVICES Permission

Starting with Android 13, you will need to use NEARBY_DEVICES permission for some Wi-Fi-related use cases. Previously, ACCESS_FINE_LOCATION permission was used.

New Permissions for Media

Three new permission is introduced with Android 13: READ_MEDIA_IMAGES, READ_MEDIA_IMAGES, READ_MEDIA_VIDEO, and READ_MEDIA_AUDIO.Use one of these new permissions if you were reading files using READ_EXTERNAL_STORAGE. All is well if an Android 13 user has already granted this permission. If not, the request for READ_EXTERNAL_STORAGE permission will be disregarded. This indicates that for this section, your app needs to be modified.

In our program, we used READ_EXTERNAL_STORAGE to select images. For picture selection, we had to support READ_MEDIA_IMAGES. I'll now describe how you can accomplish this.

Firstly, you need to update compile and target api level to 33. Now you could access the new APIs :)

compile: 33,
target : 33

Secondly, you need to put READ_MEDIA_IMAGES permission to AndroidManifest file.

Lastly, you need to programatically ask for READ_EXTERNAL_STORAGE permission for API level lower than 33 and ask for READ_MEDIA_IMAGES permission for API level equal or higher than 33.


private val readImagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) Manifest.permission.READ_MEDIA_IMAGES else Manifest.permission.READ_EXTERNAL_STORAGE
if(ContextCompat.checkSelfPermission(this, readImagePermission) == PackageManager.PERMISSION_GRANTED){
    //permission granted
} else {
    //permission not granted
}

Thats it, now your app is supporting this new permission! Hope this tutorial helped you in migrating to the new permissions. Please provide a clap if you liked this post.

April 25, 20233 minutesVivek BeladiyaVivek Beladiya
How to use Biometric(Fingerprint) in Android?

1) What is Biometric? -> Authenticate by using biometric data, and perform cryptographic operations

  • Declaring dependencies -> Add the dependencies for the artifacts you need in the build.gradle file for your app or module:

    dependencies {

     // Java language implementation
    implementation "androidx.biometric:biometric:1.1.0"
    
    // Kotlin
    implementation "androidx.biometric:biometric-ktx:1.2.0- 
     alpha05"

    }

2) How to show a biometric authentication dialog?

-> Implementing biometric authentication, such as face recognition or fingerprint recognition, is one way to safeguard sensitive information or premium content within your app. This guide will show you how to support biometric login processes in your app.

  • Declare the strong authentication that your app supports. -> To define the types of authentication that your app supports, use the BiometricManager.Authenticators interface. The system lets you declare the following types of authentication:
  1. BIOMETRIC_STRONG
  2. BIOMETRIC_WEAK
  3. DEVICE_CREDENTIAL : (Authentication using a screen lock credential – the user's PIN, pattern, or password.)
  • Pass an authentication type or a bitwise mixture of types into the setAllowedAuthenticators() function to define the forms of biometric authentication that your app permits. The code snippet below illustrates how to implement authentication using a Class 3 biometric or a screen lock credential :

     promptInfo = new 
       BiometricPrompt.PromptInfo.Builder()
       .setTitle("Biometric login for my app")
       .setSubtitle("Log in using your biometric 
      credential")
      .setAllowedAuthenticators(BIOMETRIC_STRONG | 
       DEVICE_CREDENTIAL)
     .build();
  • Check that biometric authentication is available

     BiometricManager biometricManager = BiometricManager.from(this);

    switch (biometricManager.canAuthenticate(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)) { case BiometricManager.BIOMETRIC_SUCCESS: Log.d("MY_APP_TAG", "App can authenticate using biometrics."); break; case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE: Log.e("MY_APP_TAG", "No biometric features available on this device."); break; case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE: Log.e("MY_APP_TAG", "Biometric features are currently unavailable."); break; case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED: // Prompts the user to create credentials that your app accepts. final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL); enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BIOMETRIC_STRONG | DEVICE_CREDENTIAL); startActivityForResult(enrollIntent, REQUEST_CODE); break; }

  • Complete the following steps to add biometric authentication to your app using the Biometric library:

1). Include a link to the androidx.biometric library as a dependency in the build.gradle file for your app module.

2). Using the logic in the following code snippet, display the biometric login dialog in the activity or fragment that hosts it:

   private Executor executor;
   private BiometricPrompt biometricPrompt;
  private BiometricPrompt.PromptInfo promptInfo;

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_login);
    executor = ContextCompat.getMainExecutor(this);
    biometricPrompt = new 
 BiometricPrompt(MainActivity.this,
        executor, new 
  BiometricPrompt.AuthenticationCallback() {
    @Override
    public void onAuthenticationError(int errorCode,
            @NonNull CharSequence errString) {
        super.onAuthenticationError(errorCode, errString);
        Toast.makeText(getApplicationContext(),
            "Authentication error: " + errString, 
      Toast.LENGTH_SHORT)
            .show();
       }

     @Override
      public void onAuthenticationSucceeded(
            @NonNull BiometricPrompt.AuthenticationResult 
       result) {
        super.onAuthenticationSucceeded(result);
        Toast.makeText(getApplicationContext(),
            "Authentication succeeded!", 
       Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAuthenticationFailed() {
        super.onAuthenticationFailed();
        Toast.makeText(getApplicationContext(), 
    "Authentication failed",
            Toast.LENGTH_SHORT)
            .show();
       }
     });

     promptInfo = new BiometricPrompt.PromptInfo.Builder()
        .setTitle("Biometric login for my app")
        .setSubtitle("Log in using your biometric 
   credential")
        .setNegativeButtonText("Use account password")
        .build();

   // Prompt appears when user clicks "Log in".
   // Consider integrating with the keystore to unlock 
  cryptographic operations,
   // if needed by your app.
    Button biometricLoginButton = 
  findViewById(R.id.biometric_login);
   biometricLoginButton.setOnClickListener(view -> {
        biometricPrompt.authenticate(promptInfo);
   });
     }
January 11, 20233 minutesVivek BeladiyaVivek Beladiya
How to start activity using Animation?

Material design apps use activity transitions to connect different states with motion and transformations. Entry and exit transitions, as well as transitions between shared elements, can be animated.

Android supports these enter and exit transitions

1] Explode :

  • Views are moved in or out of the scene's center.

2] Slide :

  • Views are moved in or out from a scene's edge.

3] Fade

  • Changes the opacity of a view to add or remove it from the scene.

These transitions are also supported on Android

ChangeBounds :

  • Makes target views' layout bounds change.

ChangeClipBounds :

  • Animates changes made to the clip boundaries of target views.

ChangeTransform :

  • Initiates the scale and rotation change of target views.

ChangeImageTransform :

  • Images have a change in size and scale as a result of animation.

Check on versions compatibility


// Check if we're running on Android 5.0 or higher
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // Apply activity transition
            } else {
                // Swap without transition
}

Create custom transitions

  • When you define a style that inherits from the material theme, enable window content transitions with the android:windowActivityTransitions attribute.
<style name="BaseAppTheme" 
parent="android:Theme.Material">
      <!-- enable window content transitions -->
      <item name="android:windowActivityTransitions">true</item>
      <!-- specify enter and exit transitions -->
      <item name="android:windowEnterTransition">@transition/explode</item>
      <item name="android:windowExitTransition">@transition/explode</item>

<!-- specify shared element transitions -->
      <item name="android:windowSharedElementEnterTransition">
            @transition/change_image_transform</item>
      <item name="android:windowSharedElementExitTransition">
            @transition/change_image_transform</item>
</style>

This example defines the change_image_transform transition as follows:

<!-- res/transition/change_image_transform.xml -->
<!-- (see also Shared Transitions below) -->
<transitionSet 
       xmlns:android="http://schemas.android.com/apk/res/android">
       <changeImageTransform/>
</transitionSet>

In your code, enable window content transitions by calling Window.requestFeature() :

            // inside your activity (if you did not enable transitions in your theme)
            getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);

            // set an exit transition
            getWindow().setExitTransition(new Explode());

Use transitions to start an activity

startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this).toBundle());

Let someone start a new activity with a shared element

To make a screen transition animation between two activities that have a shared element:

            final View imgContainerView = findViewById(R.id.img_container);

            // get the common element for the transition in this activity
            final View androidRobotView = findViewById(R.id.image_small);

            // define a click listener
            imgContainerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(this, Activity2.class);
                    // create the transition animation - the images in the layouts
                    // of both activities are defined with android:transitionName="robot"
                    ActivityOptions options = ActivityOptions
                        .makeSceneTransitionAnimation(this, androidRobotView, "robot");
                    // start the new activity
                    startActivity(intent, options.toBundle());
                }
            });

An activity with multiple elements is an excellent start

            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,
                    Pair.create(view1, "agreedName1"),
                    Pair.create(view2, "agreedName2"));
September 15, 20222 minutesVivek BeladiyaVivek Beladiya
How to add ProGuard to Android?

We may have used ProGuard in our project when developing Android applications. In this blog, all of the features and how to use ProGuard effectively on Android.

1. What is ProGuard?

ProGuard is a free java tool in Android, which helps us to do the following:

  • Shrink(Minify) the code: Remove unused code in the project.
  • Obfuscate the code: Rename the names of class, fields, etc.
  • Optimize the code: Do things like inlining the functions.

In short, ProGuard has the following impact on our project:

  • It reduces the size of the application.
  • It removes the unused classes and methods that contribute to the 64K method count limit of an Android application.
  • It makes the application difficult to reverse engineer by obfuscating the code.

2. How to use it in our project?

To enable Proguard in your project, in the app's build.gradle add,

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

    }
}

Here, we have minfyEnabled as true. It activates the proguard which takes from the file,

proguard-android.txt

It is under the release block, which means that it will only be applied to the release of the build we generate.

But it can be too much sometimes when the proguard removes too much code and it might break your code for the flow.

So, configuring the code we have to add some custom rules to make sure we remove the set of code from obfuscating. We can fix this by writing out custom rules in our proguard and it will respect while generating the build.

Now, let us see how we can write customs rules in proguard.

1. Keeping class files

Assume we have a data class that is required by some API but that we obfuscate by generating a build. We have a User data class, for example.

data class User(val id: String = "")

and we want not to obfuscate the class which generating build then to ignore it from obfuscating we use @Keep annotation and update the code like,

@Keep
data class User(val id: String = "")

This annotation allows the class to be ignored when minified using proguard. The class and its member functions will be preserved even when not in use.

-keep

to preserve options of class while generating the build. Using -keep over @Keep we get more control over what to preserve and what not to.

2. Keeping a class's members

If we want to keep only the class members and not the entire class while shrinking, we can use,

-keepclassmembers

in the proguard rule file. This will help us to ignore members of a specific class.

Consider the above User class, and we want to preserve all the public methods inside it. We write the rule like,

-keepclassmembers class com.mindorks.sample.User{
    public *;
}

3. Keeping names of the class and members

Let's say we want to keep all of the same class names and members if they are used in the code, i.e. if the class is not used, it will be shrunk by proguard but will not be obfuscated because it has already been shrunk and there is no need for obfuscation.

-keepnames

Practical use of it looks like,

-keepnames class com.mindorks.sample.GlideModule

Here, if the GlideModule would keep all of its names of the class and the member function.

Note:-

As a fragment TAG, do not use something like MainFragment.class.getSimpleName().

While obfuscating, Proguard may assign the same name (A.class) to two different fragments in different packages. Two fragments will have the same TAG in this case. It will result in a bug in your application.

Keep your Proguard mapping file in order to trace back to the original code. You may need to upload it to different locations, such as the PlayStore Console, to see the original stack-trace of the crashes.

June 06, 20223 minutesVivek BeladiyaVivek Beladiya
How to Check the Visibility Keyboard in Android?

The keyboard is one of the basic components of any Android application. Typically, we use the keyboard to take input from the user. Soft keyboards are used in Android applications, and the Android system gives you with a keyboard to receive user input in any EditText or anything similar. Also, the keyboard will be invisible from the screen if the user has given input. So, in this blog, we will learn how to check if keyboard appears in Android app. How can I make this keyboard invisible or turn it off if it is visible?. So, let's get started.

Step 1 − Create a new project in Android Studio, Add the following code to activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:id = "@+id/main_layout"
   tools:context = ".MainActivity">
   <EditText
      android:id = "@+id/editext"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content">
   </EditText>
   <Button
      android:id = "@+id/button"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Click here to hide"
      app:layout_constraintBottom_toBottomOf = "parent"
      app:layout_constraintLeft_toLeftOf = "parent"
      app:layout_constraintRight_toRightOf = "parent"
      app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

Step 3 − Add the following code to MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
   ConstraintLayout constraintLayout;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button button = findViewById(R.id.button);
      EditText editText=findViewById(R.id.editext);
      editText.requestFocus();
      constraintLayout=findViewById(R.id.main_layout);
      constraintLayout.getViewTreeObserver().addOnGlobalLayoutListener(new  ViewTreeObserver.OnGlobalLayoutListener() {
         @Override
         public void onGlobalLayout() {
            Rect r = new Rect();
            constraintLayout.getWindowVisibleDisplayFrame(r);
            int screenHeight = constraintLayout.getRootView().getHeight();
            int keypadHeight = screenHeight - r.bottom;
            if (keypadHeight > screenHeight * 0.15) {
               Toast.makeText(MainActivity.this,"Keyboard is showing",Toast.LENGTH_LONG).show();
            } else {
               Toast.makeText(MainActivity.this,"keyboard closed",Toast.LENGTH_LONG).show();
            }
         }
      });
      button.setOnClickListener(this);
   }

   @Override
   public void onClick(View v) {
      switch (v.getId()) {
         case R.id.button:
         hideSoftkeybard(v);
         break;
      }
   }

   private void hideSoftkeybard(View v) {
      InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
      inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
   }
}

Here, we are using hideSoftKeyboard to hide the keyboard if the keyboard is visible on clicking the button.

So, finally, run the application and see the output on your mobile device.

In this blog, we learned how to check if the keyboard is visible or not on the screen. Also, we have if the keyboard is visible then how to close it. That’s it for this blog.

March 01, 20222 minutesVivek BeladiyaVivek Beladiya
How To Add Google In-App Review for Android

Integrating in-app reviews is very easy. It can be achieved with very minimal code. Let's see how to integrate it.

1. As the In-App Review is a part of the Play core library, we need to add the required dependencies to our app's build.gradle (app level) file,

implementation “com.google.android.play:core:1.8.0”
implementation "com.google.android.material:material:1.3.0-alpha02"

2. First, we need to create the instance of ReviewManager which would help us to start the API. We create the instance using,

ReviewManager manager = ReviewManagerFactory.create(this);

Now, using this manager object, we have to request the flow to launch the In-App review flow.

 ReviewManager manager = ReviewManagerFactory.create(this);
 Task<ReviewInfo> request = manager.requestReviewFlow();
 request.addOnCompleteListener(task -> {
      if (task.isSuccessful()) {
// We can get the ReviewInfo object
      ReviewInfo reviewInfo = task.getResult();
      } else {
// There was some problem, continue regardless of the result.
      }
 });

A complete code is required for the in-app review flow.

MainActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.google.android.play.core.tasks.Task;

public class MainActivity extends AppCompatActivity {

   private ReviewManager reviewManager;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       init();
   }

   private void init() {
       reviewManager = ReviewManagerFactory.create(this);
       findViewById(R.id.btn_rate_app).setOnClickListener(view -> showRateApp());
   }

   public void showRateApp() {
       Task<ReviewInfo> request = reviewManager.requestReviewFlow();
       request.addOnCompleteListener(task -> {
           if (task.isSuccessful()) {
               ReviewInfo reviewInfo = task.getResult();
               Task<Void> flow = reviewManager.launchReviewFlow(this, reviewInfo);
               flow.addOnCompleteListener(task1 -> {
               });
           } else {
               showRateAppFallbackDialog();
           }
       });
   }
   private void showRateAppFallbackDialog() {
       new MaterialAlertDialogBuilder(this)
               .setTitle(R.string.rate_app_title)
               .setMessage(R.string.rate_app_message)
               .setPositiveButton(R.string.rate_btn_pos, (dialog, which) -> {

               })
               .setNegativeButton(R.string.rate_btn_neg,
                       (dialog, which) -> {
                       })
               .setNeutralButton(R.string.rate_btn_nut,
                       (dialog, which) -> {
                       })
               .setOnDismissListener(dialog -> {
               })
               .show();
   }
}

How to test the In-App Review?

To check the in-app review flow, you must already have the app approved on Playstore. This does not mean that the application should be available to the public. At the very least, you should have an account ready for internal testing or internal application sharing.

  • You can use Internal Test Track to release the app and test the in-app review flow.
  • You can use Internal App Sharing to test the in-app review flow.

You can find more information about the test part on the Android Developer page.

February 11, 20222 minutesVivek BeladiyaVivek Beladiya
How to Start and Stop Jobscheduler in Android

Android apps will work in the background (Android Background Service) mode to listen to broadcast messages, push services, and many other features that extend the functionality of the app. Similarly, it comes with job scheduling.

The Android Job Scheduler is a very efficient way of dealing with things. It will provide a wake lock for the app by default, which will provide a guarantee that the device will stay awake until the work is completed. Also, it provides better battery performance, which is the key point in any application.

activity_main.xml

This tutorial deals with the Android JobShedular UI is easy. Just two buttons to start and stop jobscheduler.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity" 
android:orientation="vertical">

<Button 
android:id="@+id/btn_start" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:text="Start Service"/>; 

<Button 
android:id="@+id/btn_stop" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:text="Stop Service"/>;

<LinearLayout/>

MyJobScheduler.Java

Add Android JobScheduler, Job Scheduler starts from this class where we can find methods that will start and stop work.

This method deals with the job start where we can also initialize our MyJobExecutor.java class so that we can execute our task as the job starts.

import android.app.job.JobParameters; 
import android.widget.Toast; 

public class MyJobScheduler extends android.app.job.JobService { 

private MyJobExecutor jobExecutor; 

@Override 
public boolean onStartJob(final JobParameters params) { 
jobExecutor = new MyJobExecutor() {

@Override 
protected void onPostExecute(String str) { 
Toast.makeText(MyJobScheduler.this, str, Toast.LENGTH_SHORT).show(); 
jobFinished(params,false); 
} 
}; 
jobExecutor.execute(); 
return true; 
} 

@Override 
public boolean onStopJob(JobParameters params) { 
jobExecutor.cancel(true); 
return false; 
} 

}
December 25, 20213 minutesVivek BeladiyaVivek Beladiya