如何从android服务获取返回值

时间:2013-09-27 02:59:06

标签: android service

我遇到的问题是我不知道如何从服务中获取返回值。为什么我想从服务返回值是我想在活动页面中显示此返回值。以下是我的服务文件,返回值为 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();
    }    
}

3 个答案:

答案 0 :(得分:3)

据我所知,服务与活动沟通的常用方式是 BROADCAST

您可以通过以下内容发送您想要“返回重估价值”的位置的广播:

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

ServiceReturnIntent和“retvalue”都是自定义字符串,用于标识广播和值名称。

在您希望获得返回值的活动中,您应该有一个广播接收器,例如:

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 
         ......
    }
}

您可以阅读this tutorial了解有关Android广播的更多信息。

修改 修改示例代码并将其设置为textview

答案 1 :(得分:1)

您可以将服务绑定到活动:link

您的服务:

  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;
  }

}

在Activity中检查值:

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 :(得分:0)

如果您希望服务与activity.in有两种方法。

1,您可以使用 BROADCAST 。您可以在服务中发送BROADCAST并在活动中使用BroadcastReceiver。

2,您还可以使用bindService来交流活动。

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;
    }
}

您可以使用iBinder与服务进行通信