Android Program to Demonstrate Binding a Service to an Activity

Here is the source code of the Program to Demonstrate Binding a Service to an Activity in Android using Java. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

MainActivity.java

package com.example.bind_service_activity;
 
import java.util.ArrayList;
import java.util.List;
 
import android.app.ListActivity;
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.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
 
public class MainActivity extends ListActivity {
    private LocalService s;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wordList = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                wordList);
        setListAdapter(adapter);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        bindService(new Intent(this, LocalService.class), mConnection,
                Context.BIND_AUTO_CREATE);
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        unbindService(mConnection);
    }
 
    private ServiceConnection mConnection = new ServiceConnection() {
 
        public void onServiceConnected(ComponentName className, IBinder binder) {
            s = ((LocalService.MyBinder) binder).getService();
            Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT)
                    .show();
        }
 
        public void onServiceDisconnected(ComponentName className) {
            s = null;
        }
    };
    private ArrayAdapter<String> adapter;
    private List<String> wordList;
 
    public void onClick(View view) {
        if (s != null) {
 
            Toast.makeText(this, "Number of elements" + s.getWordList().size(),
                    Toast.LENGTH_SHORT).show();
            wordList.clear();
            wordList.addAll(s.getWordList());
            adapter.notifyDataSetChanged();
        }
    }
}

LocalService.java

package com.example.bind_service_activity;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
 
public class LocalService extends Service {
    private final IBinder mBinder = new MyBinder();
    private ArrayList<String> list = new ArrayList<String>();
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
 
        Random random = new Random();
        if (random.nextBoolean()) {
            list.add("C");
        }
        if (random.nextBoolean()) {
            list.add("C++");
        }
        if (random.nextBoolean()) {
            list.add("C#");
        }
        if (random.nextBoolean()) {
            list.add("Java");
        }
        if (list.size() >= 20) {
            list.remove(0);
        }
        return Service.START_NOT_STICKY;
    }
 
    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }
 
    public class MyBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }
 
    public List<String> getWordList() {
        return list;
    }
 
}

MyReceiver.xml

package com.example.bind_service_activity;
 
import java.util.Calendar;
 
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
 
public class MyReceiver extends BroadcastReceiver {
 
    // Restart service every 30 seconds
    private static final long REPEAT_TIME = 1000 * 30;
 
    @Override
    public void onReceive(Context context, Intent intent) {
        AlarmManager service = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, MyStartServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 30);
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                cal.getTimeInMillis(), REPEAT_TIME, pending);
 
    }
}

Screenshot_2013-10-05-16-04-48

advertisement
advertisement

Screenshot_2013-10-05-16-05-01

Screenshot_2013-10-05-16-05-23

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.