6

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

3 回答 3

5

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

您可以通过以下方式在要“返回 retvalue”的位置发送广播:

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

您可以阅读本教程以了解有关在 android 中广播的更多信息。

编辑 修改示例代码并将其设置为文本视图

于 2013-09-27T03:14:19.630 回答
1

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

您的服务:

  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;
            }
        };
于 2013-09-27T04:33:10.183 回答
0

如果您希望服务与活动进行通信。我们有两种方法。

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

2、你也可以使用bindService来通信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;
    }
}

您可以使用 iBinder 与服务通信

于 2013-09-27T03:40:02.913 回答