android - Activity 在 Intent 中找不到 Bundle

标签 android android-intent bundle intentservice

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

下面的代码输出:

I/System.out: It's null

主要 Activity :

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

}

Intent 服务:

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

最佳答案

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

更改:

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

致:

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

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

关于android - Activity 在 Intent 中找不到 Bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33554073/

相关文章:

android - 在 Android 中使用 Shared ViewModel 在不同 ViewModel 之间共享数据

java - 如何下载较旧的 google play 服务?

java - 由于 Intent,Action Bar 没有显示?

java - (Android)通过intent传递多维数组

安卓 : How to make Popup Menu to have same width as its anchor?

java - 在android中获取当前位置(坐标)?

android - 从主要 Activity (按钮)启动 map View

java -/AndroidRuntime 致命异常 : main 03-25 11:50:16. 455

ruby - 修复 "Nokogiri failed to build gem native extension"

android - 我如何获得 Android Bundle/Packager Identifier