Sunday, November 19, 2017

android show notification like viber when app is in background



Manifest.xml

------------------------------------------------

<activity android:name=".pushnotification.NewMsgDialogActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar"  />







MyFirebaseMEssagingService.java

 ------------------------------------------------

 final Intent intent = new Intent(MyFirebaseMEssagingService.this, NewMsgDialogActivity.class);

        intent.putExtra("trainerId", trainer_id);

        intent.putExtra("trainer_image_str", trainer_image_str);

        intent.putExtra("trainer_name", trainer_name);


        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);


        PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseMEssagingService.this, 0, intent, 0);

        try {

            // Perform the operation associated with our pendingIntent

            pendingIntent.send();


        } catch (PendingIntent.CanceledException e) {

            e.printStackTrace();

        }




NewMsgDialogActivity.java

------------------------------------------------

public class NewMsgDialogActivity extends Activity {

    String trainerId, trainer_name, trainer_image_str = "";

    public  static  String new_msg = "";


    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        show_new_msg_dialog();

    }


    public void show_new_msg_dialog() {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);


        dialog.setTitle(getResources().getString(R.string.new_msg))

                .setCancelable(false)

                .setIcon(R.drawable.messages_icon)

                .setMessage(NewMsgDialogActivity.new_msg)

                .setNegativeButton("Ignore", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialoginterface, int i) {

                        dialoginterface.dismiss();

                        finish();

                    }

                })

                .setPositiveButton("Check", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialoginterface, int i) {

                        goto_voice_msg_activity();

                        dialoginterface.dismiss();

                        finish();

                    }

                }).show();

    }



    @Override

    public void onBackPressed() {

        super.onBackPressed();

        finish();

    }

}



android check app is running foreground

static boolean shouldShowNotification(Context context) {
        ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
        ActivityManager.getMyMemoryState(myProcess);
        if (myProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
            return true;

        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        // app is in foreground, but if screen is locked show notification anyway
        return km.inKeyguardRestrictedInputMode();
    }

android voice recorder

Wednesday, April 19, 2017

java binary tree







// ref: http://javabeat.net/binary-search-tree-traversal-java/

package binarysearchtreedemo;

public class BinarySearchTreeDemo {

    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();

        int[] nums = {40, 25, 78, 10, 32};
//        int[] nums = {10, 20, 0, 5, 15};
        for (int i : nums) {
            bst.insert(i);
        }
//        System.out.println("Inorder traversal");
//        bst.printInorder();

        System.out.println("Preorder Traversal");
        bst.printPreorder();

//        System.out.println("Postorder Traversal");
//        bst.printPostorder();
//
//        System.out.println("The minimum value in the BST: " + bst.findMinimum());
//        System.out.println("The maximum value in the BST: " + bst.findMaximum());
        System.out.println("Print Same Level Node: "  );
        bst.printSameLevelNode(3);
   
    }
}



------------------------------------------------------------------------------------------------------------------


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package binarysearchtreedemo;

import java.util.ArrayList;

/**
 * Represents the Binary Search Tree.
 */
public class BinarySearchTree {

    //Refrence for the root of the tree.
    public Node root;

    ArrayList<Integer> nodeAl = new ArrayList<Integer>();

    int level_no, count = 0,tree_height, desired_level;

    public BinarySearchTree insert(int value) {
        Node node = new Node(value);

        if (root == null) {
            root = node;
            return this;
        }

        insertRec(root, node);
        return this;
    }

    private void insertRec(Node latestRoot, Node node) {

        if (latestRoot.value > node.value) {

            if (latestRoot.left == null) {
                latestRoot.left = node;
//        return;
            } else {
                insertRec(latestRoot.left, node);
            }
        } else {
            if (latestRoot.right == null) {
                latestRoot.right = node;
//        return;
            } else {
                insertRec(latestRoot.right, node);
            }
        }
    }

    public void printSameLevelNode(int _desired_level) {

//        level_no = _level_no;
//        printSameLevelNode(root);
//        nodeAl.clear();
        tree_height = height(root);
        desired_level = _desired_level;
        System.out.println("height=" + tree_height);

        int i;
//        for (i = 1; i <= h; i++) {
//            printGivenLevel(root, i);
//        }
        if(desired_level>tree_height || desired_level<=0)
        {
            System.out.print("Highest level number can be 1 to "+tree_height);
        }
        else
        {
            printGivenLevel(root, desired_level);
            
        }
        System.out.print("\n");
        

    }

    /* Print nodes at the given level */
    void printGivenLevel(Node root, int level) {
        if (root == null) {
            
            return;
        }
        if (level == 1) {
            
            count++;
            if(count==1)
            {
                System.out.print("Level "+ desired_level+" Nodes are: ");
            }
            
            System.out.print(root.value + " ");
        } else if (level > 1) {
            printGivenLevel(root.left, level - 1);
            printGivenLevel(root.right, level - 1);
        }
    }

    int height(Node root) {
        if (root == null) {
            return 0;
        } else {
            /* compute  height of each subtree */
            int lheight = height(root.left);
            int rheight = height(root.right);

            /* use the larger one */
            if (lheight > rheight) {
                return (lheight + 1);
            } else {
                return (rheight + 1);
            }
        }
    }

    public void printSameLevelNode(Node _currRoot) {

        Node currNode = _currRoot;

        System.out.println("parent Node=" + currNode.value + " left child=" + currNode.left.value + " right child=" + currNode.right.value);

        for (int i = 0; i <= level_no; i++) {
            if (i == level_no) {
//                nodeAl.add(currNode.left.value);
//                nodeAl.add(currNode.right.value);
            } else {
                printSameLevelNode(currNode.left);
                printSameLevelNode(currNode.right);
            }
        }

//        System.out.println("nodeAl=" + nodeAl);
    }

    /**
     * Returns the minimum value in the Binary Search Tree.
     */
    public int findMinimum() {
        if (root == null) {
            return 0;
        }
        Node currNode = root;
        while (currNode.left != null) {
            currNode = currNode.left;
            System.out.println("currNode=" + currNode.value);
        }
        return currNode.value;
    }

    /**
     * Returns the maximum value in the Binary Search Tree
     */
    public int findMaximum() {
        if (root == null) {
            return 0;
        }

        Node currNode = root;
        while (currNode.right != null) {
            currNode = currNode.right;
        }
        return currNode.value;
    }

    /**
     * Printing the contents of the tree in an inorder way.
     */
    public void printInorder() {
        printInOrderRec(root);
        System.out.println("");
    }

    /**
     * Helper method to recursively print the contents in an inorder way
     */
    private void printInOrderRec(Node currRoot) {
        if (currRoot == null) {
            return;
        }
        printInOrderRec(currRoot.left);
        System.out.print(currRoot.value + ", ");
        printInOrderRec(currRoot.right);
    }

    /**
     * Printing the contents of the tree in a Preorder way.
     */
    public void printPreorder() {
        printPreOrderRec(root);
        System.out.println("");
    }

    /**
     * Helper method to recursively print the contents in a Preorder way
     */
    private void printPreOrderRec(Node currRoot) {
        if (currRoot == null) {
            return;
        }
        System.out.print(currRoot.value + ", ");
        printPreOrderRec(currRoot.left);
        printPreOrderRec(currRoot.right);
    }

    /**
     * Printing the contents of the tree in a Postorder way.
     */
    public void printPostorder() {
        printPostOrderRec(root);
        System.out.println("");
    }

    /**
     * Helper method to recursively print the contents in a Postorder way
     */
    private void printPostOrderRec(Node currRoot) {
        if (currRoot == null) {
            return;
        }
        printPostOrderRec(currRoot.left);
        printPostOrderRec(currRoot.right);
        System.out.print(currRoot.value + ", ");

    }
}


------------------------------------------------------------------------------------------------------------------


package binarysearchtreedemo;


public class Node {
  //The value present in the node.
  public int value;

  //The reference to the left subtree.
  public Node left;

  //The reference to the right subtree.
  public Node right;

  public Node(int value) {
    this.value = value;
  }

}

------------------------------------------------------------------------------------------------------------------

output:

Preorder Traversal
40, 25, 10, 32, 78,
Print Same Level Node:
height=3
Level 3 Nodes are: 10 32 

Monday, March 20, 2017

java thread Wait & Notify example

WaitNotifyTest .java
------------------------------------------------------



package waitnotifytest;

public class WaitNotifyTest {

    public static void main(String[] args) {
        Message msg = new Message("process it");
        Waiter waiter = new Waiter(msg);
        new Thread(waiter,"waiter_1").start();
       
        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1, "waiter2").start();
       
        Notifier notifier = new Notifier(msg);
        new Thread(notifier, "notifier").start();
        System.out.println("All the threads are started");
    }

}







Waiter.java
----------------------------------------------------------------------

package waitnotifytest;

import java.util.Date;

public class Waiter implements Runnable{
   
    private Message msg;
   
    public Waiter(Message m){
        this.msg=m;
    }

    @Override
    public void run() {
        String thread_name = Thread.currentThread().getName();
       
        synchronized (msg) {
            try{
                System.out.println(thread_name+" waiting to get notified at time:"+System.currentTimeMillis()+ " min="+new Date().getMinutes()+" sec=" + new Date().getSeconds());
                msg.wait();
                System.out.println("--wait()");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(thread_name+" after wait at time:"+System.currentTimeMillis()+ " min="+new Date().getMinutes()+" sec="  + new Date().getSeconds());
            //process the message now
            System.out.println(thread_name+" processed: "+msg.getMsg());
        }
    }

}








Notifier.java
------------------------------------------------------

package waitnotifytest;

public class Notifier implements Runnable {

    private Message msg;
   
    public Notifier(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        String thread_name = Thread.currentThread().getName();
        System.out.println(thread_name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg("Notifier thread_name=" + thread_name+" Notifier work done");
//                msg.notify();
                 msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
    }

}


Message.java
-----------------------------------------------------------------------------------
package waitnotifytest;

public class Message {
    private String msg;
   
    public Message(String str){
        this.msg=str;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String str) {
        this.msg=str;
    }

}



###############output#################
All the threads are started
notifier started
waiter_1 waiting to get notified at time:1490077406336 min=23 sec=26
waiter2 waiting to get notified at time:1490077406342 min=23 sec=26
--wait()
waiter2 after wait at time:1490077407336 min=23 sec=27
waiter2 processed: Notifier thread_name=notifier Notifier work done
--wait()
waiter_1 after wait at time:1490077407336 min=23 sec=27
waiter_1 processed: Notifier thread_name=notifier Notifier work done

java thread & synchronized example

package threadjoinexample;

import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadJoinExample {

    public static void main(String[] args) {
        Table mTable = new Table();//only one object 
       
        Thread t1 = new Thread(new MyRunnable(mTable), "1st");
        Thread t2 = new Thread(new MyRunnable(mTable), "2nd");
        Thread t3 = new Thread(new MyRunnable(mTable), "3rd");

        t1.start();

        //start second thread after waiting for 2 seconds or if it's dead
//        try {
////            t1.join(2000);
//            System.out.println("1st try");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }
        t2.start();

        //checks if this thread is alive
        System.out.println(t1.getName() + "=, isAlive = " + t1.isAlive());

        //start third thread only when first thread is dead
//        try {
////            t1.join();
//            System.out.println("2nd block  try="+t1.getName());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            t2.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }
        t3.start();
       
        try {
            t3.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoinExample.class.getName()).log(Level.SEVERE, null, ex);
        }

        //let all threads finish execution before finishing main thread
//        try {
//
////            t1.join();
//
//            System.out.print(t2.getName());
//            //checks if this thread is alive
//            System.out.println(", t2 isAlive = " + t2.isAlive());
//
////            t2.join();
////            t3.join();
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable {
    Table t;
   
    MyRunnable(Table t) {
        this.t = t;
    }

    synchronized void test() {
        for (int i = 1; i <= 5; i++) {
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println(i*100 + " " + Thread.currentThread().getName());
        }
    }

    @Override
    public void run() {
        System.out.println("--Thread started:::" + Thread.currentThread().getName());
        t.printTable(100);
//        test();
//        try {
//            Thread.sleep(4000);
//            System.out.println("run() 4s after=" + Thread.currentThread().getName());
//
//            test();
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        System.out.println("!--Thread ended:::" + Thread.currentThread().getName()+"\n\n");
    }

}

class Table {

    synchronized void printTable(int n) {//synchronized method 
        for (int i = 1; i <= 5; i++) {
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println(i*100 + " " + Thread.currentThread().getName());
        }

    }
}