Tuesday, October 21, 2014

Android Services - Introduction

What is Service?

A service is a component that runs in background to run operation/tasks without user interaction.
i.e, a service might play music in the background while the user is in a different application, or it might fetch data over the server without blocking user interaction with in an activity.

Many Android apps need to do some things in the background when your application isn't open .
Maybe we need to periodically abstract data from server or maybe we need to have certain tasks run on an interval that is specified by users. Android Service is the best for these tasks.

Is service different from thread??

As we know services and thread are both run on background and both are run without user interaction. But they are very different in how they are applied in android application, and most importantly services is not a thread. It runs on the UI thread(User Interface thread) along with our application. Some time we have to use thread inside of services while lifting some heavy data from server in our application.

A service is usually take two state

1. Started:
It is started by activity by calling startService(), once it is started it runs on background indefinitely. It is basically used for downloading/uploading file over server (which is done for one time operation).
After its done it should stop itself.


2. Bound:

It is started by activity by calling bindService(). A bount service offers client-server interface that allow component to interact with service, send request , get result, and even do so across processes with interprocess communication(IPC).

There are two type of services 

1. Platform services:
The android Platform Services are default android system services. The Android platform provides and runs predefined system services and every Android application can use them, given the right permissions. These system services are usually exposed via a specific Manager class. To access them we need  getSystemService() method. The Context class defines several constants for accessing these services.

2. Custom Services:
Custom services allows us to design responsive applications.We can fetch the application data via it and once the application is started by the user, it can present fresh data to the users.

How to create a custom services in android app, its so simple look below.

//creating a new class for service
public class MyService extends Service {
  @Override
  public IBinder onBind(Intent arg0) {
            //TODO for communication return IBinder implementation
           return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
     // Let it continue running until it is stopped.
     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
     return START_STICKY;
  }

  @Override
  public void onDestroy() {
     super.onDestroy();
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  }
}

 Calling  services in our activity....

public class MainActivity extends Activity {
@Override 

     public void onCreate(Bundle savedInstanceState)
      {  
         super.onCreate(savedInstanceState);
setContentView(R.layout.main);

             //Start service 
startService(new Intent(getBaseContext(), MyService.class));
     }

Finally a service needs to be declared in the AndroidManifest.xml file...like below
 <service android:name=".MyService" />


How to start Services regularly via AlarmManager?

Here is the complete example of starting Service regularly via AlarmManager to notify user through NotificationManager. For this we need to create MyService (extends IntentService), AlarmNotificationReceicer (extends BroadcastReceiver), MainActivity (extends Activity) and declare service and receiver in AndroidMinfeast.xml file...See  below.....

1. Make a Class for Service which Extends IntentService.

package com.examples.semicolon.Alarms;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;

public class MyService extends IntentService {

private AlarmManager mAlarmManager;
private Intent mNotificationReceiverIntent, mLoggerReceiverIntent;
private PendingIntent mNotificationReceiverPendingIntent,
mLoggerReceiverPendingIntent;
private static final long INITIAL_ALARM_DELAY = 1 * 60 * 1000;

public MyService() {


super("Semicolon");
}

@Override
protected void onHandleIntent(Intent intent) {

// Get the AlarmManager Service(platform services)
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

// Create PendingIntent to start the AlarmNotificationReceiver
mNotificationReceiverIntent = new Intent(MyService.this,
AlarmNotificationReceiver.class);
mNotificationReceiverPendingIntent = PendingIntent.getBroadcast(
PlayService.this, 0, mNotificationReceiverIntent, 0);

// seting repeated alarm
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + INITIAL_ALARM_DELAY,
INITIAL_ALARM_DELAY, mNotificationReceiverPendingIntent);

}

}


2. Make a class for Notification which extends BroadcastReceiver

package com.examples.semicolon.Alarms;

import java.text.DateFormat;
import java.util.Date;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import course.examples.Alarms.AlarmCreate2.R;

public class AlarmNotificationReceiver extends BroadcastReceiver {
// Notification ID to allow for future updates
private static final int MY_NOTIFICATION_ID = 1;
private static final String TAG = "AlarmNotificationReceiver";

// Notification Text Elements
private final CharSequence tickerText = "Are You Playing games Again!";
private final CharSequence contentTitle = "A Kind of Reminder";
private final CharSequence contentText = "Get back to studying!!";

// Notification Action Elements
private Intent mNotificationIntent;
private PendingIntent mContentIntent;

// Notification Sound and Vibration on Arrival
private Uri soundURI = Uri.parse("android.resource://com.examples.semicolon.Alarms/"
+ R.raw.alarm_rooster);
private long[] mVibratePattern = { 0, 200, 200, 300 };

@Override
public void onReceive(Context context, Intent intent) {

mNotificationIntent = new Intent(context, MainActivity.class);
mContentIntent = PendingIntent.getActivity(context, 0,
mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

                 // notification building
Notification.Builder notificationBuilder = new Notification.Builder(

context).setTicker(tickerText)
.setSmallIcon(android.R.drawable.stat_sys_warning)// icon from drawable
.setAutoCancel(true).setContentTitle(contentTitle)
.setContentText(contentText).setContentIntent(mContentIntent)
.setSound(soundURI).setVibrate(mVibratePattern);

// Pass the Notification to the NotificationManager:
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());

Log.i(TAG,"Sending notification at:" + DateFormat.getDateTimeInstance().format(new                      Date()));

}
}

3. Creating  the activity and calling the service in an activity.


package com.examples.semicolon.Alarms;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import course.examples.Alarms.AlarmCreate2.R;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
                //start the service
startService(new Intent(getBaseContext(), MyService.class));
}
}

4. Defined the Service and Receiver in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.examples.semicolon.Alarms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

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

    <application
        android:allowBackup="false"
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name="com.examples.semicolon.Alarms.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver android:name="com.examples.semicolon.Alarms.AlarmNotificationReceiver" />
        <service android:name="com.examples.semicolon.Alarms.PlayService" />

    </application>

</manifest>

The output of  above code: You will receive a notification in every 1 minute of time interval even your app is not open.



Sunday, October 12, 2014

WordPress JSON API Development

WordPress is a fully featured framework with high user friendly nature and variable option of customization. There is also an availability of rss feed but when we need to built our own customized API, it is a troubling matter. I assume you are already familiar with WordPress hooks, action and filter. In this tutorial, we are going to learn about how to built our own custom API and feed the data in well known JSON format.

To create an API, the three things are required:

  1. URI : Path for accessing API
  2. Custom Variable : Required if values is being sent using GET Method
  3. Query handler : Handling the Request

Step 1: Generating URI for the API

URI is the method of accessing API defined for particular task and addition data is send to determine the action. WordPress has a convenient way to define URL. It has a built in action for rewrite rule.

add_rewrite_rule($regex, $redirect, $after);
$regex- It is used to define the URI of API like what is to be sent and a what the receiver can expect. Eg: www.example.com/values/?[0-9]
  • $redirect- It actually takes the GET data and array-matches[] is used to get the values. Eg:  www.example.com/values/?id=matches[1]
  • $after- It has two option top and bottom. "top" does not require checking of existing WordPress rule while "bottom" requires.  

Step 2: Registering Custom Variables

Custom variables are the one which is sent through the URI as like values and id in above cases. In order to use custom variable, they must be registered so that WordPress can recognize them and we can use or get them anywhere we need.

add_filter( 'query_vars', 'function_name');
function function_name($vars){
$vars[]="values";
$vars[]="id";
return $vars;
}
Now, we have two variables "values" and "id" which can be passed through the URI and it can be accessed as

global $wp;
$wp->query_vars['id'];
$wp->query_vars['values'];

Step 3: Sniffing Request and Handling Queries

We have all the necessary backbone for API but we need one more thing i.e. Query Handler. When a URI is entered in the address bar, we need to get that address and check whether that address is for our API or not, if yes we need to perform our task otherwise let it go. WordPress has a beautiful hook for it and check if our variable is present or not.

add_action('parse_request',  'sniff_requests');
function sniff_requests(){
 global $wp;
  if (!empty($wp->query_vars['values']) AND !empty($wp->query_vars['id']) ) {
$this->handle_request();
exit;
  }
}
If the URI has our function, we can run our function(handle_request) otherwise we let WordPress handle it.

 

© 2013 Echo "Semicolon Developers"; Kathmandu. All rights resevered @ Semicolon Developers Network Pvt. Ltd.. Designed by Templateism

Back To Top