Monday 6 May 2013

Android Update a ui using BroadcastReceiver | Android BroadcastReceiver Example | Android Service


Hello Friends , Have you thinking about calling the service in your android app.
Trying to start service when you receive some type of notifiaction or need to refresh a view
or activty after getting new data from web service or need to refresh
your activity after every few second of time interval.

Yes , this android article help you a lot. In my case I wanted to refresh my activity silently
whenever I received new data  in my web service response.

For this I used Broadcast receiver and services and things work like charm to me  :)


1.What is Broadcast receiver??
  A broadcast receiver  is an Android component which allows you to register
  for system or application events.

 Let’s start with BroadcastReceiver: Here we will try to refresh our view via
 Android service call.


First of all we need to define private variable in our Activity:
//---------------------------

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
   public void onReceive(Context context, Intent intent) {
updateDate(intent);
   }
};

//---------------------------

2.Then we override methods onResume() where our broadcast receiver will be registered
  and also onPause() where will our receiver be unregistered:

//---------------------------
@Override
public void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver, new IntentFilter(
MyService.BROADCAST_ACTION));
}

@Override
public void onPause() {
super.onPause();
// unregisterReceiver(broadcastReceiver);
}
//---------------------------

3.Now we can start our service (onStart), send a broadcast message and we will show a toast message.
   And also update the UI afeter ever few(7 second) second.

//---------------------------
package com.mukesh.services;

import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

public class MyService extends Service {
        public static final String BROADCAST_ACTION = "com.mukesh.service";
        private final Handler handler = new Handler();
        Intent intent;
        int counter = 0;

        @Override
        public void onCreate() {
                // Called on service created
                intent = new Intent(BROADCAST_ACTION);
        }

        @Override
        public void onDestroy() {
                // Called on service stopped
                stopService(intent);
        }

        @Override
        public void onStart(Intent intent, int startid) {
                int i = 0;
                while (i <= 2) {
                        if (i > 1) {
                                i++;
                                this.onDestroy();
                        } else {
                                counter = i;
                                i++;
                                handler.removeCallbacks(sendUpdatesToUI);
                                handler.postDelayed(sendUpdatesToUI, 1 * 1000); // 1 sec
                        }

                }

        }

        private Runnable sendUpdatesToUI = new Runnable() {
                public void run() {
                        DisplayLoggingInfo();
                        handler.postDelayed(this, 7 * 1000); // 7 sec
                }
        };

        private void DisplayLoggingInfo() {

                intent.putExtra("time", new Date().toLocaleString());
                intent.putExtra("counter", String.valueOf(counter));
                sendBroadcast(intent);
                stopService(intent);
        }

        public static boolean isRunning() {
                return true;
        }

        @Override
        public IBinder onBind(Intent intent) {
                return null;
        }
}


//---------------------------
4. Don’t forget to add this service declaration in your AndroidManifest.xml in
    order to be set up properly:

//----------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SimpleCalendarViewActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

//----------------------------


Download Source code:
Android Service Demo


Enjoy Coding :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

3 comments:

  1. Thank you very much. Helped me in completing the service

    ReplyDelete
  2. Where is Toast?

    ReplyDelete
  3. HI frnd I have new in android i have create one project in that read galley, colect web history, gps, and all catch the data using broadcast receiver but i have problem is i have start services in one button click so it ii dispaly not responding msg.
    pls give me the solution if you have

    ReplyDelete

 

Copyright @ 2013 Android Developers Blog.