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



在自己的服务中,我想意向性地发送数据,但我从"活动"中得到了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来解决问题。

我认为发生此错误是因为您的数据是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 );
}

试试这种方法,希望这能帮助你解决问题

未读为int,则:

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

未读为字符串,则:

getIntent().getStringExtra("data");

使用这个来"放置"

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");
}

最新更新