Hi .... Dear All .... Today I am uploading a superb example of Bound Service .
A bound service is the server in a
client-server interface.
A
bound service allows components (such as activities) to bind to the service,
send requests, receive responses, and even perform interprocess communication
(IPC).
A
bound service typically lives only while it serves another application
component and does not run in the background indefinitely.
Bound services are created
as sub-classes of the Android Service class and must, at a minimum, implement
the onBind() method.
This method returns an
IBinder
object that defines the programming interface that clients
can use to interact with the service.
The
bindService()
method returns immediately without a value, but when the
Android system creates the connection between the client and service, it calls onServiceConnected()
on the ServiceConnection
, to deliver the IBinder
that the client can use to communicate with the service.
Lets see an
example
A.
Implement the Binder
public class BindServ extends Service
{
private final IBinder mBinder = new LocalBinder();
public
class LocalBinder extends Binder
{
BindServ getMyServ()
{
return BindServ.this;
}
}
{
BindServ getMyServ()
{
return BindServ.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public
void dis()
{
Toast.makeText(this,"Hello finally Married",Toast.LENGTH_LONG).show();
}
}
{
Toast.makeText(this,"Hello finally Married",Toast.LENGTH_LONG).show();
}
}
B. Preapre the Client
public class BindingActivity extends AppCompatActivity { BindServ mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chapservices1); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this,BindServ.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); if(mBound) { unbindService(mConnection); mBound=false; } } public void startMyService(View view) { if(mBound) { mService.dis(); } } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { BindServ.LocalBinder binder = (BindServ.LocalBinder)service; mService = binder.getMyServ(); mBound=true; } @Override public void onServiceDisconnected(ComponentName name) { mBound=false; } }; }
C. Output will be like
No comments:
Post a Comment