Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday 11 July 2016

CustomLogin Button Facebook login in android

Hello friends if you want login with Facebook with your own login custom button then use this sample.

First you create new project and follow step by step ....

Step 1> 
Add sdk in grale dependency

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.samset.user.customfblogin"
        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.facebook.android:facebook-android-sdk:4.6.0'
}


Add permission and configure need to fb login resources in android mainisfeast

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samset.user.customfblogin">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <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.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <!--  if you want share your content then enable this commented code
<provider android:authorities="com.facebook.app.FacebookContentProvider788910871208730"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="true"/>
-->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 2> Create fb_app_id go to this link.https://developers.facebook.com/apps/788910871208730/dashboard/ and create id.

now you write your android code

MainActvity.java

package com.samset.user.customfblogin;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.ProfilePictureView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    ImageView imgFacebookLogin, logout;
    public static CallbackManager callbackManager;

    private Intent intent;
    private ImageView imageView;
    private ProfilePictureView profile;
    private TextView tvName, tvEmail;
    private LinearLayout linearLayout;
    private RelativeLayout relativeLayout;


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

        imgFacebookLogin = (ImageView) findViewById(R.id.imgFacebookLogin);
        logout = (ImageView) findViewById(R.id.imgFacebooklogout);
        tvEmail = (TextView) findViewById(R.id.useremail);
        tvName = (TextView) findViewById(R.id.username);
        profile = (ProfilePictureView) findViewById(R.id.picture);
        linearLayout = (LinearLayout) findViewById(R.id.profilelayout);
        relativeLayout = (RelativeLayout) findViewById(R.id.logoutlayout);
        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
        imgFacebookLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fblogin();
            }
        });
    }

    public void getHashKey() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo("com.samset.user.customfblogin", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("HASH KEY:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
    }

    private void fblogin() {
        callbackManager = CallbackManager.Factory.create();
        final List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "user_friends", "public_profile");
        //List<String> permissionNeed = Arrays.asList("publish_actions");
        LoginManager.getInstance().logInWithReadPermissions(this, permissionNeeds);
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResults) {

                        GraphRequest request = GraphRequest.newMeRequest(loginResults.getAccessToken(),
                                new GraphRequest.GraphJSONObjectCallback() {
                                    @Override
                                    public void onCompleted(JSONObject object, GraphResponse response) {
                                        try {
                                            linearLayout.setVisibility(View.VISIBLE);
                                            relativeLayout.setVisibility(View.VISIBLE);
                                            imgFacebookLogin.setVisibility(View.GONE);


                                            String email = object.getString("email");
                                            String name = object.getString("name");
                                            String id = object.getString("id");
                                            URL fbUserImageUrl = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=150");

                                            tvName.setText(name);
                                            tvEmail.setText(email);
                                            profile.setProfileId(object.getString("id"));
                                           /* try {
                                                Bitmap bmp = BitmapFactory.decodeStream((InputStream) new URL(fbUserImageUrl.toString()).getContent());
                                                imageView.setImageBitmap(bmp);
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
*/
                                            Log.e("Fb", "Fb details" + name + " email " + email + " image" + fbUserImageUrl.toString());
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "id,name,email,gender, birthday");
                        request.setParameters(parameters);
                        request.executeAsync();

                    }

                    @Override
                    public void onCancel() {
                        Log.e("FB", "facebook login canceled");
                        try {
                            LoginManager.getInstance().logOut();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(FacebookException e) {
                        Log.e("FB", "facebook login failed error");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void logout() {
        LoginManager.getInstance().logOut();
linearLayout.setVisibility(View.GONE);
relativeLayout.setVisibility(View.GONE);
imgFacebookLogin.setVisibility(View.VISIBLE);

    }
}


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.user.customfblogin.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="@color/colorAccent"
        android:text="Facebook Login" />
    <LinearLayout
        android:id="@+id/profilelayout"
        android:visibility="gone"
        android:layout_below="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="35dp"
        >

        <com.facebook.login.widget.ProfilePictureView
            android:id="@+id/picture"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:layout_width="200sp"
            android:layout_height="200sp"/>
        <TextView
            android:layout_marginTop="10dp"
            android:id="@+id/username"
            android:text="Name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_marginTop="10dp"
            android:id="@+id/useremail"
            android:text="Email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />



    </LinearLayout>


    <ImageView
        android:layout_centerInParent="true"
        android:id="@+id/imgFacebookLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/facebook_blue_circle" />

<RelativeLayout
    android:id="@+id/logoutlayout"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:visibility="gone"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_centerInParent="true"
        android:id="@+id/imgFacebooklogout"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/sighout" />
    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/logout"

        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Logout"
        android:textColor="#fff"
        android:textSize="20dp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

</RelativeLayout>

styring.xml

<resources>
    <string name="app_name">CustomFbLogin</string>
    <string name="facebook_app_id">788910871208730</string>
</resources>


finally done and enjoy

Thank you
Full Source code CustomFbLogin
Live Sample


















Two date compare in java




private void sorting()
{
    List<Date> dateList = new ArrayList<Date>();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
    try {
        dateList.add(sdf.parse("01/12/2013 04:10:06 AM"));
        dateList.add(sdf.parse("02/11/2013 09:10:10 PM"));
        dateList.add(sdf.parse("03/12/2013 03:10:03 AM"));
        dateList.add(sdf.parse("04/10/2013 04:10:02 PM"));
        dateList.add(sdf.parse("05/05/2013 02:10:09 AM"));
        dateList.add(sdf.parse("06/12/2003 01:10:02 PM"));

        dateList.add(sdf.parse("07/03/2013 04:10:02 PM"));
        dateList.add(sdf.parse("05/01/2013 02:10:09 AM"));
        dateList.add(sdf.parse("07/07/2003 01:10:02 PM"));
        dateList.add(new Date());

        Collections.sort(dateList);
        Comparator<Date> cmp = new Comparator<Date>() {

            @Override
            public int compare(Date o1, Date o2) {
                if(o1.getTime() > o2.getTime()) return 1;
                else if(o1.getTime() < o2.getTime()) return -1;
                else return 0;
            }
        };

        List<Date>  out_of_date_list = new ArrayList<Date>();
        for(Date date : dateList){
            if(cmp.compare(date,new Date())<0){
                out_of_date_list.add(date);
            }
        }

        Log.e("Main"," >>> print all out of date  ");
        Collections.sort(out_of_date_list, Collections.reverseOrder());
        out_of_date_list.remove(0);
        for(Date date : out_of_date_list){

            Log.e("Main"," >>> date = "+sdf.format(date));
        }
    } catch (ParseException e) {// TODO Auto-generated catch block
        e.printStackTrace();
    }
}


Thank you

Wednesday 6 July 2016

Share image from drawable folder in android




1> Method

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.facebook_sharing_bg);
Intent share1 = new Intent(Intent.ACTION_SEND);
share1.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
        b, "Title", null);
Uri imageUri1 =  Uri.parse(path);
share1.putExtra(Intent.EXTRA_STREAM, imageUri1);
startActivity(Intent.createChooser(share1, "Share Image using"));



2> Method

Uri imageuri2=Uri.parse("android.resource://"+getPackageName()+"/"+R.drawable.ic_launcher);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, imageuri2);
startActivity(Intent.createChooser(share, "Share Image using"));

















Saturday 2 July 2016

MultiSelection recyclerview in android

Hello friends,
If you want select multiple items in recyclerview then use this sample code

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</android.support.v7.widget.Toolbar>

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:scrollbars="vertical" />

</LinearLayout>


MainActvity.java

package com.samset.user.multichoicerecyclerviewsample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements MultiSelectAdapter.ViewHolder.ClickListener{
    private Toolbar toolbar;

    private RecyclerView mRecyclerView;
    private MultiSelectAdapter mAdapter;

    private ArrayList<String> mArrayList  = new ArrayList<String>();

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


        for (int i = 1; i <= 100; i++) {

            mArrayList.add ("Box " + i);
        }

        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("MultiSelectRecylcerView");

        }

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
        mAdapter = new MultiSelectAdapter(MainActivity.this,mArrayList,this);
        mRecyclerView.setAdapter (mAdapter);


    }

    @Override
    public void onItemClicked (int position) {

        toggleSelection(position);
    }

    @Override
    public boolean onItemLongClicked (int position) {
        toggleSelection(position);

        return true;
    }

    private void toggleSelection(int position) {
        mAdapter.toggleSelection (position);

    }
}


MultiselectAdapter.java


package com.samset.user.multichoicerecyclerviewsample;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

public class MultiSelectAdapter extends SelectableAdapter<MultiSelectAdapter.ViewHolder> {

    private ArrayList<String> mArrayList;
    private Context mContext;
    private ViewHolder.ClickListener clickListener;



    public MultiSelectAdapter(Context context, ArrayList<String> arrayList, ViewHolder.ClickListener clickListener) {
        this.mArrayList = arrayList;
        this.mContext = context;
        this.clickListener = clickListener;

    }

    // Create new views
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,
                                                             int viewType) {

        View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.row, null);

        ViewHolder viewHolder = new ViewHolder(itemLayoutView,clickListener);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {

        viewHolder.tvName.setText(mArrayList.get (position));

        viewHolder.selectedOverlay.setVisibility(isSelected(position) ? View.VISIBLE : View.INVISIBLE);

    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder  implements View.OnClickListener,View.OnLongClickListener  {

        public TextView tvName;
        private ClickListener listener;
        private final View selectedOverlay;


        public ViewHolder(View itemLayoutView,ClickListener listener) {
            super(itemLayoutView);

            this.listener = listener;

            tvName = (TextView) itemLayoutView.findViewById(R.id.tvName);
            selectedOverlay = (View) itemView.findViewById(R.id.selected_overlay);

            itemLayoutView.setOnClickListener(this);

            itemLayoutView.setOnLongClickListener (this);
        }

        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onItemClicked(getAdapterPosition ());
            }
        }
        @Override
        public boolean onLongClick (View view) {
            if (listener != null) {
                return listener.onItemLongClicked(getAdapterPosition ());
            }
            return false;
        }

        public interface ClickListener {
            public void onItemClicked(int position);

            public boolean onItemLongClicked(int position);
        }
        }
    }



SelectableAdapter.java

package com.samset.user.multichoicerecyclerviewsample;

import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;

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

public abstract class SelectableAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
@SuppressWarnings("unused")
private static final String TAG = SelectableAdapter.class.getSimpleName();

private SparseBooleanArray selectedItems;

public SelectableAdapter () {
selectedItems = new SparseBooleanArray ();
}

/**
* Indicates if the item at position position is selected
* @param position Position of the item to check
* @return true if the item is selected, false otherwise
*/
public boolean isSelected(int position) {
return getSelectedItems().contains(position);
}

/**
* Toggle the selection status of the item at a given position
* @param position Position of the item to toggle the selection status for
*/
public void toggleSelection(int position) {
if (selectedItems.get(position, false)) {
selectedItems.delete(position);
} else {
selectedItems.put(position, true);
}
notifyItemChanged(position);
}

/**
* Clear the selection status for all items
*/
public void clearSelection() {
List<Integer> selection = getSelectedItems();
selectedItems.clear();
for (Integer i : selection) {
notifyItemChanged(i);
}
}

/**
* Count the selected items
* @return Selected items count
*/
public int getSelectedItemCount() {
return selectedItems.size();
}

/**
* Indicates the list of selected items
* @return List of selected items ids
*/
public List<Integer> getSelectedItems() {
List<Integer> items = new ArrayList<> (selectedItems.size());
for (int i = 0; i < selectedItems.size(); ++i) {
items.add(selectedItems.keyAt(i));
}
return items;
}
}


row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:background="@color/colorAccent">

        <TextView
            android:id="@+id/tvName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="name"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

    </RelativeLayout>

    <View
        android:id="@+id/selected_overlay"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:background="#80000000"
        android:visibility="invisible">


    </View>
</RelativeLayout>


AndroidManifest

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

    <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>
    </application>


</manifest>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.samset.user.multichoicerecyclerviewsample"
        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.3.0'
    compile 'com.android.support:recyclerview-v7:23.3.0'
}




Thank you
LiveSample










Background music without using service

Hello friends,
If you want play background music without using service then use this sample code

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 );
                }

        });
     

}
}

SecondActvity.java

public class SecondActvity extends AppCompatActivity {
 

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

}



Mymusic.java

package com.tech.samset;

import android.content.Context;
import android.media.MediaPlayer;
import android.widget.Toast;

import com.example.user.audiomusic.R;


/**
 * Created by user on 02-Jul-16.
 */
public class MyMusic implements MediaPlayer.OnErrorListener {

    MediaPlayer mPlayer;
    private int length = 0;
    public MyMusic(Context c)
    {
        mPlayer = MediaPlayer.create(c, R.raw.background_sound);
        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;
            }
        });
    }

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

            }
        }

    }

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

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


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

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

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


BaseActvity.java

package com.example.user.audiomusic.parentActivity;

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

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);
        setContentView(R.layout.activity_main);

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        listenerBinding.unbind();
        Log.i("Base", "  onDestroy");
    }

    @Override
    public void onBecameForeground() {
       
        MyApplication.getInstance().onMusicResume();
        Toast.makeText(BaseActivity.this,"App is foreground",Toast.LENGTH_SHORT).show();
        Log.i(Foreground.TAG, getClass().getName() + " became foreground");
    }

    @Override
    public void onBecameBackground() {
        MyApplication.getInstance().onMusicPause();
   
        Toast.makeText(BaseActivity.this,"App went background",Toast.LENGTH_SHORT).show();
        Log.i(Foreground.TAG, getClass().getName() + " went background");
    }

}



MyApplication.java

public class MyApplication extends Application {
 
    public  MyMusic myMusic;
 

@Override
    public void onCreate() {
        super.onCreate();
myMusic=new MyMusic(this);
 
    }
 public  void onMusicPause()
    {
        myMusic.pauseMusic();
    }
    public  void onMusicResume()
    {
        myMusic.resumeMusic();
    }
    public  void onMusicDestroy()
    {
        myMusic.onDestroy();
    }

    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" />
     
    </application>



</manifest>

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.3.0'
    compile 'com.sjl:Foredroid:1.0.0'
}


Thank you