通过 LocalBroadcastManager 调用片段中的方法

Invoking a method in a fragment through a LocalBroadcastManager

我正在构建一个包含 2 个片段的应用程序。

在第二个片段中,我有一个 "Save" 按钮。在这个按钮的 onClick 中,我正在 尝试 发送本地广播:

btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                localBroadcastManager.sendBroadcast(localIntent);
            }
        });

这是我的意图:

 final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager
                .getInstance(Objects.requireNonNull(getContext()));

        final Intent localIntent = new Intent("CUSTOM_ACTION");

这样做的目的是让第一个片段拾取它并执行一种方法,将图像保存为带有标题的位图(这就是 2 个 TextView 的用途)。这是我的尝试:

private BroadcastReceiver listener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent ) {
            String data = intent.getStringExtra("DATA");
            Toast.makeText(context, data + " received", Toast.LENGTH_SHORT).show();

            createAndSaveBitmap(topTextView.getText().toString(), bottomTextView.getText().toString(), memeBitmap, memeCanvas, memePaint, imageView, imageUri);
        }
    };

    public void createAndSaveBitmap(String top, String bottom, Bitmap bitmap,
                                    Canvas canvas, Paint paint, ImageView imageView, Uri imageUri) {

        try {
            memeBitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri))
                    .copy(Bitmap.Config.ARGB_8888, true); }

        catch (FileNotFoundException e) { e.printStackTrace(); }

        canvas = new Canvas(memeBitmap);

        paint = new Paint();

        canvas.drawText(top, 0, 0, paint);
        canvas.drawText(bottom, 0, memeCanvas.getHeight() - 10, paint);

        imageView.setImageBitmap(memeBitmap);

        if(bitmap != null){
            File file = Environment.getExternalStorageDirectory();
            File newFile = new File(file, "test.jpg");

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(newFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            }

            catch (FileNotFoundException e) {e.printStackTrace();}
            catch (IOException e) { e.printStackTrace(); }
        }
    }

当我 运行 应用程序时,单击 "Save" 按钮时没有任何反应。不下载图像,也不会崩溃。由于没有错误堆栈跟踪,我看不出哪里出错了。

确保您在接收片段的 onResume 中调用它。

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
        listener, 
        new IntentFilter("CUSTOM_ACTION")
);

这在 onPause

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(listener);