我试图从活动传递意图信息到服务,但它不起作用。从活动传递意图到服务失败
在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