我試圖從活動傳遞意圖信息到服務,但它不起作用。從活動傳遞意圖到服務失敗
在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過程中「丟失」。 如何解決這個問題?
謝謝
克里斯
intent.getBundleExtra(「宋史」)被定義爲返回式捆綁,而不是字符串 的東西我使用錯誤/棄用的API? 你在使用什麼API? – ChrisPeeters 2014-11-09 00:35:20