【问题标题】:Android Pass String form Service to Service?And use at onCreate in Service?Android将String形式的Service传递给Service?并在Service的onCreate中使用?
【发布时间】:2017-11-23 05:50:49
【问题描述】:

我有两个服务。所以在这里我将字符串从一个服务传递到另一个服务

这里我用This来传递字符串值..

startService(new Intent(Service_A.this, Service_A.class).putExtra("svdata", url));

这个接收字符串

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    MyURL = intent.getExtras().getString("svdata");

    System.out.print("@@@@@@@@@@@@@@@@@@@@@@@@@"+MyURL+"$$$$$$$$$$$$$$$$$");

    return START_STICKY;
}

在 onCreate 中,我正在使用该 URL 开始我的网络服务

但网址不见了,

@Override
public void onCreate() {
   try{
       new MyWebService(ServWeb.this).execute();
   }
   catch(Exception e){
       Toast.makeText(getApplicationContext(), "Failed to Connect Server", Toast.LENGTH_LONG).show();
   }

}

我正在使用MyWebService() 来获取带有该 URL 的 json 数据。

但是 URL 是 wokring 和 String 在获取。确切的 url 值,但在此之前 onCreate() 方法正在运行

但是我已经把字符串给onStartCommand()

谁能建议我如何将字符串设置为我的服务的 URL。 或如何将字符串直接添加到 onCreate。 服务中

更新

我的问题是.. 我在onCreate 开始服务我有一个 Json 服务,它将从 url 获取 json。但我从另一个服务中得到String(url)

将字符串形式的服务传递给我使用的服务 startService(new Intent(Service_A.this, Service_A.class).putExtra("svdata", url));

但要接收该字符串,我需要写 onStartCommand..

我在这里获取字符串,但我想在 onCreate 中使用相同的字符串...

有什么方法可以在 onCreate...IN SERVICE 中获取该字符串

【问题讨论】:

  • onCreate 只会被调用一次。所以最好在启动服务之前获得价值。
  • 你能不能更新一下答案...跨度>

标签: java android string service


【解决方案1】:

编写一个 SyncManager(单例类)来处理您的服务工作。

在您的 oncreate 方法中: 提供同步凭据,如 url、用户信息等。

 public class SyncService extends IntentService {

     SyncManager syncManager;

     /**
      * Creates an IntentService.  Invoked by your subclass's constructor.
      *
      * @param name Used to name the worker thread, important only for debugging.
      */

     public SyncService(String name) {
      super(name);
     }

     public SyncService() {
      super("SyncService");
     }

     @Override
     protected void onHandleIntent(Intent intent) {
       syncManager = SyncManager.getInstance(getApplicationContext());
       syncManager.startSynchronisation();
      }
      /* The service is starting, due to a call to startService() */
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
      return super.onStartCommand(intent, flags, startId);
     }


     @Override
     public void onDestroy() {
      super.onDestroy();
     }

    }

【讨论】:

  • 但是我想在onCreate中使用字符串..因为我在onCreate上运行我的json服务...这里的问题是在启动服务之后-->Oncrete---> onstart command(String ...)....但我想要 Sting--->oncreate..
  • 你应该以更好的方式更新你的问题。
猜你喜欢
  • 2019-01-28
  • 2012-04-14
  • 2012-12-30
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多