Tuesday, May 31, 2011

Creating a Remote Background Service In Android.

How to create a basic Remote Services in Android:

Following article will illustrate how to create a simple basic Remote Service in Android that will run in the background, and which will be triggered by the activity.

Since last so many days I was struggling badly on creating a Remote background service in Android, For the same I found various articles, also went through many blogs, the docs for the android developers etc. Whatever articles I went through, the example given in them had some service task performing, which was confusing me, however I wanted a clear framework and design starting from a strach to implement the background service, and so is this post,

Following atricle will illustrate the basics of creating a Remote Background Service in Android.

The very first step is to create a new Android Project in Eclipse.

Then add the Service Interface in a '.aidl' file.

AIDL  (Android Interface Definition Language) is similar to the java interface with the method signature defined.

Following are the contents of 'RemoteServiceExample.aidl' file:

package com.example;

interface RemoteServiceExample {
      void doServiceTask();
}

Once after creating above file whenever you build the workspace, Eclipse generates the corresponding java interface, you can see the same in the 'gen' section. Also a care is to be taken that this is the autogenerated file and no need to modify the same.


Following is the code for the Core Service implementation:


package com.example;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder; 
import android.os.RemoteException;
import android.util.Log;


public class CoreRemoteService extends Service{
@Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return coreRemoteServiceStub;
}  

private Stub RemoteServiceExample.Stub coreRemoteServiceStub = new RemoteServiceExample.Stub() {
public void doServiceTask() throws RemoteException {
/// Write here, code to be executed in background
Log.d(getClass().getSimpleName(),"Hello World From Remote Service!!");
}   
};

@Override 
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(),"onCreate()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getSimpleName(),"onDestroy()");
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(getClass().getSimpleName(), "onStart()");
}
}

Form the above code have a look at the onBind() method, it returns the IBinder object. IBinder will represent the implementation of the remote service.
The implementation of the method of the 'aidl' interface (doServiceTask() in this example) is provided by the Stub class of the RemoteServiceExample.
In the method doServiceTask() will have the list of all the task to be executed while service is running. It can have the other method calls or the Code blocks to be executed. In the example I'm just printing a single line log "Hello World From Remote Service!!".

Now, coming to the main Activity class which will trigger the service, or we can say that the Activity will act as Client which can connect to the above created service. Have a look at the code for the same as follows:

package com.example;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;


public class ExampleRemoteService extends Activity {
RemoteServiceExample remoteServiceExample;
private RemoteServiceConnection conn = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        Intent i = new Intent();        
i.setClassName("com.example", "com.example.CoreRemoteService");
startService(i);
conn = new RemoteServiceConnection(); 
bindService(i, conn, Context.BIND_AUTO_CREATE);        
    }       
    class RemoteServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className, IBinder boundService ) {    
        remoteServiceExample = RemoteServiceExample.Stub.asInterface((IBinder)boundService);        
        try{
        remoteServiceExample.doServiceTask();
        }catch(RemoteException e){        
        e.printStackTrace();
        }        
          Log.d( getClass().getSimpleName(), "onServiceConnected()" );
        }


        public void onServiceDisconnected(ComponentName className) {          
  Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
        }
    };
    
}

Here I haven't kept any button to explicitly start the service, instead the service is started as the Activity is created.
An object of Intent is created, where the classname of the same is set, and then this object is passed as an argument of startService() method.
The class name set in the Intent is the fully qualified class name of the Class which extends 'Service', here in the example, 'CoreRemoteService' class.
Now the class 'RemoteServiceConnection' which implements 'ServiceConnection' interface is created to establish the connection with the remote service.
The object of this class along with the Intent object is passed as an argument in bindService() method.

Finally, we need to add a reference of the remote service created in Android Manifest file as follows:
<service android:name=".CoreRemoteService">
</service>

Now you are done with creating the remote background service.

As you install the apk and run on an Android Device or Emulator, service Prints in the log "Hello World From Remote Service!!".

Also you can check in your device, Settings>Applications>Running Service, the name of your service in the running services list.

So this was the very basic example of creating a remote background service in Android.

Thats all from my end!

Happy Coding!! :-))




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here



Friday, May 27, 2011

HTTP Post Request From Android Application

HTTP Post Request From Android Application

While writing Applications in Pure Native Android Java, following is the sample piece of code which will help to make the HTTP Post request.

       try {
           HttpClient client = new DefaultHttpClient();            
           String postURL = <SERVER_URL>;
           HttpPost post = new HttpPost(postURL);            
            List<NameValuePair> params = new ArrayList<NameValuePair>();                
            params.add(new BasicNameValuePair("Key1", "Value1"));
            params.add(new BasicNameValuePair("Key2", "Value2"));                           UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
               post.setEntity(ent);      
               HttpResponse responsePOST = client.execute(post);
               HttpEntity resEntity = responsePOST.getEntity();
               if (resEntity != null) {  
                   Log.i("RESPONSE",EntityUtils.toString(resEntity));
               }
       } catch (UnsupportedEncodingException uee){
        uee.printStackTrace();
       } catch (ClientProtocolException cpe){
        cpe.printStackTrace();
       } catch (IOException ioe){
        ioe.printStackTrace();
       }


Explanation:

Creating the Objects for HttpClient and HttpPost are required so as to execute the post request.
String postURL is the Server URL, where the HttpPost request is to be made, which is in turn an argument while creating HttpPost Object.
All the request parameters in the form of the Key Value Pair are to be set in the Arraylist,

List<NameValuePair> params = new ArrayList<NameValuePair>();  

'setEntity()' methods throws 'UnsupportedEncodingException'.

'execute()' method actually makes the call to the server as follows

HttpResponse responsePOST = client.execute(post);

'client.execute()' throws 'ClientProtocolException'

Make sure to catch all the exceptions and process accordingly as per the requirements.

Finally at last make sure to add internet permission in Android Manifest file of the Application as follows:

<uses-permission android:name="android.permission.INTERNET" />


Thats All For Now!

Happy Coding :-))

~Mayuri




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here



Thursday, May 26, 2011

Get Current Location (GPS Position) in Android Native Java Code

Get Current Location (GPS Position) in Android Native Java Code

Generally till now while developing Android Apps or I should say PhoneGap Supported Apps, to get the current GPS location, I always referred to the following function:

navigator.geolocation.getCurrentPosition(onSuccess, onError);

which instantly gives all the required location details like latitude, longitude, accuracy etc.

But then, how do I get these details which I'm not using a web app or I should say not a PhoneGap Application but a pure native Android Application or an Android Service, So for the same I tried researching  on the various articles and documents and finally arrived at the solution as follows:

package com.mayuri.location;
import java.sql.Timestamp;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log; 
import android.widget.TextView;
import android.widget.Toast;


public class LocationSample extends Activity {   
TextView tv;
    @Override 
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);         
    tv = (TextView)this.findViewById(R.id.txtLocation);
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);    
    }  
    private class mylocationlistener implements LocationListener {
    @Override 
    public void onLocationChanged(Location location) {    
     Date today = new Date();  
Timestamp currentTimeStamp = new Timestamp(today.getTime());
        if (location != null) {
        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        Strig str = "\n CurrentLocation: "+
        "\n Latitude: "+ location.getLatitude() + 
        "\n Longitude: " + location.getLongitude() + 
        "\n Accuracy: " + location.getAccuracy() + 
        "\n CurrentTimeStamp "+ currentTimeStamp;         
          Toast.makeText(LocationSample.this,str,Toast.LENGTH_LONG).show();
          tv.append(str);               
        } 
    } 
    @Override
    public void onProviderDisabled(String provider) {
    Toast.makeText(LocationSample.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
    }    
    @Override
    public void onProviderEnabled(String provider) {
    Toast.makeText(LocationSample.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    Toast.makeText(LocationSample.this,"onStatusChanged",Toast.LENGTH_LONG).show();
    }
    }
}

The heart of the Logic lies in the 'LocationManager' class, which provides an access to the System location services.  

'requestLocationUpdates' gives the periodic location updates as per the arguments specified.


The method, 'onLocationChanged' of the Interface 'LocationListener' gives the entire location details like Latitude, Longitude, Accuracy etc which can be used as per our requirements, currently In the example I'm periodically updating the text view as well as showing the Toast Popup of the location details along with the Current Timestamp.

Most Important thing to be remembered while using the LocationService in Android Application is to modify the Application manifest file with the following,

        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />      
        <uses-permission android:name="android.permission.INTERNET" />    
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Thats all on this from my end!!

Happy Coding :-))

~ Mayuri



Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here


Tuesday, May 24, 2011

Getting an Access of Android Java Code to a PhoneGap JavaScript.

PhoneGap Provides a standard set of functions available in PhoneGap docs to access the internal Device Details like the list of the phone numbers, access to camera etc.

Apart from this standard functions, if our requirements extends then these available functions, then we need to create our own custom logical functions which access the internal device hardware details like 'imei' number etc or to apply some custom logic or validate the data and then make it available to PhoneGap, then this article helps to do the same.

Though PhoneGap provides the 'imei' number through the standard function 'device.uuid' but in Android 2.1, it is still an issue. For such cases we need to take the help of the Native Android Java Code and then make it accessible to PhoneGap, here is how we will be doing the same.

Following example is of getting the device's 'imei' number through the Android's TelephonyManager class and then make it available to PhoneGap JavaScript:

Create a custom Class as follows:

import com.phonegap.DroidGap;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.webkit.WebView;


public class CustomNativeAccess {
    private WebView mAppView;
    private DroidGap mGap;
    public CustomNativeAccess(DroidGap gap, WebView view)
    {
        mAppView = view;
        mGap = gap;
    }   
    public String getImeiNumber(){
    TelephonyManager tm = (TelephonyManager) mGap.getSystemService(Context.TELEPHONY_SERVICE);
        String imeiId = tm.getDeviceId();      
        return imeiId;
    }
}

Function 'getImeiNumber()' retuns the 'imei' number of the device and the same function we will be using in PhoneGap Javascript.

Now Comming to the main Activity Class of the Application:


import com.phonegap.*;
public class MyActivity extends DroidGap {
    /** Called when the activity is first created. */
CustomNativeAccess cna;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        super.init();    
        cna = new CustomNativeAccess(this, appView);    
        appView.addJavascriptInterface(cna, "CustomNativeAccess");      
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

'appView' is an built in variable of DroidGap and it is initialized through the call 'super.init();'.
'appView.addJavascriptInterface' adds all the function of the specified class i.e. 'CustomNativeAccess' here in example, and makes it accessible in the JavaScript in PhoneGap Application.

Finally, to get the access in JavaScript,


var imeiNumber = window.CustomNativeAccess.getImeiNumber();

returns the valid 'imei' number.

I hope this article is useful for getting the Native Android Java Code Access to the PhoneGap's JavaScript.

~ Mayuri




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here


Step by Step Setup For Android Development Environment

Step by Step Setup For Android Development Environment

Following are the steps for setting up the basic development environment for Android Development.

The whole set of guidelines are given in the http://developer.android.com/index.html, but I have simplified the same as follows:

1) Download Eclipse Classic Galileo 3.5

http://www.eclipse.org/downloads/

2) Download Android SDK from the location given below (Choose the download as per the OS requirements)

http://developer.android.com/sdk/index.html

After the SDK is successfully downloaded, keep it in a known location as we will require the same in further setup process.

3) Install Android Adt Plugin for Eclipse with following steps:

Start Eclipse, then select Help > Install New Software.

Click Add, in the top-right corner.

In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:

https://dl-ssl.google.com/android/eclipse/

Click OK

Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).

In the Available Software dialog, select the checkbox next to Developer Tools and click Next.

In the next window, you'll see a list of the tools to be downloaded. Click Next.

Read and accept the license agreements, then click Finish.

Note: If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.

When the installation completes, restart Eclipse.

Select Window > Preferences... to open the Preferences panel.
Select Android from the left panel.

For the SDK Location in the main panel, click Browse... and locate your downloaded SDK directory.
Click Apply, then OK.


From within Eclipse, select Window > Android SDK and AVD Manager

To download components, use the graphical UI of the Android SDK and AVD Manager to browse the SDK repository and select new or updated components . The Android SDK and AVD Manager installs the selected components in your SDK environment.

Creating Android Virtual Devices:
From the above figure, Select 'Virtual Devices' tab.


In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD.
The Create New AVD dialog appears.


Fill in the details for the AVD.

Give it a name, a platform target, an SD card size, and a skin (HVGA is default). You can also add specific hardware features of the emulated device by clicking the New... button and selecting the feature.

Note: Be sure to define a target for your AVD that satisfies your application's Build Target (the AVD platform target must have an API Level equal to or greater than the API Level that your application compiles against).
Click Create AVD.
Your AVD is now ready and you can either close the SDK and AVD Manager, create more AVDs, or launch an emulator with the AVD by selecting a device and clicking Start.
For the full Set of Details Refer the following link:
http://developer.android.com/guide/developing/devices/managing-avds.html




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here


Animated Container in Flutter

Please check this flutter video tutorial for detailed example and implementation of Animated Container in Flutter.