CodeChrist - This is a personal blog which I write to help follow coders

If you like it, feel free to comment and appreciate the good work


Following are the some features of CodeChrist

  • Easy to navigate and use.
  • You can subscibe for emails
  • CodeChrist is beautiful on every screen size (try resizing your browser!)
by

Making a Background Service and Parsing some JSON from URL

Making a background service is really easy. We just need to extend Service() class in any of our class to make it a service. Implement its method and you are done. And just one more thing, don't forget to call it from your main activity using Intent.

In this post, the JParsingInBackground class which extends Service will continuously run in background and will hit the URL and fetch JSON data every 60 sec.

MainActivity.java


package com.example.jsoninbackground;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
               // to invoke service the first time
Intent mServiceIntent = new Intent(this, JparsingInBackground.class);
this.startService(mServiceIntent);
Log.e("Activity started","Running activity");
}

}

JparsingInBackground.java


package com.example.jsoninbackground;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class JparsingInBackground extends Service {

JSONParser jsonParser;
JSONObject jsono;

JSONArray category = null;


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

private Handler mHandler = new Handler();
private NotificationManager mNotificationManager;
private int numMessages = 0;
private static String url = "http://stringr.in/application/DB_fetchCategoryFromDB.php";
private static final String TAG_CATEGORY = "category";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG = "tag";
private static final String TAG_NAME = "name";
       
         // makes the service run infinitely
private void ping() {
try {
new GetContacts().execute();
} catch (Exception e) {
Log.e("Error", "In onStartCommand");
e.printStackTrace();
}
scheduleNext();
}

private void scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() {
ping();
}
}, 60000);
}

public int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {

Log.e("IBinder started", "Running finely");
return null;
}
        // Async task to fetch JSON
private class GetContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {

try {

jsonParser = new JSONParser();
params.add(new BasicNameValuePair("bid", "1"));
//json object
jsono = jsonParser.getJSONFromUrl(url, params);
category = jsono.getJSONArray(TAG_CATEGORY);
for (int i = 0; i <category.length(); i++) {
JSONObject c = category.getJSONObject(i);
str = c.getString("name");
Log.e("name",str);
}

} catch (Exception e) {
e.printStackTrace();
Log.e("ee", e.toString());
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
displayNotification(str);

}
}

       //This is a function to show notifications

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void displayNotification(String name) {
Log.i("Start", "notification");
/* Invoking the default notification service */
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext());
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle(name);
mBuilder.setContentText(name);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
mBuilder.setDefaults(Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_SHOW_LIGHTS);
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);
/* Creates an explicit intent for an Activity in your app */
Intent resultIntent = new Intent(getApplicationContext(),
MainActivity.class);
resultIntent.putExtra("name", name);
TaskStackBuilder stackBuilder = TaskStackBuilder
.create(getApplicationContext());
stackBuilder.addParentStack(MainActivity.class);
/* Adds the Intent that starts the Activity to the top of the stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
/* notificationID allows you to update the notification later on. */
mNotificationManager.notify(100, mBuilder.build());
mBuilder.setVibrate(null);

}

}

We also need to add service to the manifest file and add internet and some other permissions.

Manifest File

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

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />
      
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.jsoninbackground.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>
         <service
            android:name=".JparsingInBackground"
            android:exported="false" />
    </application>

</manifest>




0 comments:

Post a Comment