Friday, March 31, 2017

Send push Notification using android with php part 2

Please get Server key from firebase console like this



In this section is relative to the PHP,

make "fcm.php" file and past following code

$url= "https://fcm.googleapis.com/fcm/send";
               
$key= "Service KEY FROM ABOVE SCREEN";

                if(($url != null && $url!="") && ($key != null && $key!="")){
                    $post_data = array(
                        'to' => $ToGCMToken, // This is token which sync from android and saved in mysql, each user have own gcmtoken
                        'content_available' => TRUE,
                        'priority' => 'high',
                        'data' => array(
                            'type' =>  "SIMPLE",
                            'body' =>  "Hello This is announcement",
                            'title' => "New announcement",
                            'badge' => "1",
                            'date' => 'Now()',
                            'sound' => "default",
                            'objectJSON' => "Hello, This is FCM Notification"
                        )
                    );
                    $headers = array(
                        'Authorization: key=' . $key,
                        'Content-Type: application/json'
                    );


                    $data_json = json_encode($post_data);

                    $ch = curl_init();
                    curl_setopt( $ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

                    //execute post
                    $result = curl_exec($ch);

                    //close connection
                    curl_close($ch);


                    echo "FCM sent succesfully";


Thursday, March 30, 2017

Send push Notification using android with php part 1

In this example, I will teach you, how to send notification from android to android with the help of PHP.

First of all, create account in Google firebase link here and follow instruction.

and get following file and past it in android app folder

google-services.json


Now, add following library in app.gradle file

dependencies {
compile 'com.google.firebase:firebase-messaging:9.6.1'
}
apply plugin: 'com.google.gms.google-services'

Like this 


Class Name : MyFirebaseInstanceIDService.java
import android.content.SharedPreferences;
import com.esteth.app.util.App;
import com.esteth.app.util.Prefs;
import com.esteth.app.util.UserModel;
import com.esteth.app.web.HttpCaller;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
       String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG,"REFRESHED TOKEN: " + refreshedToken);
      // Sync this fcm token in you mysql database user table
    }
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }
}
put this class in your code
Class Name : MyFirebaseMessagingService.java
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
importcom.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.JsonArray;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
   
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG,"From: " + remoteMessage.getFrom());
        // Check if message contains a data payload.
        if(remoteMessage.getData().size() > 0) { 
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }
        Map<String,String> data =remoteMessage.getData();
        String type=data.get("type");            
        showNotification(title);
    }
    private void showNotification(String title) {
        Intent intent = new Intent(this, YourActivity.class);    
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
       PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Uri defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_notification_icon).setContentTitle(title)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)       
.setAutoCancel(true)
        .setSound(defaultSoundUri);
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, notificationBuilder.build());
    }
}
Put following obove two class in your code and also declare in manifest file like following
When Notification come from other mobile, you will get notification value in MyFirebaseMessagingService. onMessageReceived()
In Part 2, you can see how ho send and receive Notification through PHP.

Tuesday, March 28, 2017

Custom Smart Tab Indicator Thickness in android








In this example, you can create custom tab with animation in android

Please put following two libraries in build.gradle in app folder


dependencies {
compile fileTree(
include: ['*.jar'], dir: 'libs')
testCompile
'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0' compile 'com.ogaclejapan.smarttablayout:library:1.6.1@aar' compile 'com.ogaclejapan.smarttablayout:utils-v4:1.6.1@aar'
}

and make class name as SmartTab Activity Class

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

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


public class SmartTab  extends ActionBarActivity {

    Toolbar toolbar;
    ViewPager viewPager;
    SmartTabLayout tabLayout;


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


        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportActionBar().getThemedContext();
        toolbar.setTitleTextColor(0xFFFFFFFF);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (SmartTabLayout) findViewById(R.id.viewpagertab);
        setupViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "One");
        adapter.addFrag(new TwoFragment(), "Two");
        adapter.addFrag(new ThreeFragment(), "Three");
        adapter.addFrag(new FrourFragment(), "Four");
        viewPager.setAdapter(adapter);
        tabLayout.setViewPager(viewPager);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}

smartTab layout

<android.support.design.widget.CoordinatorLayout 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">


    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent"
            android:background="@android:color/holo_blue_dark"
            android:theme="@style/AppTheme.PopupOverlay" />

        <!--  <android.support.design.widget.TabLayout
              android:id="@+id/tabs"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:tabMode="scrollable"
              android:layout_gravity="center_horizontal"
              />-->

        <com.ogaclejapan.smarttablayout.SmartTabLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/viewpagertab"
            android:background="@android:color/holo_blue_dark"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:clipToPadding="false"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            app:stl_defaultTabTextColor="@android:color/white"
            app:stl_defaultTabTextHorizontalPadding="18dp"
            app:stl_dividerColor="@android:color/transparent"
            app:stl_dividerThickness="0dp"
            app:stl_indicatorColor="@android:color/holo_blue_light"
            app:stl_indicatorCornerRadius="18dp"
            app:stl_indicatorGravity="center"
            app:stl_indicatorInterpolation="smart"
            app:stl_indicatorThickness="36dp"
            app:stl_underlineColor="@android:color/transparent"
            app:stl_underlineThickness="0dp"
            />


    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

</android.support.design.widget.CoordinatorLayout>

How to make horizontal scroll bar inside EditText android

If you want to put more text in Edittext and want to show horizontal scroll bar in edittext, put following small code.

without horizontal scroll bar in editText


<EditText
            android:id="@+id/edtLocationDetails"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:ems="10"
            android:textColor="@color/black"
            android:inputType="textCapSentences"
            android:textSize="10sp"
            android:paddingRight="5dp" />

with horizontal scroll bar in editText

<EditText
            android:id="@+id/edtLocationDetails"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:ems="10"
            android:textColor="@color/black"
            android:inputType="textCapSentences"
            android:textSize="10sp"
   android:scrollHorizontally="true"
            android:scrollbarAlwaysDrawHorizontalTrack="true"
            android:scrollbarFadeDuration="2000"
            android:scrollbarSize="80dp"
            android:scrollbarStyle="insideInset"
            android:scrollbars="horizontal"
            android:paddingRight="5dp" />