how can I get return value from android services

匿名 (未验证) 提交于 2019-12-03 00:52:01

问题:

I got the problem that I don't know how can I fetch return value from services. Why I want return value from services is I want to show this return value in Activity page. Following is my services file and return value is retvalue.

public class SyncService extends Service{     private String forSync, lastrecordfromlocal, userdefined;     DatabaseUtil dbUtil = new DatabaseUtil(this);      @Override     public IBinder onBind(Intent arg0) {         // TODO Auto-generated method stub         return null;     }      @SuppressWarnings("deprecation")     @Override     public void onStart(Intent intent, int startId) {         // TODO Auto-generated method stub         super.onStart(intent, startId);             forSync = common.getInfoForSync(this);          String[] getlist = forSync.split(":");         lastrecordfromlocal = getlist[0].toString();          userdefined = getlist[1].toString();          if (common.isNetAvailable(this) == true) {             SyncServiceTask InstallData = new SyncServiceTask(this);             try {                 String (((retvalue))) = InstallData.execute(lastrecordfromlocal, userdefined).get();             } catch (InterruptedException e) {                 e.printStackTrace();             } catch (ExecutionException e) {                 e.printStackTrace();             }                                        }                 this.stopSelf();     }      @Override     public void onDestroy() {         super.onDestroy();     }     }

回答1:

You can bind service to the Activity:link

Your Service:

  public class SyncService extends Service {   private final IBinder mBinder = new MyBinder();   private String;    @Override   public int onStartCommand(Intent intent, int flags, int startId) {       forSync = common.getInfoForSync(this);      String[] getlist = forSync.split(":");     lastrecordfromlocal = getlist[0].toString();      userdefined = getlist[1].toString();      if (common.isNetAvailable(this) == true) {         SyncServiceTask InstallData = new SyncServiceTask(this);         try {             String (((retvalue))) = InstallData.execute(lastrecordfromlocal, userdefined).get();         } catch (InterruptedException e) {             e.printStackTrace();         } catch (ExecutionException e) {             e.printStackTrace();         }                                    }         return Service.START_NOT_STICKY;   }    @Override   public IBinder onBind(Intent arg0) {     return mBinder;   }    public class MyBinder extends Binder {     SyncService getService() {       return SyncService .this;     }   }    public String getRetValue() {     return retvalue;   }  }

And in Activity check the value:

SyncService mService;     @Override         protected void onStart() {             super.onStart();             // Bind to LocalService             Intent intent = new Intent(this, SyncService .class);             bindService(intent, mConnection, Context.BIND_AUTO_CREATE);         }          @Override         protected void onStop() {             super.onStop();             // Unbind from the service             if (mBound) {                 unbindService(mConnection);                 mBound = false;             }         }          /** Called when a button is clicked (the button in the layout file attaches to           * this method with the android:onClick attribute) */         public void onButtonClick(View v) {             if (mBound) {                  Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();             }         }      /** Defines callbacks for service binding, passed to bindService() */         private ServiceConnection mConnection = new ServiceConnection() {              @Override             public void onServiceConnected(ComponentName className,                     IBinder service) {                 LocalBinder binder = (LocalBinder) service;                 mService = binder.getService();                 mBound = true;             }              @Override             public void onServiceDisconnected(ComponentName arg0) {                 mBound = false;             }         };


回答2:

As far as I know, the common way for service to communicate with activity is by BROADCAST.

You can send a broadcast at the position you want to "return retvalue" by something like:

Intent retIntent = new Intent(ServiceReturnIntent); retIntent.putExtra("retvalue", retvalue); sendBroadcast(retIntent);

which ServiceReturnIntent and "retvalue" are all self-defined strings to identify the broadcast and value name.

And in your activity which wishes to catch the return value, you should have a broadcast receiver, with something like:

public class myActivity extends Activity implements BroadcastReceiver {     TextView myTextView;   @Override      OnCreate(Bundle savedInstanceState) {          setContentView(R.layout.simple_layout);          myTextView = (TextView) findViewByID(R.id.simple_textview);      }     @Override     public void onReceive(Context context, Intent intent) {          int action = jumpTable.get(intent.getAction());         switch (action) {     case ServiceReturnIntent:             String valueFromService = intent.getStringExtra("retvalue");                 myTextView.setText(valueFromService);                 break;             // handle other action           ......     } }

You can read this tutorial for more about broadcast in android.

EDIT modify sample code with setting it to a textview



回答3:

if you want service to communicate with activity.we have two method.

1, you can use BROADCAST. you can send BROADCAST in service and use BroadcastReceiver in activity.

2, you also can use bindService to communicate activity.

public class LocalService extends Service {     // This is the object that receives interactions from clients.  See     // RemoteService for a more complete example.     private final IBinder mBinder = new LocalBinder();      public class LocalBinder extends Binder {         LocalService getService() {             return LocalService.this;         }     }      @Override     public IBinder onBind(Intent intent) {         return mBinder;     } }

you can use iBinder to communicate with service



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!