Sunday, August 21, 2016

Android Firebase Cloud Messaging

this titorial is written with the consideration that you are familiar  with GCM. if you are new to firebase please follow the official documentaion.


1 . go to the Firebase Console and create new project or you can import existing gcm project into firebase.

2. after project creating go to the project setting from top left cornet (click setting icon).
3. enter your package name , and download the google-services.json
4. copy google-services.json into your app directory .
5. add rules to your root-level build.gradle file, to include the google-services plugin:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

6. Then, in your module Gradle file (usually the app/build.gradle), add the
apply plugin line at the bottom of the file to enable the Gradle plugin:

apply plugin: 'com.android.application' android {   // ... } dependencies {   // ... com.google.firebase:firebase-messaging:9.4.0} // ADD THIS AT THE BOTTOM apply plugin: 'com.google.gms.google-services'
Note : please check libraries are available for the different Firebase features.
https://firebase.google.com/docs/android/setup

7. Retrieve the current registration token
 When you need to retrieve the current token, call FirebaseInstanceID.getToken().
 This method returns null if the token has not yet been generated.

public class FirebaseInstanceIDService 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);
    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the    
// Instance ID token to your app server.    
// send this token to your server so you can start 
// downstream messages to client.
   }
}
8.  Handle Message receiving 

create new service which extends FirebaseMessagingService . 
here i've created MyFirebaseMessagingService.java

example 

public class MyFirebaseMessagingServiceextends 
       FirebaseMessagingService  {

/** * Called when message is received.
* * @param remoteMessage Object representing the 
message received from Firebase Cloud Messaging. 
*/// [START receive_message]
@Overridepublic 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());
   }
    // Check if message contains a notification payload.  
   if (remoteMessage.getNotification() != null) {
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
   }
}


9.  AndroidManifest.xml

<service    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
<service    android:name=".FirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
10.  Your MainActivity

//get token
String token = FirebaseInstanceId.getInstance().getToken();

//start subsription to firebase
FirebaseMessaging.getInstance().subscribeToTopic("news");

//for unsubscribtion
FirebaseMessaging.getInstance().unsubscribeFromTopic("news");
11. SERVER CODE FOR SENDING MESSAGES

please refer following link

https://github.com/firzan/php/edit/master/Gcm.php

Thursday, October 2, 2014

Android upload file to PHP server with parameters using progress bar


new ProcessFileUploadTask(new File(Environment.getExternalStorageDirectory().toString()+"/yourfile_name/";


//asynch task to upload file with parameters
public class ProcessFileUploadTask extends AsyncTask<Void, Integer, Void>  implements DialogInterface.OnCancelListener{

  private ProgressDialog progressDialog;
  private File file;
  String res="";

   public ProcessFileUploadTask(File file) {
    this.file = file;
  }

   @Override
// can use UI thread here
protected void onPreExecute() {
super.onPreExecute();
try{
progressDialog = new ProgressDialog(PostDataActivity.this);
progressDialog.setMessage("Uploading... Please wait!");
progressDialog.setIndeterminate(false);
progressDialog.setMax(file_size);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
       progressDialog.setCanceledOnTouchOutside(false);
       progressDialog.show();
}
catch(Exception e){
Log.e("Exception:",e.toString());
}
}

protected void onPostExecute(Void v) {  
   
progressDialog.dismiss();
Toast toast=Toast.makeText(getApplicationContext(), "Uploaded Successfully.", Toast.LENGTH_LONG);

}

   @Override
  protected Void doInBackground(Void... v) {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection conn = null;
     
   
    try {
    //posting parameters with url
    String finalUrl = Uri.parse("www.example.com/demo.php")
               .buildUpon()
               .appendQueryParameter("name", "firzan")
               .build().toString();
      conn = (HttpURLConnection) new URL(finalUrl).openConnection();
      conn.setConnectTimeout(10*1000);
     
      conn.setRequestMethod("POST");
      String boundary = "---------------------------boundary";
      String tail = "\r\n--" + boundary + "--\r\n";
      conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      conn.setDoOutput(true);

      String metadataPart = "--" + boundary + "\r\n"
          + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
          + "" + "\r\n";

      String fileHeader1 = "--" + boundary + "\r\n"
          + "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
          + serverFileName + "\"\r\n"
          + "Content-Type: application/octet-stream\r\n"
          + "Content-Transfer-Encoding: binary\r\n";

       long fileLength = file.length() + tail.length();
      String fileHeader2 = "Content-length: " + fileLength + "\r\n";
      String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
      String stringData = metadataPart + fileHeader;

      long requestLength = stringData.length() + fileLength;
      conn.setRequestProperty("Content-length", "" + requestLength);
      conn.setFixedLengthStreamingMode((int) requestLength);
      conn.connect();

      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      out.writeBytes(stringData);
      out.flush();

      int progress = 0;
      int bytesRead = 0;
      byte buf[] = new byte[10*1024];
      BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
      while ((bytesRead = bufInput.read(buf)) != -1) {
     
      // write output
        out.write(buf, 0, bytesRead);
        out.flush();
        progress += bytesRead;
        // update progress bar
        publishProgress(progress);
      }
     
       // Write closing boundary and close stream
      out.writeBytes(tail);
      out.flush();
      out.close();

       // Get server response
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line = "";
      StringBuilder builder = new StringBuilder();
      while((line = reader.readLine()) != null) {
        builder.append(line);
      }
      serverResponseCode = conn.getResponseCode();
    serverResponseMessage = conn.getResponseMessage();
    ServerResponce=builder.toString();
    Log.e("ser res",ServerResponce.toString());
    }
    catch (Exception e) {
    Log.e("Exception",e.toString());
    progressDialog.dismiss();
    exceptionText=e.toString();
   
    } finally {  
      if (conn != null) conn.disconnect();
      //finish();
    }
   
    return null;
  }
   @Override
  protected void onProgressUpdate(Integer... progress) {
    progressDialog.setProgress((int) (progress[0]));
  }
   @Override
  public void onCancel(DialogInterface dialog) {
   super.onCancelled();
    cancel(true);
    dialog.dismiss();
    finish();
 
  }
 
  }



PHP Script

<?php

        $name=$_REQUEST['name'];
$target_path_videos = 'videos/';
$target_path_videos = $target_path_videos .'_'. basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path_videos))
{
  echo '1';
}
else
{
echo "Error";
}

 
?>

Android Sliding Menu using Navigation Drawer/ Hamburger

Download the Demo Project From Following link and import it in your eclipse ide.

Download

1. Find the String variables for List View items and icon names in strings.xml.(change as per your needs.)
2. Android introduced a newer UI element called DrawerLayout for Navigation Drawer. Open your layout file (activity_main.xml) for main activity and type the following code.
Here FrameLayout is used to replace the main content using Fragments and it should be always the first child of the layout for z-index purpose.
3.list_item_bg_normal.xml  and list_item_bg_pressed.xml represents list item state when normal and pressed.
4. Created another xml file to combine both the drawable states under res ⇒ drawable named list_selector.xml
5.counter_bg.xml  used  for rounde corner background for the counter value.
6. As listview has the custom layout, we need another layout file which defines the each list row. So create a layout file under res ⇒ layout named drawer_list_item.xml. This is a relative layout which places the icon, title and counter relative to one another.
7. In NavDrawerItem.java, isCounterVisible defines the visibility of the counter value.
8. in MainActivity.java, invalidateOptionMenu() is called in onDrawerOpened() and onDrawerClosed() to hide and show the action bar icons on navigation drawer opened and closed.

Thursday, December 26, 2013

Simple Fragments with Action Bar Example in Android 2.2, android:minSdkVersion="8",

Download(File->Download)

import it in eclipse if it having issues then follow the steps:

Setup the Android Support Libraries in your development project 
Support Library Setup
1. In eclipse File->Import>Existing Projects into workspace
Select a root directory->
C:\Program Files\Android\android-sdk\extras\android\support\v7\appcompat

2. add compatible library to your project.
Right click on your project ->Properties->Android->Library->add
select the V7 lib which you have imported in step 1.

3. Build and run.