Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get return value from android services

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();
    }    
}
like image 483
PPShein Avatar asked Sep 27 '13 02:09

PPShein


People also ask

What are the return value of onStartCommand () in Android services?

onStartCommand() is equivalent to returning START_STICKY . If you don't want the default behavior you can return another constant.

How do you get a response from an activity in Android?

startActivityForResult(Intent intent,int requestCode) will give the response from second activity to first activity as a result.

How send data from service to activity in Android?

class MainActivity : AppCompatActivity() { private val sb = object :SerToBroad(){ override fun broadcastResult(connected: String?) { t(connected) } } override fun onCreate(savedInstanceState: Bundle?) { super. onCreate(savedInstanceState) setContentView(R. layout. activity_main) } fun t(connected: String?) { Toast.

What is the difference between activity and service in Android?

Services are a unique component in Android that allows an application to run in the background to execute long-running operation activities, on the other hand, an activity, like a window or a frame in Java, represents a single screen with a user interface.


2 Answers

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

like image 68
J Jiang Avatar answered Oct 10 '22 12:10

J Jiang


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;
            }
        };
like image 1
Srikanth Roopa Avatar answered Oct 10 '22 12:10

Srikanth Roopa