fork download
  1. package com.example.testbinder2;
  2.  
  3. import android.os.*;
  4. import android.app.*;
  5. import android.content.ComponentName;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.ServiceConnection;
  9. import android.util.Log;
  10. import android.view.Menu;
  11. import android.view.View;
  12. import android.view.View.OnClickListener;
  13. import android.widget.*;
  14.  
  15. public class MainActivity extends Activity {
  16. Button getNum;
  17. TextView txtView;
  18. MyService mService;
  19. boolean bound;
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_main);
  24. getNum = (Button) findViewById(R.id.getRanBt);
  25. txtView = (TextView) findViewById(R.id.textViewFd);
  26. }
  27.  
  28. protected void onStart(){
  29. super.onStart();
  30. Intent intent = new Intent(this, MyService.class);
  31. bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
  32. Log.i("Started", "Now bound = " + bound);
  33. getNum.setOnClickListener(new OnClickListener() {
  34. @Override
  35. public void onClick(View arg0) {
  36. if (bound)
  37. Log.i("Service", "is running and returns " + mService.getNumber());
  38. else
  39. Log.i("Service", "is not running");
  40. }
  41. });
  42. }
  43.  
  44. protected void onStop() {
  45. super.onStop();
  46. if (bound) {
  47. unbindService(mConnection);
  48. bound = false;
  49. }
  50. }
  51.  
  52. private ServiceConnection mConnection = new ServiceConnection() {
  53. @Override
  54. public void onServiceConnected(ComponentName className,
  55. IBinder service) {
  56. // We've bound to LocalService, cast the IBinder and get LocalService instance
  57. MyService.MyBinder binder = (MyService.MyBinder) service;
  58. mService = binder.getService();
  59. bound = true;
  60. Log.i("Service Connection", "Connected");
  61. }
  62.  
  63. @Override
  64. public void onServiceDisconnected(ComponentName arg0) {
  65. bound = false;
  66. Log.i("Service Connection", "Disconnected");
  67. }
  68. };
  69.  
  70. @Override
  71. public boolean onCreateOptionsMenu(Menu menu) {
  72. // Inflate the menu; this adds items to the action bar if it is present.
  73. getMenuInflater().inflate(R.menu.main, menu);
  74. return true;
  75. }
  76. public class MyService extends Service {
  77. MyBinder mBinder = new MyBinder();
  78. @Override
  79. public IBinder onBind(Intent arg0) {
  80. // TODO Auto-generated method stub
  81. return mBinder;
  82. }
  83. public class MyBinder extends Binder {
  84. MyService getService() {
  85. return MyService.this;
  86. }
  87. }
  88. public int getNumber() {
  89. return 10;
  90. }
  91. }
  92. }
  93.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty