Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday 30 June 2016

Detecting when your Android app goes background / foreground

Hello friends
If you want to  know your application background or foreground then you follow below instructions.
i am use third party lib.

First you add android studio gradle dependency lib...

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.user.audiomusic"
        minSdkVersion 15
        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.4.0'
    compile 'com.sjl:Foredroid:1.0.0'
}

BaseActivity.java

package com.example.user.audiomusic.parentActivity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.user.audiomusic.MyApplication;
import com.example.user.audiomusic.R;
import com.sjl.foreground.Foreground;

public abstract class BaseActivity extends AppCompatActivity implements Foreground.Listener {

    private Foreground.Binding listenerBinding;

    //protected abstract void startAnotherActivity();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        listenerBinding = Foreground.get(getApplication()).addListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        listenerBinding.unbind();
    }

    @Override
    public void onBecameForeground() {
        MyApplication.getInstance().startService();
        Log.i(Foreground.TAG, getClass().getName() + " became foreground");
    }

    @Override
    public void onBecameBackground() {
        MyApplication.getInstance().musicSrv.pauseMusic();
        Log.i(Foreground.TAG, getClass().getName() + " went background");
    }

}


actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.user.audiomusic.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:layout_margin="10dp"
        android:textSize="20dp"
        android:layout_gravity="center_horizontal"
        android:text="First"
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:layout_margin="10dp"
        android:textSize="20dp"
        android:layout_gravity="center_horizontal"
        android:text="Second"
        android:id="@+id/third"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:layout_margin="10dp"
        android:textSize="20dp"
        android:layout_gravity="center_horizontal"
        android:text="Third"
        android:id="@+id/fourth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActvity.java

package com.example.user.audiomusic;

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

import com.example.user.audiomusic.parentActivity.BaseActivity;


public class MainActivity extends BaseActivity {

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



        findViewById(R.id.second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);

            }
        });

        findViewById(R.id.third).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ThirdActivity.class);
                startActivity(intent);

            }
        });

        findViewById(R.id.fourth).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,FourthActivity.class);
                startActivity(intent);

            }
        });
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("MainActvity","onDestroy");
    }
}



second_actvity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.user.audiomusic.SecondActivity">
<TextView
    android:textSize="20dp"
    android:text="I am 2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />


    <Button
        android:layout_gravity="center_horizontal"
        android:textSize="25dp"
        android:id="@+id/sec_next"
        android:text="Next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


SecondActvity.java

package com.example.user.audiomusic;

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

import com.example.user.audiomusic.parentActivity.BaseActivity;


public class SecondActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        findViewById(R.id.sec_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SecondActivity.this,FourthActivity.class));
            }
        });    }
 
}


third_actvity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.user.audiomusic.ThirdActivity">

</RelativeLayout>

ThirdActvity.java
 package com.example.user.audiomusic;

import android.os.Bundle;
import android.util.Log;

import com.example.user.audiomusic.parentActivity.BaseActivity;


public class ThirdActivity extends BaseActivity {

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

FourthActivity.java

package com.example.user.audiomusic;

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

import com.example.user.audiomusic.parentActivity.BaseActivity;

public class FourthActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fourth);
        findViewById(R.id.fourth_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(FourthActivity.this,ThirdActivity.class));
            }
        });
    }
}


actvity_fourth.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.user.audiomusic.FourthActivity">
    <TextView
        android:textSize="20dp"
        android:text="I am 4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <Button
        android:layout_gravity="center_horizontal"
        android:textSize="25dp"
        android:id="@+id/fourth_next"
        android:text="Next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


Thank you

FullSourceCode
Live Sample







Know your app foreground or background in android

Hello friends
Today we are learn about how to detect our app background or foreground so lets start and enjoying this code.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:textSize="25dp"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/first" />

    <Button
        android:layout_centerInParent="true"
        android:text="Next"
        android:elevation="4dp"
        android:id="@+id/FirstBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="23dp"
        tools:ignore="NotSibling" />

</RelativeLayout>

MainActvity.java


package com.example.user.actvitylifecycle;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends BaseActivity {

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

((Button) findViewById(R.id.FirstBtn))
.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),
SecondActvity.class));
}
});
}

}

second_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SecondActvity" >

    <TextView
        android:textSize="25dp"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/second" />

    <Button
        android:layout_centerInParent="true"
        android:text="Next.."
        android:elevation="4dp"
        android:id="@+id/SecondBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="23dp"
        tools:ignore="NotSibling" />

</RelativeLayout>


third_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ThirdActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/action_settings" />

</RelativeLayout>

SecondActivity.java

package com.example.user.actvitylifecycle;

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

public class SecondActvity extends BaseActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
((Button) findViewById(R.id.SecondBtn))
.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),
ThirdActivity.class));
}
});
}

}


ThirdActivity.java

package com.example.user.actvitylifecycle;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;

public class ThirdActivity extends BaseActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setTitle(getString(R.string.action_settings));
return true;
}
}

BaseActvity.java

package com.example.user.actvitylifecycle;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

public abstract class BaseActivity extends AppCompatActivity {

    protected static final String TAG = BaseActivity.class.getName();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    public static boolean isAppWentToBg = false;
    public static boolean isWindowFocused = false;
    public static boolean isBackPressed = false;

    @Override
    protected void onStart() {
        Log.d(TAG, "onStart isAppWentToBg " + isAppWentToBg);
        applicationWillEnterForeground();
        super.onStart();
    }

    private void applicationWillEnterForeground() {
        if (isAppWentToBg) {
            isAppWentToBg = false;
            Toast.makeText(getApplicationContext(), "App is in foreground", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop ");
        applicationdidenterbackground();
    }

    public void applicationdidenterbackground() {
        if (!isWindowFocused) {
            isAppWentToBg = true;
            Toast.makeText(getApplicationContext(),"App is Going to Background", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        if (this instanceof MainActivity) {
        } else {
            isBackPressed = true;
        }
        Log.d(TAG,"onBackPressed " + isBackPressed + ""+ this.getLocalClassName());
        super.onBackPressed();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        isWindowFocused = hasFocus;
        if (isBackPressed && !hasFocus) {
            isBackPressed = false;
            isWindowFocused = true;
        }
        super.onWindowFocusChanged(hasFocus);
    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.actvitylifecycle">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActvity"></activity>
        <activity android:name=".ThirdActivity"></activity>
    </application>

</manifest>

FullSourceCode.

LiveSample















Wednesday 29 June 2016

Background Music in android game

Hello guys
Today we are learn about how to play audio music in background in your whole android game app  so lets start ..

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tech.samset.MainActivity">

   <Button
        android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next" />


</LinearLayout>


MainActvity.java

package com.tech.samset;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;

public class MainActivity extends AppCompatActivity {
   
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                   Intent intent = new Intent(MainActivity.this, SecondActvity.class);
                       startActvity(intent );
                }

        });
       
}

@Override
    protected void onResume() {
        super.onResume();
       MyApplication.getInstance().startService();
       
}

@Override
    protected void onPause() {
        super.onPause();
       MyApplication.getInstance().musicSrv.pauseMusic();
//if you want when you go another activity then your music is pause then you call


       
}
}

SecondActvity.java

public class SecondActvity extends AppCompatActivity {
   
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
       
}

@Override
    protected void onResume() {
        super.onResume();
       MyApplication.getInstance().startService();
     
}
}
}



Mymusic.java

package com.tech.samset;

import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener {

private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;

public MusicService() {
}

public class ServiceBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}

@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}

@Override
public void onCreate() {
super.onCreate();

mPlayer = MediaPlayer.create(this, R.raw.jingle);
mPlayer.setOnErrorListener(this);

if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}


mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

public boolean onError(MediaPlayer mp, int what, int extra) {

onError(mPlayer, what, extra);
return true;
}
});
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}

public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();

}
}

public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}

public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}

@Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}

public boolean onError(MediaPlayer mp, int what, int extra) {

Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}

MyApplication.java

public class MyApplication extends Application {
   
    public  Mymusic musicSrv;
    private Intent playIntent;
    private boolean musicBound = false;

public ServiceConnection musicConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            Mymusic .ServiceBinder binder = (Mymusic .ServiceBinder) service;
            musicSrv = binder.getService();
            musicBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicBound = false;
        }
    };

public void startService()
    {
        if (playIntent == null) {
            playIntent = new Intent(getApplicationContext(), Mymusic .class);
            bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
            startService(playIntent);
            Log.e("MAin", " intent is null ");
        } else {
            musicSrv.resumeMusic();
            Log.e("MAin", " intent is not null ");
        }
    }
    public void stopService()
    {
        if (playIntent!=null)
        {
            playIntent = new Intent(getApplicationContext(), Mymusic .class);
            unbindService(musicConnection);
            stopService(playIntent);
            musicSrv.stopMusic();
        }
    }

@Override
    public void onCreate() {
        super.onCreate();
   
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

}
AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tech.samset">

    <application
        android:name=.MyApplication
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       <activity android:name=".SecondActvity" />
        <service android:name=".MusicService" android:enabled="true" />
    </application>

</manifest>

FullSourcecode 

Thank you

Play audio music with service in android

Hello guys
Today we are learn about audio music with service so lets start ..

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tech.samset.MainActivity">

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop" />

    <Button
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause" />
    <Button
        android:id="@+id/resume"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Resume" />

</LinearLayout>


MainActvity.java

package com.tech.samset;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;

public class MainActivity extends AppCompatActivity {
    private MusicService musicSrv;
    private Intent playIntent;
    //binding
    private boolean musicBound=false;
    //activity and playback pause flags
    private boolean paused=false, playbackPaused=false;


    //connect to the service
    private ServiceConnection musicConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            MusicService.ServiceBinder binder = (MusicService.ServiceBinder)service;
            musicSrv = binder.getService();
            musicBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(playIntent==null){
                    playIntent = new Intent(MainActivity.this, MusicService.class);
                    bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
                    startService(playIntent);
                    Log.e("MAin", " intent is null ");
                }else {
                    musicSrv.resumeMusic();
                    Log.e("MAin"," intent is not null ");
                }
            }
        });
        findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    playIntent = new Intent(MainActivity.this, MusicService.class);
                    unbindService(musicConnection);
                    stopService(playIntent);
                    musicSrv.stopMusic();
                }

        });
        findViewById(R.id.pause).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicSrv.pauseMusic();
            }
        });

        findViewById(R.id.resume).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }
}

Mymusic.java

package com.tech.samset;

import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener {

private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;

public MusicService() {
}

public class ServiceBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}

@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}

@Override
public void onCreate() {
super.onCreate();

mPlayer = MediaPlayer.create(this, R.raw.jingle);
mPlayer.setOnErrorListener(this);

if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}


mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

public boolean onError(MediaPlayer mp, int what, int extra) {

onError(mPlayer, what, extra);
return true;
}
});
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}

public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();

}
}

public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}

public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}

@Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}

public boolean onError(MediaPlayer mp, int what, int extra) {

Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}


AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tech.samset">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MusicService" android:enabled="true" />
    </application>

</manifest>

FullSourcecode 

Thank you

Thursday 9 June 2016

Generics in Java

Hello friends,

What is Generics:-

In Generics we can store any type of objects in collection but non-generic we  store only specific type of object.

In generic not need to type casting.But non-generic compulsory to type casting like..

List mylist=new ArrayList();
mylist.add("Samset"); 

String str=(String)mylist.get(0);     //This is typecasting


List<String> mylist=new ArrayList(String);
mylist.add("Samset"); 

String str=mylist.get(0);     //No need typecasting

Example.java

public class Test
{
public static void main(String ar[])
{
List<String> mylist=new ArrayList(String);
mylist.add("Hello"); 
mylist.add("Samset"); 


for(int i=0;i<mylist.size();i++)
{
System.out.println("String data :- "+mylist.get(i));
}
}
}

OUTPUT :- 
String data :-

Hello
Samset


Second Example 


public class Test2
{
   // generic method printArray                         
   public static < E > void printArray( E[] input )
   {
      // Display array elements              
         for ( E element : input ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'W', 'E', 'L', 'C', 'O','M','E' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}


OUTPUT :-


Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 

Array characterArray contains:
W E L C O M E










Iterate a List in Java





public class IterateExample {

           public  static void main(String[] ar) {

            // create list
           
List<String> strList = new ArrayList<String>();

            // add value in list
           
strList.add("India");
            strList.add("Nepal");
            strList.add("China");
            strList.add("Bhotan");
            strList.add("Pakistan");
            strList.add("ShriLanka");

            // iterate via "for loop"
           
System.out.println("Simple for loop iterate ");

            for (int i = 0; i < strList.size(); i++) {
                System.out.println(strList.get(i));
            }

            // iterate via "New way to loop"
           
System.out.println(" Advance for loop iterate");
            for (String temp : strList) {
                System.out.println(temp);
            }

            // iterate via "iterator loop"
           
System.out.println("Iterator");
            Iterator<String> itr = strList.iterator();
            while (itr.hasNext()) {
                System.out.println(itr.next());
            }

            // iterate via "while loop"
           
System.out.println(" While loop iterate ");
            int i = 0;
            while (i < strList.size()) {
                System.out.println(strList.get(i));
                i++;
            }

      }
}

Output :-


Simple for loop iterate 

India
Nepal
China
Bhutan
Pakistan
ShriLanka

Advance for loop iterate

India
Nepal
China
Bhutan
Pakistan
ShriLanka

Iterator
India
Nepal
China
Bhutan
Pakistan
ShriLanka

While loop iterate

India
Nepal
China
Bhutan
Pakistan
ShriLanka


Thank you





ExcelToJson sample in android

Hello friends,

Firstly you add excel library


MainActvity.java


public class RowReadActvity extends AppCompatActivity {

    static int rowSize=25;


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

public void read() {
    InputStream stream = getResources().openRawResource(R.raw.test);
    List<HashMap<String,HashMap<String,List>>> stdList = new ArrayList();

 
    try {
        XSSFWorkbook workbook = new XSSFWorkbook(stream);
        int numberOfSheets = workbook.getNumberOfSheets();

        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Iterator rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                Row row = (Row) rowIterator.next();
                Iterator cellIterator = row.cellIterator();

                    for(int j=0; j<rowSize;j++)
                    {

                    if (row.getRowNum()==j)
                    {
                        HashMap<String,HashMap<String,List>> map=new HashMap<>();
                        HashMap<String,List> map2=new HashMap<>();
                        List list = new ArrayList();
                        while(cellIterator.hasNext()){
                            Cell cell = (Cell) cellIterator.next();
                            list.add(cell.toString());
                     
                            map2.put("shirt",list);

                        }

                        map.put("cloth",map2);
                        stdList.add(map);
                    }
                }
            }

        }
        Gson gson = new Gson();
        String json = gson.toJson(stdList);
        Log.e("Row", "jason data: " +  json.toString());
        cretaeJson(json.toString());


    } catch (Exception ex) {
        ex.printStackTrace();
    }

}


public void cretaeJson(String object) throws IOException {
    String s=" hello sam";
    File resolveMeSDCard = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"hello_file.txt");
    resolveMeSDCard.createNewFile();
    FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
    fos.write(s.getBytes());
    fos.close();


    //write the JSON data to file
   
BufferedWriter bufferedWriter = null;
    try {

        File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"myFile.json");
        if(!file.exists()){
            file.createNewFile();
        }

        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(object);
        Log.e("Row"," ct=reated");


    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufferedWriter != null){
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}

// OTHER WAY YOU USE


public void onReadClick() {
    //printlnToUser("reading XLSX file from resources");
   
InputStream stream = context.getResources().openRawResource(R.raw.test);
    try {
        XSSFWorkbook workbook = new XSSFWorkbook(stream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        int rowsCount = sheet.getPhysicalNumberOfRows();
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        for (int r = 0; r < rowsCount; r++) {
            Row row = sheet.getRow(r);
            int cellsCount = row.getPhysicalNumberOfCells();
            for (int c = 0; c < cellsCount; c++) {
                String value = getCellAsString(row, c, formulaEvaluator);

                String cellInfo = "r:" + r + "; c:" + c + "; v:" + value;

                //Log.e("Test", " Value " + cellInfo);
           
}
        }
    } catch (Exception e) {
        /* proper exception handling to be here */
       
e.printStackTrace();
    }
}



protected String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
    String value = "";
    try {
        Cell cell = row.getCell(c);
        CellValue cellValue = formulaEvaluator.evaluate(cell);
        switch (cellValue.getCellType()) {
            case Cell.CELL_TYPE_BOOLEAN:
                value = "" + cellValue.getBooleanValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                double numericValue = cellValue.getNumberValue();
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    double date = cellValue.getNumberValue();
                    SimpleDateFormat formatter =
                            new SimpleDateFormat("dd/MM/yy");
                    value = formatter.format(HSSFDateUtil.getJavaDate(date));
                } else {
                    value = "" + numericValue;
                }
                break;
            case Cell.CELL_TYPE_STRING:
                value = "" + cellValue.getStringValue();
                break;
            default:
        }
    } catch (NullPointerException e) {
        /* proper error handling should be here */
       
e.printStackTrace();
    }
    return value;
}



build.gradle


apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

   
defaultConfig {
        applicationId "com.samset.xlsxreadwrite"
       
minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
       
multiDexEnabled true
   
}
    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.android.support:multidex:1.0.1'
   
compile 'com.google.code.gson:gson:2.2.+'
   
compile files('libs/poi-3.12-android-a.jar')
    compile files('libs/poi-ooxml-schemas-3.12-20150511-a.jar')
}



Wednesday 8 June 2016

PullToRefreshListView sample

Hello friends,

Today we are learn about how to refresh listview data.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swype"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.v4.widget.SwipeRefreshLayout>


MainActivity.java


package com.samset.pulltorefreshlist;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private SwipeRefreshLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String[] items = new String[]{
                "India", "U.S.A.", "Nepal", "Bhotan", "Pakistan", "China", "Bangladesh", "Myanmar", "Taivan", "Iron", "Afganistan", "British"
       
};

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layout = (SwipeRefreshLayout) findViewById(R.id.swype);
        layout.setOnRefreshListener(this);

        // Set the refresh swype color scheme
       
layout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);

        ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
    }

    @Override
    public void onRefresh() {
        // I create a handler to stop the refresh and show a message after 3s
       
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                layout.setRefreshing(false);
                Toast.makeText(MainActivity.this, "Update.. !", Toast.LENGTH_LONG).show();
            }

        }, 3000);


    }
}

Thank you

FullCodePullToRefreshListView


Live Sample








Fix white screen on app Start up


Hello guys
If you face problem when you launch your application and show 1 sec or 2 sec white screen then use this method and resolve your problem.


splash.xml


<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/colorPrimary"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/img_face"/>
    </item>
</layer-list>


theme.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme.CenterAnimation">
        <item name="android:windowBackground">@drawable/splash</item>
    </style>
</resources>


actvity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.samset.splash.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

MainActvity.java


package com.samset.splash;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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



splash_activity.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.samset.splash.Splash">

</RelativeLayout>

SplashActvity.java


package com.samset.splash;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Splash extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                startActivity(new Intent(Splash.this,MainActivity.class));
            }
        }).start();
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samset.splash">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Splash" android:theme="@style/AppTheme.CenterAnimation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>
    </application>

</manifest>

Thank you

FullSourceCodePreventWhiteScreen

Live Sample













MaterialDesign Splash screen with placeholder


Hello friends
If you want create beautiful splash screen with animation see this blog and enjoy.
Follow step by step instruction...

Step 1: Create a resource file in values folder by name theme.xml

theme.xml


<?xml version="1.0" encoding="utf-8"?><resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        
<item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@null</item>
    </style>
<style name="AppTheme.Placeholder">
    <item name="android:windowBackground">@drawable/toolbar_placeholder</item>
</style>


</resources>

Step 2: Create a drawable  file in drawable folder by name logo.xml and download any type of logo image.

toolbar_placeholder.xml


<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque"
    >
    <item>
        <shape>
            <solid android:color="@color/grey"/>
        </shape>
    </item>

    <item
        android:height="180dp"
        android:gravity="top">
        <shape android:shape="rectangle">
            <solid android:color="?colorPrimary"/>
        </shape>
    </item>

</layer-list>


Step 3: Go to style.xml and define the button style

style.xml


<resources>


    <style name="Button" parent="Theme.AppCompat">
        <item name="colorControlHighlight">@color/colorPrimary</item>
        <item name="colorButtonNormal">@color/teal</item>
    </style>
</resources>

color.xml


<?xml version="1.0" encoding="utf-8"?><resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="teal">#009687</color>

</resources>

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/grey"
        android:orientation="vertical"
        tools:context=".OnboardingWithPlaceholderActivity"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="156dp"
            android:background="?colorPrimary"
            android:elevation="4dp"
            app:theme="@style/ThemeOverlay.AppCompat.Light"
            >

            <TextView
                android:id="@+id/text_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:alpha="0"
                android:text="Cold starts are evil!"
                android:textAppearance="@style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"
                />
        </android.support.v7.widget.Toolbar>


        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:paddingTop="8dp"
            />

    </LinearLayout>

  

</FrameLayout>



MainActvity.java


package com.example.saulmm.splashes;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.saulmm.splashes.itemanimator.ItemAnimatorFactory;

import java.util.ArrayList;
import java.util.List;

public class OnboardingWithPlaceholderActivity extends AppCompatActivity {
    private int mContentViewHeight;
    private Toolbar mToolbar;
    private RecyclerAdapter mAdapter;
    private View mFab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Fake a long startup time
       
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onFakeCreate();
            }

        }, 500);
    }

    private void onFakeCreate() {
        setTheme(R.style.AppTheme);
        setContentView(R.layout.activity_onboarding_placeholder);

        TextView titleTextView = (TextView) findViewById(R.id.text_title);
        ViewCompat.animate(titleTextView).alpha(1).start();

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
        mFab = findViewById(R.id.fab);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(ItemAnimatorFactory.slidein());

        mAdapter = new RecyclerAdapter();
        recyclerView.setAdapter(mAdapter);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.getViewTreeObserver().addOnPreDrawListener(
            new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    mToolbar.getViewTreeObserver().removeOnPreDrawListener(this);
                    final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                    final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

                    mToolbar.measure(widthSpec, heightSpec);
                    mContentViewHeight = mToolbar.getHeight();
                    collapseToolbar();
                    return true;
                }
            });
    }


    private void collapseToolbar() {
        int toolBarHeight;
        TypedValue tv = new TypedValue();
        getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
        toolBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
        ValueAnimator valueHeightAnimator = ValueAnimator.ofInt(mContentViewHeight, toolBarHeight);
        valueHeightAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ViewGroup.LayoutParams lp = mToolbar.getLayoutParams();
                lp.height = (Integer) animation.getAnimatedValue();
                mToolbar.setLayoutParams(lp);
            }
        });

        valueHeightAnimator.start();
        valueHeightAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);

                // Fire item animator
               
mAdapter.addAll(ModelItem.getFakeItems());

                // Animate fab
               
ViewCompat.animate(mFab).setStartDelay(600)
                    .setDuration(400).scaleY(1).scaleX(1).start();

            }
        });
    }

    class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
        private ArrayList<ModelItem> mItems = new ArrayList<>();

        @Override
        public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_card, parent, false);
            return new RecyclerViewHolder(v);
        }

        public void addAll(List<ModelItem> items) {
            int pos = getItemCount();
            mItems.addAll(items);
            notifyItemRangeInserted(pos, mItems.size());
        }

        @Override
        public void onBindViewHolder(RecyclerViewHolder holder, int position) {
            holder.bind(position);
        }

        @Override
        public int getItemCount()    {
            return mItems.size();
        }


        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            private TextView mTitleTextView;
            private ImageView mImageView;

            public RecyclerViewHolder(View itemView) {
                super(itemView);
                mTitleTextView = (TextView) itemView.findViewById(R.id.text_title);
                mImageView = (ImageView) itemView.findViewById(R.id.img_sampleimage);
            }

            public void bind(int position) {
                mImageView.setImageBitmap(BitmapFactory.decodeResource(
                    getResources(), mItems.get(position).getImgId()));
                mTitleTextView.setText(mItems.get(position).getAuthor());
            }
        }

    }

}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samset.splashscreen">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"  
android:theme="@style/AppTheme.Placeholder">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thank you

FullSourceCodeSplashScreen


Live Sample