我正在尝试将意图信息从活动传递到服务但它不起作用。
在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 :(得分:0)
在服务中试用这些代码
String song=intent.getStringExtra("song");
答案 1 :(得分:0)
这是因为你没有在捆绑中获得字符串值。 尝试添加extras.getString("")
答案 2 :(得分:0)
如何使用
String song = intent.getBundleExtra("song");
答案 3 :(得分: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
*/
}
我认为你没有正确地表达你的意图,这就是为什么它一直给你这个错误