Android使用putExtra在活动中获取在SERVICE中发送的NULL数据

时间:2014-11-05 08:26:52

标签: android android-intent

在自己的服务中我想发送有意图的数据,但我从Activity中获取null。我已阅读有关此解决方案的文档,但我无法解决问题。

服务:

    public void notifyTest(int unread){
        Intent i = new Intent();
        i.setClass(this, YourDialog.class);
        i.putExtra("data", unread);
        i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity ( i );
    }

从活动中获取数据:

    Intent intent = getIntent ();
    String count = intent.getStringExtra("data");

我无法使用BroadCostReceiver来解决问题。

3 个答案:

答案 0 :(得分:2)

我认为发生此错误的原因是您的数据为int,但您希望将其作为String收到。

尝试改变它:

public void notifyTest(int unread){
    Intent i = new Intent();
    i.setClass(this, YourDialog.class);
    i.putExtra("data", unread + ""); //convert to STRING
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity ( i );
}

答案 1 :(得分:0)

用它来“放”

Intent i = new Intent(FirstScreen.this, SecondScreen.class);   

String keyIdentifer = null; i.putExtra(“STRING_I_NEED”,strName);

然后,要检索值,请尝试以下内容:

String newString;
if (savedInstanceState == null) {
    extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("STRING_I_NEED");
    }
} else {
    newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

答案 2 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

未读是int:

getIntent().getIntExtra("data",0);

未读是字符串然后:

getIntent().getStringExtra("data");