Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, 18 April 2023

AndroidTv Sample

 Hi friends


After long time i again write blogs for you, i hope you doing well, so today in this post we are learn about how to create Android TV app in android studio. So i explain step to step and every class and component what's exactly works. 


So let's start without loss moment....


First you create app as like you create your android app and select Android Tv from options. Now you select No Activity. Actully we can choose Empty Activity but so more code comes in project so very difficult for understanding which component what is works. So we are fallow very simple way and understand one by one component .
Please follow steps...



Add fragment
<?xml version="1.0" encoding="utf-8"?>
<fragment 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:id="@+id/main_browse_fragment"
android:name="com.tech.yourapp.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />

class MainFragment : BrowseSupportFragment() {





Now 

At first, let’s make activity. Right click on “com.tech.yourapp”, and choose

New -> Activity -> Blank activity


Check “Launcher Activity”.


I will start from making blank activity, named “MainActivity“. 

Next, we want to design UI of MainActivity by creating MainFragment.

Right click on the package name (in my case com.tech.yourapp)


New -> Java Class -> Name: MainFragment


*  Instead of above procedure, if we choose New -> Fragment -> Blank fragment Uncheck “Create layout XML?”, it makes too match sample source code.


First, modify activity_main.xml as follows so that it only displays mainfragment.

* Click right-top “<>” icon on the code, if you want to copy & paste


Second modify MainFragment as follows.

We will make this MainFragment as a sub-class of BrowseSupportFragment.

BrowseSupportFragment class is supplied by Android SDK Leanback library, and it creates standard UI for Android TV application which we will see through this Tutorial.



override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_main, container, false)
}


}

Now build and run it

For more info Please go to github





Saturday, 13 June 2020

ThreadPoolExecuter in java

Hello Friends,

If you are working with thread and want to use more better thread so know about ThreadpoolExecuter.


Why you need threadpool?
If you create any simple application and create some of runnable objets and create corresponding thread and execute them. The creating and executing every thread every time this is very complex work and reduce the app performance also.

How to work threadpool ?
Threadpool is collection of pre-initialised thread. Generally the size if the collection is fixed but it is not mandatory. Its facilitated to execute N number of task using the same thread and task need to wait in queue like FIFO. When any task is completed of execution i can pickup the new task from the queue and start execution.

See image to understand



What is threadpoolExecuter?
Java 5 is introducing Executer  interface and ExecuterService. ThreadPoolExecuter is class and implement these both interfaces.
ThreadPoolExecuter is separate the task creation and execution. In ThreadPoolExecuter  you have can implement runnable object and send them to executer. It's responsible for execution, instantiation and running with particular thread.

How to create ThreadPoolExecuter?
We can create 5 types-:

Fixed thread pool executer: Create thread pool that reuse fixed number of thread to execute any number of thread. When additional task are submitted when all thread are active, they will wait in queue until thread  available its is the best example for real-life use.


  ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newFixedThreadPool(10);

Cached thread pool executer: Create a thread pool that is create new thread as needed but reuse perviously constructed thread if they are available.  Do not reuse this thread pool if task are long-running. 

ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newCachedThreadPool();


Single thread pool executer:  Create single thread to execute all tasks. Its use when you want to execute single task.

ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newSingleThreadPool();

Work stealing pool executer: Create a thread pool that maintain the enough thread to support the given parallelism level. Here  parallelism level means the maximum number of thread which will be used execute a given task, at single point of time, in multi-processor machine.

ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newWorkStealingThreadPool();


Lets see example ...

MyTask.java

package com.samset.threads;
 
import java.util.concurrent.TimeUnit;
 
public class MyTask implements Runnable {
    private String name;
 
    public MyTask(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void run() {
        try {
            Long duration = (long) (Math.random() * 10);
            System.out.println("Executing : " + name);
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


Execute task with threadpoolexecuter

package com.samset.threads;
 
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
 
public class ThreadPoolExample
{
    public static void main(String[] args)
    {
        ThreadPoolExecutor executor = (ThreadPoolExecutor)
Executors.newFixedThreadPool(2);
         
        for (int i = 1; i <= 5; i++)
        {
            MyTask task = new MyTask("Task " + i);
            System.out.println("Created : " + task.getName());
 
            executor.execute(task);
        }
        executor.shutdown();
    }
}


Output:

Created : Task 1
Created : Task 2
Created : Task 3
Created : Task 4
Created : Task 5
Executing : Task 1
Executing : Task 2
Executing : Task 3
Executing : Task 4
Executing : Task 5


ScheduledThreadExecutor: Fixed thread pools or cached thread pools are good when you have one unique task only once. When you need to execute a task repeatedly N times, either N fixed number of time or infinitely after fixed delay, you should be using ScheduledThreadPoolExecuter.
ScheduledThreadPoolExecuter provide 4 methods with different capability.
(1). Schedulefuture schedule(Runnable run,long deley,Timeunit unit)--> Create and executes a task that become enabled after the given delay.

(2). Schedulefuture schedule(Callable run,long deley,Timeunit unit)--> Create and executes a task schedulefuture that become enabled after the given delay.

(3). Schedulefuture scheduleAtFixedRate(Runnable run,long initialdelay,long deley,Timeunit unit)--> Create and executes periodic action that become enable first after the given initial delay, and subsequently with the given time period. If any execution of this task takes longer time than its period, then subsequent execution may start late, but will not concurrently execute.

(4). Schedulefuture scheduleAtFixedDelay(Runnable run,long initialdelay,long deley,Timeunit unit)--> Create and executes periodic action that become enable first after the given initial delay, and subsequently with the given time period. No matter how much time a long running task takes, there will be a fixed delay time gab between two execution.




package com.samset.threads;
 
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class ScheduledThreadPoolExecutorExample
{
    public static void main(String[] args)
    {
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2);
         
        Task task = new Task("Repeat Task");
        System.out.println("Created : " + task.getName());
         
        executor.scheduleWithFixedDelay(task, 2, 2, TimeUnit.SECONDS);
    }
}
 
class Task implements Runnable {
    private String name;
 
    public Task(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void run() {
        System.out.println("Executing : " + name + ", Current Seconds : " + new Date().getSeconds());
    }
}

Output:

Created : Repeat Task
Executing : Repeat Task, Current Seconds : 36
Executing : Repeat Task, Current Seconds : 38
Executing : Repeat Task, Current Seconds : 41
Executing : Repeat Task, Current Seconds : 43
Executing : Repeat Task, Current Seconds : 45
Executing : Repeat Task, Current Seconds : 47



Thanks,
I hope now you better understand what is executer and how to work enjoy my friends.