Month: May 2016

  • How to answer incoming call programmatically in Android

    How to answer incoming call programmatically in Android

    Here is example for accepting incoming calls programmatically

    The most stable version is using adb shell feature.

    Call can be answered by sending command “adb shell input keyevent 79” via Terminal

    Same thing can be done programmatically.

    But, it works good for user-driven answering and this solution good for custom call screen.
    It will not work for any sort of automated call-control-type applications.
    Like auto answering via BroadcastReceivers etc.

    Screenshot 2016-05-26 13.54.20

    try {
        Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
    } catch (IOException e) {
       //handle error here
    }

    Awaiting comments. Let me know the better ways.

  • Epson XP-103 ink pad counter reset for FREE

    Epson XP-103 ink pad counter reset for FREE

    My printer has stop working and “paper” and “ink” start blinking.

    This happens when printer’s ink pads are full

    From manual:
    Screenshot 2016-05-23 01.16.54
    “The printer’s ink pads are nearing or at the end of their service life. Contact Epson Support to replace ink pads. When the printer’s ink pads are nearing the end of their service life, you can resume printing by pressing x r or r x. The paper light and the ink light ash alternately.”

    I’ve opened printer and clean ink pads.

    After that I need reset counter. To do it I’ve downloaded iWIC tool software.

    WIC Reset Utility for Windows (ZIP, 2.56 mB)
    iWIC for Mac OS 10.6 Intel and higher (iWIC.dmg)
    WIC for Linux

    Download Free

    Screenshot 2016-05-23 01.20.19

    This software require key. But you can use “trial” or “TRIAL” software for one free resetting.

    Hope it helps.

    Let me know if you know better FREE method. I’ll need it in future 🙂

  • Image loading in Android.

    Image loading in Android.

    There a lot libraries for loading images. Lets talk about couple of them.

    1. Picasso (http://square.github.io/picasso/)

    dependency

    dependencies {
        compile 'com.squareup.picasso:picasso:2.5.1'
    }

    This library easy to use. To load image from url to ImageView you need do just one line.

    Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
    

    Current library have a features which can be useful for your app:

      • Image transformation
    Picasso.with(context)
      .load(url)
      .resize(50, 50)
      .centerCrop()
      .into(imageView)
      • Placeholder for progress and error. Useful to show some drawable if downloading failed or in progress
    Picasso.with(context)
        .load(url)
        .placeholder(R.drawable.user_placeholder)
        .error(R.drawable.user_placeholder_error)
        .into(imageView);
      • Using Picasso you can load images from resources, file or web
    Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
    Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
    Picasso.with(context).load(new File(...)).into(imageView3);
    1. Glide (https://github.com/bumptech/glide)

    Current library is recommended by Google.

    dependency

    dependencies {
        compile 'com.github.bumptech.glide:glide:3.5.2'
        compile 'com.android.support:support-v4:22.0.0'
    }

    Usage:

    Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);

    Also Glide has a features:

    Glide
        .with(myFragment)
        .load(url)
        .centerCrop()
        .placeholder(R.drawable.loading_spinner)
        .crossFade()
        .into(myImageView);

    I use Glide because:
    1. Faster than Picaso
    2. Have better “.with()” method. Glide.with(this) can take Context, Fragment, Activity, etc.

    Currently Glide better Image loader library.

    Awaiting your comments.

  • iPhone to Android and Android to iPhone density converter

    iPhone to Android and Android to iPhone density converter

    I use this coefficients when I need convert iOS assets to Android or Android to iOS.

    MDPI / BASE = 100

    TVDPI = 133

    HDPI = 150

    XHDPI / RETINA = 200

    XXHDPI = 300

    XXXHDPI = 400

  • How to make single debug.keystore for whole android team or signing with Gradle

    How to make single debug.keystore for whole android team or signing with Gradle

    Problem happens when you have more than one developer in the Android team or you develop project from different computers.

    Some APIs or functionality depends on keystore which sign the APK. For example Facebook API.

    To make life easier you need keep your debug.keystore same for all your computers/developers.

    But, it isn’t solution!

    How to make it?

    You can keep debug.keystore in your project and link it for signing automatically.
    Gradle help with it.

    Here is gradle config with current functionality.

    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.3"
    
        signingConfigs {
            debug {
                storeFile file('../keystore/debug.keystore.jks')
                storePassword "android"
                keyAlias "android"
                keyPassword "android"
            }
            
            release {
                storeFile file('../keystore/release.keystore.jks')
                storePassword "releaseStorePassHere"
                keyAlias "releaseAliasHere"
                keyPassword "releaseKeyPassHere"
            }
        }
    
        defaultConfig {
            applicationId "com.hrupin.sampleapp"
            minSdkVersion 21
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                zipAlignEnabled true
                minifyEnabled true
            }
        }
    }
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.3.0'
    }

    The important part is here:

    signingConfigs {
            debug {
                storeFile file('../keystore/debug.keystore.jks')
                storePassword "android"
                keyAlias "android"
                keyPassword "android"
            }
            
            release {
                storeFile file('../keystore/release.keystore.jks')
                storePassword "releaseStorePassHere"
                keyAlias "releaseAliasHere"
                keyPassword "releaseKeyPassHere"
            }
        }

    storeFile file(‘../keystore/debug.keystore.jks’) – related path to keystore

    Nice coding!

  • Android Loop Tabs Sample

    Android Loop Tabs Sample

    Here is sample for loop tabs in Android.

    Video with sample application in action

    Lets show how it works.

    1. I have Tab enum which describe Tab element. Also you can handle tab state. I don’t do it in this sample.

    package com.hrupin.looptabs.infinitetabbar;
    
    import com.hrupin.looptabs.R;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03/05/16.
     */
    public enum Tab {
        TAB_1(R.drawable.ic_tab_1_act, R.drawable.ic_tab_1, 0),
        TAB_2(R.drawable.ic_tab_2_act, R.drawable.ic_tab_2, 1),
        TAB_3(R.drawable.ic_tab_3_act, R.drawable.ic_tab_3, 2);
    
        private final int resActive;
        private final int resInctive;
        private final int index;
    
        public int getResActive() {
            return resActive;
        }
    
        public int getResInctive() {
            return resInctive;
        }
    
        public int getIndex() {
            return index;
        }
    
        Tab(int resActive, int resInctive, int index) {
            this.resActive = resActive;
            this.resInctive = resInctive;
            this.index = index;
        }
    }
    

    2. Project has View for tabs which extended from TabCloneableView. Here you can work around tab state. And tab transition between tabs.

    package com.hrupin.looptabs.infinitetabbar;
    
    import android.content.Context;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import com.hrupin.looptabs.R;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03/05/16.
     */
    public class TabView extends TabCloneableView {
    
        private static final String TAG = "TabView";
    
        public enum State {
            INACTIVE, INACTIVE_PRESSED, ACTIVE, ACTIVE_PRESSED;
        }
    
        private Tab tab;
        private State state = State.INACTIVE;
        private ImageView ivInActive;
        private ImageView ivActive;
        private TextView tvIndex;
    
        public TabView(Context context) {
            super(context);
            View.inflate(context, R.layout.item_tab, this);
            this.ivInActive = (ImageView) findViewById(R.id.iv_inactive);
            this.ivActive = (ImageView) findViewById(R.id.iv_active);
            this.tvIndex = (TextView) findViewById(R.id.index);
        }
    
        public TabView clone() {
            TabView vw = new TabView(this.getContext());
            vw.switchState(State.INACTIVE);
            vw.setId((int) (Math.random() * 10000));
            vw.setTag(this.getTag());
            vw.setTab(this.getTab());
            return vw;
        }
    
        public void setTab(Tab tab) {
            this.tab = tab;
            this.ivActive.setImageResource(tab.getResActive());
            this.ivInActive.setImageResource(tab.getResInctive());
            this.tvIndex.setText(tab.getIndex() + "");
        }
    
        public Tab getTab() {
            return tab;
        }
    
        public State getState() {
            return state;
        }
    
        public void switchState(State state) {
            this.state = state;
            switch (state) {
                case ACTIVE:
                    this.ivActive.setAlpha(1f);
                    this.ivInActive.setAlpha(0f);
                    break;
                case INACTIVE:
                    this.ivActive.setAlpha(0f);
                    this.ivInActive.setAlpha(1f);
                    break;
                case ACTIVE_PRESSED:
                    this.ivActive.setAlpha(0.6f);
                    this.ivInActive.setAlpha(0f);
                    break;
                case INACTIVE_PRESSED:
                    this.ivActive.setAlpha(0f);
                    this.ivInActive.setAlpha(0.6f);
                    break;
            }
        }
    
        public void setPositionOffset(boolean isNext, float positionOffset) {
            float activeAlpha = positionOffset;
            float inActiveAlpha = 1f - positionOffset;
            if (isNext) {
                this.ivActive.setAlpha(activeAlpha);
                this.ivInActive.setAlpha(inActiveAlpha);
            } else {
                this.ivActive.setAlpha(inActiveAlpha);
                this.ivInActive.setAlpha(activeAlpha);
            }
        }
    
        @Override
        public String toString() {
            return "TV{" +
                    "t=" + tab +
                    //", state=" + state +
                    ",i=" + tab.getIndex() +
                    '}';
        }
    }

    3. TabCloneableView class

    package com.hrupin.looptabs.infinitetabbar;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.widget.RelativeLayout;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03/05/16.
     */
    
    public abstract class TabCloneableView extends RelativeLayout {
    
    	public TabCloneableView(Context context) {
    		super(context);
    		// TODO Auto-generated constructor stub
    	}
    	public TabCloneableView(Context context, AttributeSet attrs) {
    		super(context,attrs);
    		
    		// TODO Auto-generated constructor stub
    	}
    	public abstract TabCloneableView clone();
    }
    

    4. The most of magic located in the TabInfiniteScrollView. This View contains TabView objects and work with them.

    package com.hrupin.looptabs.infinitetabbar;
    
    import android.app.Activity;
    import android.content.Context;
    import android.os.Handler;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.FrameLayout;
    import android.widget.RelativeLayout;
    
    import com.hrupin.looptabs.looppager.LoopViewPager;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03/05/16.
     */
    
    public class TabInfiniteScrollView extends FrameLayout implements View.OnTouchListener {
        private static final String TAG = "TabInfiniteScrollView";
    
        private final static int SWIPE_OR_CLICK_ACTION_THRESHHOLD = 150;
    
        private static boolean touchDown = false;
        private final float tabWidth;
    
        private Context context;
        private ArrayList<TabCloneableView> carouselItems;
        private TabCloneableView replicaF, replicaB;
        private int itemCount = 0;
        private float scrollX;
        private float firstX;
        private float firstY;
        private TabSize itemSize;
        private boolean isScrolling = false;
        private LoopViewPager viewPager;
    
        public TabInfiniteScrollView(Context ctx, TabSize itemsize) {
            super(ctx);
            context = ctx;
            itemSize = itemsize;
            tabWidth = itemSize.width;
            RelativeLayout.LayoutParams sparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            this.setClipChildren(true);
            this.setLayoutParams(sparams);
            this.setOnTouchListener(this);
            carouselItems = new ArrayList<TabCloneableView>();
            setHorizontalScrollBarEnabled(false);
        }
    
        @Override
        public boolean onInterceptHoverEvent(MotionEvent event) {
            //return super.onInterceptHoverEvent(event);
            return false;
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            //return super.onInterceptTouchEvent(ev);
            return false;
        }
    
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    firstX = arg1.getX();
                    firstY = arg1.getY();
                    touchDown = true;
                    if (isLeftTab()) {
                        //TODO handle tab state
                    } else if (isRightTab()) {
                        //TODO handle tab state
                    } else {
                        //TODO handle tab state
                    }
                    return true;
                case MotionEvent.ACTION_UP: {
                    touchDown = false;
                    float finishX = arg1.getX();
                    float finishY = arg1.getY();
                    if (isAClick(firstX, finishX, firstY, finishY)) {
                        if (isLeftTab()) {
                            swipeLeft(true);
                        } else if (isRightTab()) {
                            swipeRight(true);
                        }
                    } else {
                        if (isLeftTab()) {
                            //TODO handle tab state
                        } else if (isRightTab()) {
                            //TODO handle tab state
                        } else {
                            //TODO handle tab state
                        }
                    }
                    firstX = 0;
                    firstY = 0;
                }
                case MotionEvent.ACTION_OUTSIDE: {
                    if (isLeftTab()) {
                        //TODO handle tab state
                    } else if (isRightTab()) {
                        //TODO handle tab state
                    } else {
                        //TODO handle tab state
                    }
                }
                case MotionEvent.ACTION_MOVE:
                    float finishX = arg1.getX();
                    if (touchDown) {
                        float differenceX = firstX - finishX;
                        if (Math.abs(differenceX) > SWIPE_OR_CLICK_ACTION_THRESHHOLD) {
                            if (differenceX > 0) {
                                swipeRight(true);
                            } else {
                                swipeLeft(true);
                            }
                        }
                    }
                    break;
            }
            return false;
        }
    
        private boolean isRightTab() {
            return firstX > 2 * tabWidth && firstX < 3 * tabWidth;
        }
    
        private boolean isLeftTab() {
            return firstX > 0 && firstX < tabWidth;
        }
    
        public void swipeLeft(boolean triggerViewPager) {
            swipe(tabWidth);
            if(triggerViewPager) {
                viewPager.swipeLeft();
            }
        }
    
        public void swipeRight(boolean triggerViewPager) {
            swipe(-tabWidth);
            if(triggerViewPager) {
                viewPager.swipeRight();
            }
        }
    
        private void swipe(final float delta) {
            if (!isScrolling) {
                isScrolling = true;
                final float step = delta / 10f;
                scrollX = step;
                new ScrollTimerTask().run();
                final Handler handler = new Handler();
                final java.util.concurrent.atomic.AtomicInteger n = new AtomicInteger(1);
                final Runnable counter = new Runnable() {
                    @Override
                    public void run() {
                        if (n.getAndIncrement() == 11) {
                            isScrolling = false;
                            touchDown = false;
                            firstX = 0;
                            scrollX = 0;
                        } else {
                            new ScrollTimerTask().run();
                            handler.postDelayed(this, 10);
                        }
                    }
                };
                handler.postDelayed(counter, 10);
            }
        }
    
        private boolean isAClick(float startX, float endX, float startY, float endY) {
            float differenceX = Math.abs(startX - endX);
            float differenceY = Math.abs(startY - endY);
            if (differenceX > SWIPE_OR_CLICK_ACTION_THRESHHOLD || differenceY > SWIPE_OR_CLICK_ACTION_THRESHHOLD) {
                return false;
            }
            return true;
        }
    
        public void setViewPager(LoopViewPager viewPager) {
            this.viewPager = viewPager;
        }
    
        public class ScrollTimerTask implements Runnable {
            public synchronized void arrangeViews() {
                if (Math.abs(scrollX) > 0.1f) {
                    //Log.i(TAG, "arrangeViews");
                    synchronized (carouselItems) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            public void run() {
                                Collections.sort(carouselItems,
                                        new Comparator<View>() {
                                            @Override
                                            public int compare(View lhs, View rhs) {
                                                FrameLayout.LayoutParams lhsParams = (FrameLayout.LayoutParams) lhs.getLayoutParams();
                                                FrameLayout.LayoutParams rhsParams = (FrameLayout.LayoutParams) rhs.getLayoutParams();
                                                return ((Integer) lhsParams.leftMargin).compareTo((Integer) rhsParams.leftMargin);
                                            }
                                        });
                                for (int i = 0; i < carouselItems.size(); i++) {
                                    // arrange
                                    TabCloneableView vw = carouselItems.get(i);
                                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) vw.getLayoutParams();
                                    if (i == 0) {
                                        params.leftMargin += scrollX;
                                    } else {
                                        FrameLayout.LayoutParams fparams = (FrameLayout.LayoutParams) carouselItems.get(0).getLayoutParams();
                                        params.leftMargin = (int) (fparams.leftMargin + (i * itemSize.width));
                                    }
                                    if (vw != replicaF && vw != replicaB) {
                                        if (scrollX > 0) {
                                            if (params.leftMargin > ((itemCount - 1) * itemSize.width) && params.leftMargin <= (itemCount * itemSize.width)) {
                                                FrameLayout.LayoutParams rparams = null;
                                                if (replicaF == null) {
                                                    replicaF = vw.clone();
                                                    rparams = new FrameLayout.LayoutParams((int) itemSize.width, (int) itemSize.height);
                                                    rparams.leftMargin = (int) -itemSize.width;
                                                    replicaF.setLayoutParams(rparams);
                                                }
                                                if (TabInfiniteScrollView.this.findViewById(replicaF.getId()) == null) {
                                                    TabInfiniteScrollView.this.addView(replicaF);
                                                    carouselItems.add(0, replicaF);
                                                }
                                            }
                                            if (params.leftMargin >= (itemCount * itemSize.width)) {
                                                if (replicaF != null) {
                                                    if (TabInfiniteScrollView.this.findViewById(replicaF.getId()) != null) {
                                                        TabInfiniteScrollView.this.removeView(replicaF);
                                                        carouselItems.remove(replicaF);
                                                        carouselItems.remove(vw);
                                                        carouselItems.add(0, vw);
                                                        i = 0;
                                                        params.leftMargin = 0;
                                                    }
                                                }
                                                replicaF = null;
                                            }
                                        } else {
                                            if (params.leftMargin < 0 && params.leftMargin >= -itemSize.width) {
                                                FrameLayout.LayoutParams rparams = null;
                                                if (replicaB == null) {
                                                    replicaB = vw.clone();
                                                    rparams = new FrameLayout.LayoutParams((int) itemSize.width, (int) itemSize.height);
                                                    rparams.leftMargin = (int) ((itemCount - 1) * itemSize.width);
                                                    replicaB.setLayoutParams(rparams);
                                                }
                                                if (TabInfiniteScrollView.this.findViewById(replicaB.getId()) == null) {
                                                    TabInfiniteScrollView.this.addView(replicaB);
                                                    carouselItems.add(replicaB);
                                                }
                                            }
                                            if (params.leftMargin < -itemSize.width) {
                                                if (replicaB != null) {
                                                    if (TabInfiniteScrollView.this.findViewById(replicaB.getId()) != null) {
                                                        TabInfiniteScrollView.this.removeView(replicaB);
                                                        carouselItems.remove(replicaB);
                                                        carouselItems.remove(vw);
                                                        carouselItems.add(vw);
                                                        i = 0;
                                                        params.leftMargin = (int) (itemCount * itemSize.width);
                                                    }
                                                }
                                                replicaB = null;
                                            }
                                        }
                                    }
                                    vw.setLayoutParams(params);
                                }
    
                                if (replicaF != null) {
                                    FrameLayout.LayoutParams fparams = (FrameLayout.LayoutParams) replicaF.getLayoutParams();
                                    if (fparams.leftMargin < -itemSize.width || fparams.leftMargin > 0) {
                                        if (TabInfiniteScrollView.this.findViewById(replicaF.getId()) != null) {
                                            replicaF.getLayoutParams();
                                            TabInfiniteScrollView.this.removeView(replicaF);
                                            carouselItems.remove(replicaF);
                                        }
                                        replicaF = null;
                                    }
                                }
                                Collections.sort(carouselItems,
                                        new Comparator<View>() {
                                            @Override
                                            public int compare(View lhs, View rhs) {
                                                FrameLayout.LayoutParams lhsParams = (FrameLayout.LayoutParams) lhs.getLayoutParams();
                                                FrameLayout.LayoutParams rhsParams = (FrameLayout.LayoutParams) rhs.getLayoutParams();
                                                return ((Integer) lhsParams.leftMargin).compareTo((Integer) rhsParams.leftMargin);
                                            }
    
                                        });
                                Log.i(TAG, carouselItems + "");
                            }
                        });
                    }
                }
    
            }
    
            @Override
            public void run() {
                arrangeViews();
            }
        }
    
        public void addItem(TabCloneableView vw) {
            FrameLayout.LayoutParams rparams = new FrameLayout.LayoutParams((int) itemSize.width, (int) itemSize.height);
            rparams.leftMargin = (int) (carouselItems.size() * itemSize.width);
            vw.setLayoutParams(rparams);
            super.addView(vw, carouselItems.size());
            carouselItems.add(vw);
            itemCount = carouselItems.size();
        }
    }

    5. TabSize class

    package com.hrupin.looptabs.infinitetabbar;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03/05/16.
     */
    
    public class TabSize {
    	float height;
    	float width;
    	public TabSize(float w, float h){
    		width = w;
    		height = h;
    	}
    	
    }
    

    6. And the Activity

    package com.hrupin.looptabs;
    
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.DisplayMetrics;
    import android.view.Window;
    
    import com.hrupin.looptabs.infinitetabbar.TabBar;
    import com.hrupin.looptabs.looppager.LoopViewPager;
    import com.hrupin.looptabs.looppager.TabAdapter;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03/05/16.
     */
    
    public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
    
        private static final String TAG = "MainActivity";
    
        private LoopViewPager viewPager;
        private TabAdapter adapter;
        private int tabWidth;
        private int tabHeight;
        private TabBar tabBar;
        private int lastPage;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            getSupportActionBar().hide();
    
            viewPager = (LoopViewPager) findViewById(R.id.pager);
            viewPager.setBoundaryCaching(true);
            adapter = new TabAdapter(getSupportFragmentManager());
            viewPager.setAdapter(adapter);
            tabBar = (TabBar) findViewById(R.id.tabbar);
    
            initTabs();
        }
    
        private void initTabs() {
            DisplayMetrics displaymetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int screenWidth = displaymetrics.widthPixels;
            tabWidth = screenWidth/3;
            tabHeight = getResources().getDimensionPixelSize(R.dimen.bar_height);
    
            tabBar.post(new Runnable() {
                @Override
                public void run() {
                      tabBar.init(MainActivity.this, tabWidth, tabHeight, viewPager);
                }
            });
    
            viewPager.setOnPageChangeListener(this);
        }
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
        }
    
        @Override
        public void onPageSelected(int position) {
            if(lastPage > position) {
                //User Move to left
                tabBar.swipeLeft();
            }else if(lastPage < position) {
                //User Move to right
                tabBar.swipeRight();
            }
            lastPage=position;
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
    
        }
    }
    

    Full source here:

    Download it from github
  • Android. How to use ActivityRecognitionApi library from Google.

    Android. How to use ActivityRecognitionApi library from Google.

    Case:
    We need know current user activity.
    Using ActivityRecognitionApi we can get if user driving, walking, running, ride bicycle.

    Android get information from all the sensors and analyse it using ActivityRecognitionApi.

    Below simple sample how to implement it.

    Please follow the steps:

    1. Create android project in Android Studio.
    2. Add compile ‘com.google.android.gms:play-services-location:8.4.0’ dependency in build.gradle:

    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.3"
    
        defaultConfig {
            applicationId "com.hrupin.activityrecognitionwithgoogle"
            minSdkVersion 21
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.3.0'
        compile 'com.google.android.gms:play-services-location:8.4.0'
    }
    

    3. Modify AndroidManifest.xml and add
    – “com.google.android.gms.permission.ACTIVITY_RECOGNITION” uses-permission

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.hrupin.activityrecognitionwithgoogle">
    
        <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
    
            <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
            <service android:name=".ActivityRecognitionService"></service>
    
            <activity
                android:name=".MainActivity"
                android:screenOrientation="portrait">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

    4. Add ActivityRecognitionService which will handle the results.

    package com.hrupin.activityrecognitionwithgoogle;
    
    import com.google.android.gms.location.ActivityRecognitionResult;
    import com.google.android.gms.location.DetectedActivity;
    
    import android.app.IntentService;
    import android.content.Intent;
    import android.util.Log;
    
    public class ActivityRecognitionService extends IntentService	 {
    
        public static final String ACTION = "com.hrupin.activityrecognitionwithgoogle.ACTIVITY_RECOGNITION_DATA";
        private String TAG = this.getClass().getSimpleName();
    	public ActivityRecognitionService() {
    		super("My Activity Recognition Service");
    	}
    
    	@Override
    	protected void onHandleIntent(Intent intent) {
    		if(ActivityRecognitionResult.hasResult(intent)){
    			ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
    			Log.i(TAG, getType(result.getMostProbableActivity().getType()) +"\t" + result.getMostProbableActivity().getConfidence());
    			Intent i = new Intent(ACTION);
    			i.putExtra("Activity", getType(result.getMostProbableActivity().getType()) );
    			i.putExtra("Confidence", result.getMostProbableActivity().getConfidence());
    			sendBroadcast(i);
    		}
    	}
    	
    	private String getType(int type){
    	    if(type == DetectedActivity.IN_VEHICLE) {
                return "In Vehicle";
            }else if(type == DetectedActivity.ON_BICYCLE) {
                return "On Bicycle";
            }else if(type == DetectedActivity.ON_FOOT) {
                return "On Foot";
            }else if(type == DetectedActivity.RUNNING) {
                return "Running";
            }else if(type == DetectedActivity.STILL) {
                return "Still";
            }else if(type == DetectedActivity.TILTING) {
                return "Tilting";
            }else if(type == DetectedActivity.UNKNOWN) {
                return "Unknown";
            }else if(type == DetectedActivity.WALKING) {
                return "Walking";
            }else {
                return "...";
            }
    	}
    
    }
    

    6. Added Activity for visualisation.

    package com.hrupin.activityrecognitionwithgoogle;
    
    import android.support.v7.app.AppCompatActivity;
    import java.io.File;
    import java.io.FileWriter;
    
    import android.app.Activity;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.text.format.Time;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesUtil;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.ActivityRecognition;
    
    public class MainActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener,
            OnClickListener {
    
        private static final String version = "1";
        private PendingIntent pIntent;
        private BroadcastReceiver receiver;
        private TextView tvActivity;
        private GoogleApiClient client;
        private Button bSend;
        private Button bClear;
        private File tempFile;
        private FileWriter writer;
    
        private static String curAct;
        private static int curCon;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tvActivity = (TextView) findViewById(R.id.tvActivity);
            bSend = (Button) findViewById(R.id.buttonSend);
            bSend.setOnClickListener(this);
            bClear = (Button) findViewById(R.id.buttonClear);
            bClear.setOnClickListener(this);
    
            int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
            if (resp == ConnectionResult.SUCCESS) {
                client = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API).addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this).build();
                client.connect();
            } else {
                Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
            }
    
            receiver = new BroadcastReceiver() {
    
                @Override
                public void onReceive(Context context, Intent intent) {
                    String time = getTime();
                    String act = intent.getStringExtra("Activity");
                    int con = intent.getExtras().getInt("Confidence");
                    Toast.makeText(MainActivity.this, time + ", A: " + act + ", C: " + con, Toast.LENGTH_SHORT).show();
                    if(act != null){
                        if(curAct == null || (!curAct.equals(act) || curCon != con)){
                            curAct = act;
                            curCon = con;
                            String v = time + ": Activity :" + act + " " + "Confidence : "
                                    + con + "\n";
                            v += tvActivity.getText();
                            tvActivity.setText(v);
                        }
                    }
                }
            };
    
            IntentFilter filter = new IntentFilter();
            filter.addAction(ActivityRecognitionService.ACTION);
            registerReceiver(receiver, filter);
            Toast.makeText(this, "STARTED !!!", Toast.LENGTH_LONG).show();
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (client != null) {
                ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(client, pIntent);
                client.disconnect();
                clear();
                Toast.makeText(this, "STOPPED !!!", Toast.LENGTH_LONG).show();
            }
            unregisterReceiver(receiver);
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult arg0) {
            Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onConnected(Bundle arg0) {
            if (client != null) {
                Intent intent = new Intent(this, ActivityRecognitionService.class);
                pIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(client, 1000, pIntent);
            }
        }
    
        @Override
        public void onConnectionSuspended(int cause) {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.buttonSend) {
                String text = null;
                try {
                    text = tvActivity.getText().toString();
                } catch (Exception e) {
    
                }
                if (text != null) {
                    try {
                        tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                                "report" + version + ".txt");
    
                        writer = new FileWriter(tempFile);
                        writer.write(text);
                        writer.close();
                        Toast.makeText(this, "Temporarily saved contents in " + tempFile.getPath(), Toast.LENGTH_SHORT)
                                .show();
                    } catch (Exception e) {
    
                    }
    
                    tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                            "report" + version + ".txt");
    
                    Intent email = new Intent(Intent.ACTION_SEND);
                    email.putExtra(android.content.Intent.EXTRA_SUBJECT, "[com.hrupin.activityrecognitionwithgoogle] version " + version);
    
                    email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + tempFile.getAbsoluteFile()));
                    email.setType("message/rfc822");
                    startActivity(Intent.createChooser(email, "Send Report"));
                    clear();
                }
            } else if (v.getId() == R.id.buttonClear) {
                clear();
            }
    
        }
    
        private void clear() {
            try {
                tvActivity.setText(getTime() + ":: cleared");
            } catch (Exception e) {
    
            }
            curAct = null;
            curCon = 0;
        }
    
        private String getTime() {
            Time t = new Time();
            t.setToNow();
            return t.format2445();
        }
    
    }
    

    Full source code here:

    Download it from github