2014-11-08 64 views
0

我试图从活动传递意图信息到服务,但它不起作用。从活动传递意图到服务失败

在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

服务

String song=intent.getStringExtra("song"); 
0

那是因为你没有得到被捆绑的字符串值试试这些代码。 尝试添加extras.getString( “”)

0

有关使用

String song = intent.getBundleExtra("song"); 
+0

intent.getBundleExtra(“宋史”)被定义为返回式捆绑,而不是字符串 的东西我使用错误/弃用的API? 你在使用什么API? – ChrisPeeters 2014-11-09 00:35:20

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 
    */ 
} 

我不认为你是正确intializing你的意图,这就是为什么它不停地给你的错误

+0

@ChrisPeeters如果此代码为您工作,请接受答案,如果不告诉我我在这里有什么错误 – 2014-11-08 21:18:21

+0

intent = getIntent() 对我不起作用 - >“方法getIntent()对于MyService类型未定义“ – ChrisPeeters 2014-11-09 00:37:50