Android 将意图从活动传递到服务失败
我试图将意图信息从活动传递到服务,但它不起作用 在startService()之前,我向intent添加了额外的内容。 当执行startService()时,该服务尝试获取额外数据,但指针为null 这是我的密码:Android 将意图从活动传递到服务失败,android,android-intent,android-service,Android,Android Intent,Android Service,我试图将意图信息从活动传递到服务,但它不起作用 在startService()之前,我向intent添加了额外的内容。 当执行startService()时,该服务尝试获取额外数据,但指针为null 这是我的密码: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { final ToggleButton btnPlayStop
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期间“丢失”了一样。
如何解决这个问题
多谢各位
Chris在服务中尝试这些代码
String song=intent.getStringExtra("song");
这是因为您没有在bundle中获取字符串值。 尝试添加额外的。getString(“”)如何使用
String song = intent.getBundleExtra("song");
在声明意图的MainActivity.java中,尝试
Intent intent = new Intent(v.getContext(), MyService.class);
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
*/
}
然后在MyService.java中收到您的意图,尝试
Intent intent = new Intent(v.getContext(), MyService.class);
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
*/
}
我认为你没有正确初始化你的意图,这就是为什么它一直给你这个错误的原因@ChrisPeeters接受答案如果这个代码对你有效,如果不告诉我这里有什么错误intent=getIntent()对我无效-->“方法getIntent()对于类型MyService”intent.getBundleExtra(“歌曲”)定义为返回Bundle而不是String类型的东西。我是否使用了错误/不推荐使用的API?您使用的是什么API?