Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday 30 October 2018

How to ON/OFF battery doze mode in android

Hello, dear friends, this post is very important to the Android developers to resolve to avoid battery doze mode so let's start...


MainActivity.java

package com.samset.doze;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.samset.doze.utils.DozeHelper;

public class MainActivity extends AppCompatActivity {
    private AppCompatButton btncheck;
    private AppCompatTextView tvmsg;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btncheck=findViewById(R.id.btncheck);
        tvmsg=findViewById(R.id.tvmsg);


        tvmsg.setText("This app is " +DozeHelper.getisBatteryOptimizations(this,getPackageName().toString()));
        btncheck.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Intent intent= DozeHelper.prepareBatteryOptimization(MainActivity.this,getPackageName(),true);
                startActivity(intent);

            }
        });





    }
}

DozeHelper.java

public class DozeHelper {


    public enum PowerSaveState {
        ON, OFF, ERROR_GETTING_STATE, IRRELEVANT_OLD_ANDROID_API    }

    public enum WhiteListedInBatteryOptimizations {
        WHITE_LISTED, NOT_WHITE_LISTED, ERROR_GETTING_STATE, UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING, IRRELEVANT_OLD_ANDROID_API    }

    public enum DozeState {
        NORMAL_INTERACTIVE, DOZE_TURNED_ON_IDLE, NORMAL_NON_INTERACTIVE, ERROR_GETTING_STATE, IRRELEVANT_OLD_ANDROID_API, UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING    }

    @NonNull    public static DozeState getDozeState(@NonNull Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return DozeState.IRRELEVANT_OLD_ANDROID_API;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return DozeState.UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING;
        }
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return DozeState.ERROR_GETTING_STATE;
        return pm.isDeviceIdleMode() ? DozeState.DOZE_TURNED_ON_IDLE : pm.isInteractive() ? DozeState.NORMAL_INTERACTIVE : DozeState.NORMAL_NON_INTERACTIVE;
    }

    @NonNull    public static PowerSaveState getPowerSaveState(@NonNull Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return PowerSaveState.IRRELEVANT_OLD_ANDROID_API;
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return PowerSaveState.ERROR_GETTING_STATE;
        return pm.isPowerSaveMode() ? PowerSaveState.ON : PowerSaveState.OFF;
    }


    @NonNull    public static WhiteListedInBatteryOptimizations getisBatteryOptimizations(@NonNull Context context, @NonNull String packageName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return WhiteListedInBatteryOptimizations.IRRELEVANT_OLD_ANDROID_API;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return WhiteListedInBatteryOptimizations.UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING;
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return WhiteListedInBatteryOptimizations.ERROR_GETTING_STATE;
        return pm.isIgnoringBatteryOptimizations(packageName) ? WhiteListedInBatteryOptimizations.WHITE_LISTED : WhiteListedInBatteryOptimizations.NOT_WHITE_LISTED;
    }

    @TargetApi(Build.VERSION_CODES.M)
    @RequiresPermission(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
    @Nullable    public static Intent prepareBatteryOptimization(@NonNull Context context, @NonNull String packageName, boolean alsoWhenWhiteListed) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return null;
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) == PackageManager.PERMISSION_DENIED)
            return null;
        final WhiteListedInBatteryOptimizations ispowersave = getisBatteryOptimizations(context, packageName);
        Intent intent = null;
        switch (ispowersave) {
            case WHITE_LISTED:
                if (alsoWhenWhiteListed)
                    intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                break;
            case NOT_WHITE_LISTED:
                intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).setData(Uri.parse("package:" + packageName));
                break;
            case ERROR_GETTING_STATE:
            case UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING:
            case IRRELEVANT_OLD_ANDROID_API:
            default:
                break;
        }
        return intent;
    }

    /**     * registers a receiver to listen to power-save events. returns true if succeeded to register the broadcastReceiver.     */    @TargetApi(Build.VERSION_CODES.M)
    public static boolean registerPowerSaveReceiver(@NonNull Context context, @NonNull BroadcastReceiver receiver) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return false;
        IntentFilter filter = new IntentFilter();
        filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        context.registerReceiver(receiver, filter);
        return true;
    }


}


Enjoy with code




Saturday 20 October 2018

WorkManager jetpack in android

Hello, guys today I goes to write about android new library Jetpack component WorkManager.

 What is WorkManager?

 Workmanager is part of Android Jetpack library and an Architecture Component for background work that needs a combination of opportunity and guaranteed execution. WorkManager will take care of the care of the logic to start your work under a variety of situations, even if you navigate away from your app.

WorkManager is a flexible library that has many additional features ...

 1: Support for both asynchronous one-off and periodic tasks.
 2: Support for constraints such as network condition, storage space, and charging status
 3: Chaining of complex work requests, including running work in parallel.
 4: Output from one work request used as input for the next.
 5: Handles API level compatibility back to API level 14.
 6: Work with or without google play services
 7: Follow system health best practice.
 8: LiveData support to easily display work request state in UI.


WorkManager Components

WorkManager: Receives the work with specific arguments and enqueues that work.

Worker: Implements doWork() which executes the functionality on the background thread.

WorkRequest: Represent an individual task. It will tell you which Worker is enqueued as well as what contents it needs to meet in order for it to run. WorkRequest is an abstract class that you will be using with OneTimeWorkRequest or PerodicWorkRequest.

WorkStatus: Provide data for each WorkRequest Object.


Let's start

MainActivity.kt


class MainActivity : AppCompatActivity(),View.OnClickListener {


    private var TAG: String = MainActivity::class.java.simpleName
    private lateinit var workManager: WorkManager
    private lateinit var timeWorkRequest: OneTimeWorkRequest
    private lateinit var periodicWorkRequest: PeriodicWorkRequest

    private  var PERIODIC_REQUEST_TAG:String="periodic_request"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        workManager = WorkManager.getInstance()!!
        btnstart.setOnClickListener(this)
        btnstop.setOnClickListener(this)


    }

    private fun setupOneTimeWorker() {
        timeWorkRequest = OneTimeWorkRequest.Builder(MyWorker::class.java)?.build()
        workManager.enqueue(timeWorkRequest)
    }

    private fun setupPeriodicWorker() {

        val works = WorkManager.getInstance().getStatusesByTag(PERIODIC_REQUEST_TAG)

        if (works.value != null && works.value?.isNotEmpty()!!) {
            return        }

        val work = PeriodicWorkRequest.Builder(MyWorker::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MINUTES, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MINUTES)
        periodicWorkRequest = work.build()

         workManager.enqueue(periodicWorkRequest)

    }

    private fun requestPerodicWorkerSecondMethod(){
        val statusesByTag = workManager.getStatusesByTag(PERIODIC_REQUEST_TAG)
        if (statusesByTag == null || statusesByTag.value?.size == 0) {

        } else {
            for (i in 0 until statusesByTag.value?.size!!) {
                Log.e("TAG", " perodic request id " + statusesByTag.value?.get(i)?.id + " Status " + statusesByTag.value?.get(i)?.state)
            }
        }
    }


    override fun onClick(view: View?) {
        if (view == btnstart) {
            setupOneTimeWorker()
        } else if (view == btnstop) {
            setupPeriodicWorker()
            // or           // requestPerodicWorkerSecondMethod()        }

    }
}

MyWorker.kt


class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    private val TAG: String = MyWorker::class.java.simpleName
    override fun doWork(): Result {

        sendNotification("Title", "Details")
        return Result.SUCCESS
    }


    fun sendNotification(title: String, message: String) {
        val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        //If on Oreo then notification required a notification channel.        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        val notification = NotificationCompat.Builder(applicationContext, "default")
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)

        notificationManager.notify(1, notification.build())
    }

}


Thank you
Full Source code WorkManager-jetpack


Nougat and oreo notification



String channelId = "default";
String title = context.getString(R.string.app_name);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Foreground Notification ContextNotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);

Notification notification = notificationBuilder
        .setContentTitle(title)
        .setSmallIcon(android.R.drawable.btn_star)
        .setContentText("Alarm Counter")
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
        .setWhen(System.currentTimeMillis())
        .build();

// Notification Channelif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(channelId, title, NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Silent Notification");
    channel.setSound(null, null);
    channel.enableLights(false);
    channel.setLightColor(Color.BLUE);
    channel.enableVibration(false);
    notificationManager.createNotificationChannel(channel);

}
startForeground(1, notification);

FirebaseDispatcher android sample

Hello, guys today we learn about what is FirebaseDispatcher and how to use our android project but before know about FirebaseRequestDispatcher, we know about JobScheduler.

What is JobScheduler?

The job scheduler is an android system service available on API level 21(Lollypop). It provides an  API for scheduling unit of work that will executed in your app process.

FirebaserequestDispatcher

The firebase jobDispatcher is a library for scheduling jobs in your android app. It provides a JobScheduler compatible API that works on all recent version of Android( API 14) that have google play service installed.


Dependency

 Add following line in your project build.gradle's dependencies section

implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
How to use?

Simple extends with JobService class the JobService by default used Service class

import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class MyJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters job) {
        // Do some work here
        return false; // Answers the question: "Is there still work going on?"
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        return false; 
    }
}

Now create a simple dispatcher class and initialize google play driver

FirebaseJobDispatcher dispatcher =
    new FirebaseJobDispatcher(new GooglePlayDriver(context));


See source code 

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String JOB_TAG = "MyJobService";
    private FirebaseJobDispatcher mDispatcher;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btnstart).setOnClickListener(this);
        findViewById(R.id.btnstop).setOnClickListener(this);

        mDispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    }

    @Override    public void onClick(View view) {
        int id = view.getId();
        if (R.id.btnstart == id) {
            scheduleJob();
        } else {
            cancelJob(JOB_TAG);
        }
    }


    private void scheduleJob() {
        Job myJob = mDispatcher.newJobBuilder()
                .setService(MyJobService.class) //  your job class name                .setTag(JOB_TAG) // define your tag name                .setRecurring(true)
                .setTrigger(Trigger.executionWindow(5, 60)) // trigger job every 1 min                .setLifetime(Lifetime.UNTIL_NEXT_BOOT)
                .setReplaceCurrent(false) // if you want when open your app then job auto replace with new job then this flag make true                .setConstraints(Constraint.ON_ANY_NETWORK)
                .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR) // this is trigger linear time inteval like.. 1min,2min,3min,4min....                .build();
        mDispatcher.mustSchedule(myJob);
        Toast.makeText(this, "job_scheduled", Toast.LENGTH_LONG).show();
    }

    // cancel job    private void cancelJob(String jobTag) {
        if ("".equals(jobTag)) {
            mDispatcher.cancelAll();
        } else {
            mDispatcher.cancel(jobTag);
        }
        Toast.makeText(this, "job_cancelled", Toast.LENGTH_LONG).show();
    }
}

MyJobService.java


public class MyJobService extends JobService {
    private int ii = 0;
    private static final String TAG = "MyJobService";

    @Override    public boolean onStartJob(JobParameters jobParameters) {
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        Log.e(TAG, "Job " + currentDateTimeString);
        sendNotification("DispatcherRequest","Current noti "+currentDateTimeString);
        return false;
    }

    @Override    public boolean onStopJob(JobParameters jobParameters) {
        Log.e(TAG, "Job cancelled!");
        return false;
    }


    private void sendNotification(String contentTitle, String message) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //notificationManager.cancelAll();

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "default_notification_channel_id";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(contentTitle)
                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);


        // Since android Oreo notification channel is needed.        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(1 /* ID of notification */, notificationBuilder.build());
    }


}


Thank you
enjoy with this source code

Full Source Code FirebaseJobDispatcher