【发布时间】:2014-11-08 16:29:22
【问题描述】:
我正在尝试将意图信息从 Activity 传递给 Service,但它不起作用。
在 startService() 之前,我在意图中添加了额外内容。 执行 startService() 时,服务尝试获取 extras 但指针为空
这是我的代码:
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
*/
}...
就好像数据在启动服务期间“丢失”了一样。 如何解决?
谢谢
克里斯
【问题讨论】:
标签: android android-intent android-service