活动无法在Intent中找到Bundle

时间:2015-11-05 20:23:11

标签: android android-intent bundle intentservice

我正在使用IntentService(第一次),我打算使用Bundle返回此服务的结果。但是,当我这样做时,主要活动找不到Bundle,返回null。什么可能导致这个?字符串键匹配!

下面的代码输出:

I/System.out: It's null

主要活动:

public class MainMenu extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //Some stuff here...

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(StorageHandler.TRANSACTION_DONE);
        registerReceiver(broadcastReceiver, intentFilter);
        Intent i = new Intent(this, StorageHandler.class);
        startService(i);
    }



    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extra = getIntent().getBundleExtra("bundle");

            if(extra == null){
                System.out.println("It's null");
            }
            else {
                ArrayList<String> objects = (ArrayList<String>) extra.getSerializable("objects");
                System.out.println(objects.get(0));
            } 
        }
    };

}

IntentService:

public class StorageHandler extends IntentService{

    public static final String TRANSACTION_DONE = "xx.xxxxx.xxxxxx.TRANSACTION_DONE";

    public StorageHandler() {
        super("StorageHandler");
    }

    public void onCreate(){
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        notifyFinished();
    }

    private void notifyFinished(){
        ArrayList<String> objects = new ArrayList<String>();
        objects.add("Resulting Array here");

        Bundle extra = new Bundle();
        extra.putSerializable("objects", objects);

        Intent i = new Intent();
        i.setAction(xx.xxxxx.xxxxxx.StorageHandler.TRANSACTION_DONE);
        i.putExtra("bundle", extra);

        StorageHandler.this.sendBroadcast(i);
    }

4 个答案:

答案 0 :(得分:1)

您正在使用getIntent()来检索广播的意图。这是错的。你必须使用的意图是onReceive的前一个参数。变化

Bundle extra = getIntent().getBundleExtra("bundle");

Bundle extra = intent.getBundleExtra("bundle");

答案 1 :(得分:1)

您尝试从错误的Intent检索数据。

变化:

Bundle extra = getIntent().getBundleExtra("bundle");

要:

Bundle extra = intent.getBundleExtra("bundle");

包含您数据的Intent作为BroadcastReceiver onReceive()方法的参数之一提供。

答案 2 :(得分:0)

只需在您的活动中使用它:

onResume回调中,您应注册registerReceiver(broadcastReceiver, intentFilter);

onPause回调中你应该取消注册这个接收器。在您的接收器中使用此:

Bundle extra = intent.getBundleExtra("bundle");

在您的服务中使用此代码:

 Intent i = new Intent(TRANSACTION_DONE).putExtra("bundle", extra);
            this.sendBroadcast(i);

更多信息,请参阅This Answer

答案 3 :(得分:0)

请勿在onCreate MainActivity中忘记这一点:

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     //All your code here
 }

我这样说是因为我在你的方法中没有看到该代码行!