简体   繁体   English

Android服务活动意图

[英]Android Service Activity Intent

I want to pass a string from activiy to service. 我想将字符串从活动传递到服务。

            Bundle mBundle = new Bundle();
            mBundle.putString("MyString", string);
            mIntent.putExtras(mBundle);
            startService(mIntent);

this is in Activity class 这是在Activity类中

            Intent myIntent = getIntent();
            String value = myIntent.getExtras().getString(key);

and this is in Service class It doesn't accept getIntent() method :SI don't know what I'll do 这是在Service类中,它不接受getIntent()方法:SI不知道我该怎么做

服务中的代码必须放在onStart(Intent intent, int startid)方法中,并且代码变为String value = intent.getExtras().getString(key);

使用startService(mIntent)启动服务时,将startService(mIntent)服务的onStartCommand ,这是处理意图的好地方。

Move the part of your code that depends on the intent to onStartCommand: http://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent , int, int) 将取决于意图的代码部分移至onStartCommand: http : //developer.android.com/reference/android/app/Service.html#onStartCommand (android.content.Intent,int,int)

OnStartCommand was called OnStart before api version 5, follow link to documentation for further information about backwards compatibility in your app. 在API版本5之前,OnStartCommand称为OnStart,请访问文档链接,以获取有关应用程序中向后兼容性的更多信息。

@Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      String value = intent.getExtras().getString(key);
  }

Also remember to move heavy code into a background thread that you start in onStartCommand, as otherwise you will run into an Application Not Responding error. 还要记住,将繁重的代码移到以onStartCommand启动的后台线程中,否则会遇到“应用程序无响应”错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM