2014-11-08 28 views
0

我試圖從活動傳遞意圖信息到服務,但它不起作用。從活動傳遞意圖到服務失敗

在startService()之前,我添加了額外的intent。 當執行startService(),該服務將嘗試獲得額外但指針是空

這裏是我的代碼:

public class MainActivity extends Activity 
{ 
@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    final ToggleButton btnPlayStop = (ToggleButton) findViewById(R.id.btnPlayStop); 
    btnPlayStop.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      Intent intent = new Intent(getBaseContext(), MyService.class); 
      intent.putExtra("song", "umake"); 
      /* 
       Debugger displays: 
        intent.mExtras.mMap.table[1] 
         key = "song" 
         value = "umake" 
      */ 

      startService(intent); 
     } 
    } 
} 

public class MyService extends Service 
{ 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    try 
    { 
     Toast.makeText(this, "MyService Started", Toast.LENGTH_LONG).show(); 

     // intent = getIntent();     
     // --> compiler error: The method getIntent() is undefined for the type MyService 

     Bundle extras = intent.getExtras(); 
     String song = extras.getString("song"); // nope 

     song = intent.getStringExtra("song"); // nope 
     Bundle bundle = intent.getBundleExtra("song"); // nope 
     song = bundle.getString("song"); // nope 

     /* 
      Neither of the above works since the map in extras is null 
      Debugger displays: 
       intent.mExtras.mMap == null 

      whereas before startService is was filled all right 
     */ 
    }... 

這是因爲如果數據得到了startService過程中「丟失」。 如何解決這個問題?

謝謝

克里斯

回答

0

服務

String song=intent.getStringExtra("song"); 
0

那是因爲你沒有得到被捆綁的字符串值試試這些代碼。 嘗試添加extras.getString( 「」)

0

有關使用

String song = intent.getBundleExtra("song"); 
+0

intent.getBundleExtra(「宋史」)被定義爲返回式捆綁,而不是字符串 的東西我使用錯誤/棄用的API? 你在使用什麼API? – ChrisPeeters 2014-11-09 00:35:20

0

在你MainActivity.java,在那裏你申報你的意圖如何,試試有

Intent intent = new Intent(v.getContext(), MyService.class); 

然後在接收您的意圖在MyService.java,請嘗試

public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    try 
    { 
     Toast.makeText(this, "MyService Started", Toast.LENGTH_LONG).show(); 
     intent = getIntent(); //Here You Want to make sure you are actually getting values from the previous activity 
     Bundle extras = intent.getExtras(); 
    /* 
     Debugger displays: 
      intent.mExtras.mMap == null 
    */ 
} 

我不認爲你是正確intializing你的意圖,這就是爲什麼它不停地給你的錯誤

+0

@ChrisPeeters如果此代碼爲您工作,請接受答案,如果不告訴我我在這裏有什麼錯誤 – 2014-11-08 21:18:21

+0

intent = getIntent() 對我不起作用 - >「方法getIntent()對於MyService類型未定義「 – ChrisPeeters 2014-11-09 00:37:50