package com.example.testbinder2;
import android.os.*;
import android.app.*;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class MainActivity extends Activity {
TextView txtView;
MyService mService;
boolean bound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getNum
= (Button) findViewById
(R.
id.
getRanBt); txtView = (TextView) findViewById(R.id.textViewFd);
}
protected void onStart(){
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService
(intent, mConnection,
Context.
BIND_AUTO_CREATE); Log.i("Started", "Now bound = " + bound);
getNum.setOnClickListener(new OnClickListener() {
@Override
public void onClick
(View arg0
) { if (bound)
Log.i("Service", "is running and returns " + mService.getNumber());
else
Log.i("Service", "is not running");
}
});
}
protected void onStop() {
super.onStop();
if (bound) {
unbindService(mConnection);
bound = false;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MyService.MyBinder binder = (MyService.MyBinder) service;
mService = binder.getService();
bound = true;
Log.i("Service Connection", "Connected");
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
Log.i("Service Connection", "Disconnected");
}
};
@Override
public boolean onCreateOptionsMenu
(Menu menu
) { // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class MyService extends Service {
MyBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
public int getNumber() {
return 10;
}
}
}