Friday, 27 February 2015

.Net WebMethod for Uploading Picture


It is often necessary to upload pictures/video from Android app to server. If you are working with .Net Web service/API in Android app. Then you need to write a web method in your .Net web service for uploading picture(s).
From Android app, you send image encoded as Base64 String to web service. The web method receives the encoded Base64 String and perform necessary manipulation to save and upload pictures.

Here is webmethod code.

[WebMethod]
    [SoapHeader("Authentication")]      //--Authentication Header- if necessary
    public String saveImage(string encodedData, string image_name)
    {
        EventLog.WriteLog("-------------------------Start Time:  " + DateTime.Now.ToString() + "-----------------------savePicture--");//write log for tracing
        String result = null;
        try
        {
            if (encodedData != null && encodedData != "")
            {

                //EventLog.WriteLog("-------------------------Encoded Data:\n  " + encodedData + "-----------------------savePicture--");
                // Convert Base64 String to byte[]
                byte[] imageBytes = Convert.FromBase64String(encodedData);
                Stream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
                                
                // Convert byte[] to Image
                ms.Write(imageBytes, 0, imageBytes.Length);
               
                Image image = Image.FromStream(ms, true);
                //string path = @"G:\Pictures\";
                              
                String imageName = image_name + ".png";
                //path += imageName;

                result = UploadFile(imageBytes, imageName);                
            }
            return result;
        }
        catch (Exception ex)
        {
            string sClientLog = System.Environment.NewLine + DateTime.Now.ToString().PadRight(30, ' ') + ex.Message + ", " + ex.StackTrace;
            EventLog.WriteLog("Application-Name:" + sClientLog);//write exception in log for error tracing
            return "Picture not Saved\nPlease Try Again";
        }
        finally
        {
            EventLog.WriteLog("-------------------------End Time:  " + DateTime.Now.ToString() + "-----------------------savePicture--");           
        }
    }

    private String UploadFile(byte[] image , string fileName)
    {
        try
        {
            EventLog.WriteLog("-------------------------UploadFile:\n  " + fileName + "-----------------------Uploading Picture--");
            //FileInfo toUpload = new FileInfo(fileName);
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://IP-Address/Folder/Pictures/" + "/" + fileName);//Create a folder for pictures
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // request.Credentials = new NetworkCredential("anonymous", "write your email address here");
            Stream ftpStream = request.GetRequestStream();
            //FileStream file = File.OpenRead(fileName);
            int length = 1024;
            byte[] buffer = new byte[image.Length];
            int bytesRead = 0;

            for (int i = 0; i < image.Length; i += length)
            {
                try
                {
                    if (bytesRead + 1024 > image.Length)
                    {
                        int remLength = image.Length - bytesRead;

                        byte[] buffer2 = new byte[remLength];

                        Buffer.BlockCopy(image, i, buffer2, 0, remLength);

                        bytesRead += remLength;

                        ftpStream.Write(buffer2, 0, remLength);
                    }
                    else
                    {
                        Buffer.BlockCopy(image, i, buffer, 0, length);

                        bytesRead += length;

                        ftpStream.Write(buffer, 0, length);
                    }
                }
                catch (Exception ex)
                {
                    EventLog.WriteLog("-----------------Exception:\n" + ex.Message.ToString() + "-----------------------Exception--");
                    return "Picture not Saved\nPlease Try Again.";//write exception in log for error tracing
                }
            }

This is all about uploading pictures through web method of .Net web service.
Please don't forget to ask if you are facing difficulty in implementing this post. Your valuable suggestions are highly appreciated and please correct me if I am doing something wrong in this post.

Thank you

Thursday, 26 February 2015

Google Cloud Messaging (GCM) Client Code


To create a working client/Android end code, you have to create an Android application with GCM implementation. For GCM Android app, you need the following classes:

1. GCMIntentService class – which is responsible for creating the push notifications.

2. GcmBroadcastReceiver – which invokes the GCMIntentService class whenever a push notifications is received.

3. MainActivity – which is responsible for registering the android device with the Google GCM Server and returns the Registration ID.

Now, I have attached complete GCM Server and GCM Client source code. You can simply download and work with the source code. If something need to fix, please don't hesitate to correct me. If this code works for you, please don't forget to give your feedback.

Thank you very much for all users who provided their valuable feedback, thus I attached complete source code for server and client.  

Wednesday, 31 December 2014

Creating Custom Dialog from Layout File


In this post, I will show how to create a custom dialog using xml layout file.
First you have to create a xml layout file. After creating layout file than you have to open activity in which you want to display dialog. Here, layout file contains a button "OK" as an example.

In the activity, declare the Dialog and than create a method as below:

private Dialog myDialog;

private void showDialog() { 


myDialog = new Dialog(this,R.style.wideDialogStyle);
myDialog.setCancelable(false);
myDialog.setCanceledOnTouchOutside(false);
myDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT);
myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myDialog.setContentView(R.layout.log_in);
myDialog.show(); 
 
// Set up the Button
okBtn = (Button) myDialog.findViewById(R.id.ok_btn); okBtn.setOnClickListener(okBtnListener); 
} 

//This is the onClickListener() for OK button of the Dialog
private Button.OnClickListener okBtnListener = new Button.OnClickListener() { 
@Override 
public void onClick(View v) { 
myDialog.dismiss();


Thank you for visiting my blog.

Monday, 22 December 2014

Check SIM card availability in Android.


 
Sometimes, It is necessary to check the availability of Network service in Android. Here is the code.

TelephonyManager telephonyManager= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

int simState = telephonyManager.getSimState();
switch (simState) {

    case TelephonyManager.SIM_STATE_ABSENT:
       Toast.makeText(context, "SIM Card Not Available., Toast.LENGTH_SHORT).show();
       break;
     case TelephonyManager.SIM_STATE_READY:
       Toast.makeText(context, "SIM Card Available.", Toast.LENGTH_SHORT).show();

}

Sunday, 21 December 2014

Viewpager/Fragment Tabs Adapter

While working with Viewpager which contains multiple Tabs and each tab is a fragment, it is necessary to have an adapter which decides which fragment should be called when user taps on a specific viewpager tab. For this you have to specify a list of fragments which is passed to adapter then this adapter is set to the viewpager. Here is the method to add and returns an ArrayList of type Fragment.
    
    public ArrayList<Fragment> defaultFragmentList(){
         
        ArrayList<Fragment> fragmentsList = new ArrayList<Fragment>();
         
        fragmentsList.add(new FirstFragment());
        fragmentsList.add(new SecondFragment());
        fragmentsList.add(new ThirdFragment());
         
        return fragmentsList;
    }
After having an arraylist of fragments type we have to pass this list to tabs adapter. Here is the method which takes the fragments arraylist and pass it to adapter.This adapter is set to the viewpager as below:


    public void populateFragments(ArrayList<Fragment> fragmentsList){
         
        mAdapter = new TabsPagerAdapter(this, getSupportFragmentManager(), fragmentsList);   
        viewPager.setAdapter(mAdapter);       
    }

In the onCreate method of the main activity, we call the above methods as:

populateFragments(defaultFragmentList());


Now, here is the complete code of TabsPagerAdapter class. 
import java.util.ArrayList;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
    final int TABs=3;
    Context context;
    FragmentManager mFragmentManager;
    ArrayList<Fragment> mFragmentsList;
    public TabsPagerAdapter(Context mContext, FragmentManager fm, ArrayList<Fragment> fragmentsList) {
        super(fm);
        
        context=mContext; 
        mFragmentsList = fragmentsList;     
        mFragmentManager=fm;
    }
    @Override
    public Fragment getItem(int index) {
    
         Fragment fragment =null;                   
         switch (index) {         
         case 0:
             // FirstFragment
             fragment = mFragmentsList.get(0);
             break;
         case 1:   
             // SecondFragment
             fragment = mFragmentsList.get(1);
              break;
         case 2:
             // ThirdFragment
             fragment = mFragmentsList.get(2);
              break;
         }       
         return fragment;                        
    }       
    @Override
    public int getCount() {
         
        // get item count - equal to number of tabs
        return TABs;
    

This is one of the simple code.
In case you feel that I need to improve this post/blog Please don't hesitate to comment.
Thank you.

Calling an Activity from Service

To call an activity from service class through intent, write the code as below:


Intent intent=new Intent(UpdateWidgetService.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

where

"UpdateWidgetService" is the service class from where you are calling activity.
"Main" is the name of activity class.

Saturday, 26 April 2014

Android Custom Push Notifications


Custom Push Notifications 


In Android Push Notifications, it often happens that the a complete message/text is not visible. For small message/text it is ok but in case of longer message/text it is necessary to show complete message/text on a single push notification. It can be easily done by creating custom push notification in android. By using custom notification it does not matter how longer message/text you want to display on a single notification.

For custom push notification, first you need to create a custom layout. Here is sample layout which you can use or create your own custom layout for push notification. Then you can use this custom layout for notification.

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="100dp"
      android:gravity="center_vertical"
      android:background="#f0f0f0">
    <ImageView
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:layout_width="wrap_content"
        android:id="@+id/image"
        android:layout_marginLeft="10dip"
        android:layout_centerVertical="true"
        android:contentDescription="icon" />
    <LinearLayout
        android:gravity="center_vertical"
        android:layout_height="match_parent"
        android:layout_width="fill_parent"
        android:layout_toRightOf="@+id/image"
        android:orientation="vertical">
          <TextView
            android:text="TextView" 
            android:textStyle="bold"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:textSize="14sp"        
            android:id="@+id/title"
            android:textColor="#3D3A34"
            android:layout_marginLeft="10dip"/> 
          <TextView
            android:gravity="center_vertical"
            android:text="TextView" 
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:textSize="12sp"
            android:id="@+id/text"
            android:textColor="#3D3A34"
            android:layout_marginLeft="10dip"
            android:singleLine="false"
            android:maxLines="8"/>              
    </LinearLayout>
</RelativeLayout>

Save this layout with "custom_notification.xml". This layout will be used in GCMIntentService Class.
After creating custom layout, create a method in GCMIntentService class as given below:

    private static void generateCustomNotification(Context context,
            String message, String title) {
               
        try{            
           
  int icon = R.drawable.applogo; // this is the icon which you can set for notification, I set applogo as icon.
            long when = System.currentTimeMillis();
            RemoteViews contentView = new RemoteViews("com.yourpackname", R.layout.custom_notification);// custom_notification.xml layout used here

            contentView.setImageViewResource(R.id.image,icon);
            contentView.setTextViewText(R.id.title,  title); // title of push notification
            contentView.setTextViewText(R.id.text,  message); //// message/text of push notification

            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new Notification(icon, message, when);
          
            Intent notificationIntent = new Intent(context, YourActivity.class); //YourActivity will be activity of your project where you want to redirect user when he/she taps on push notification.
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // set intent so it does not start a new activity 
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
            PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
            notification.contentIntent = intent ;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
            notification.defaults |= Notification.DEFAULT_VIBRATE; //Whenever a push notification receives, phone vibrates. For this, you need Vibrate permission in Manifest file. Otherwise, app crashes.
            notification.defaults |= Notification.DEFAULT_LIGHTS;
            notification.contentView = contentView;
            notificationManager.notify(counter, notification); //static int counter = 0; this counter will be used if you send multiple push notifications so each notification displays as separate notification.
            counter ++;
        }catch (Exception e) {
           
        }
    }



That's all about Custom push notification. 


Thanks visiting my blog. Please don't forget to give your feedback.
I welcome your valuable suggestions.