簡體   English   中英

Android服務活動意圖

[英]Android Service Activity Intent

我想將字符串從活動傳遞到服務。

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

這是在Activity類中

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

這是在Service類中,它不接受getIntent()方法:SI不知道我該怎么做

服務中的代碼必須放在onStart(Intent intent, int startid)方法中,並且代碼變為String value = intent.getExtras().getString(key);

使用startService(mIntent)啟動服務時,將startService(mIntent)服務的onStartCommand ,這是處理意圖的好地方。

將取決於意圖的代碼部分移至onStartCommand: http : //developer.android.com/reference/android/app/Service.html#onStartCommand (android.content.Intent,int,int)

在API版本5之前,OnStartCommand稱為OnStart,請訪問文檔鏈接,以獲取有關應用程序中向后兼容性的更多信息。

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

還要記住,將繁重的代碼移到以onStartCommand啟動的后台線程中,否則會遇到“應用程序無響應”錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM