如何从非Activity类启动Activity,并在Activity类中接收onActivityResult()。

huangapple go评论74阅读模式
英文:

How to launch activity from non-activity class and receive the onActivityResult() on the activity class

问题

Fragment class:

public class MyFragment extends Fragment
{
    private static final String TAG = "Example";
    private NonActivityClass nonActivityClass = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        RequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        nonActivityClass = new NonActivityClass(getActivity());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.d(TAG, "ON RESULT");
        if (requestCode == NonActivityClass.REQUEST && resultCode == RESULT_OK)
        {
            Log.d(TAG, "ON RESULT!");
        }
    }
}

Non-activity class:

public class NonActivityClass
{
    private Activity activity;
    static final int REQUEST = 1;

    public NonActivityClass(Activity activity)
    {
        this.activity = activity;
    }
    private Activity getActivity()
    {
        return  this.activity;
    }

    public void DispatchTakePictureIntent()
    {    
        PackageManager packageManager = getActivity().getPackageManager();
        if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
        {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            // Ensure that there's a camera activity to handle the intent
            if (takePictureIntent.resolveActivity(packageManager) != null)
            {
                // Create the File where the photo should go
                File photoFile = null;
                try
                {
                    photoFile = CreateImageFile(); //this method creates the temporary file, shouldn't be relevant
                }
                catch (IOException ex)
                {
                    Log.d(TAG, "Error occurred while creating the File:" + ex.toString());
                }
                // Continue only if the File was successfully created
                if (photoFile != null)
                {
                    Uri photoURI = FileProvider.getUriForFile(getActivity(),
                            "com.example.fileprovider",
                            photoFile);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                    //THIS
                    getActivity().startActivityForResult(takePictureIntent, REQUEST);
                    //
                }
            }
        }
    }
}
英文:

I have one class that extends from fragment, and another class, which is a non-activity class that starts some intents (camera related stuff).

I pass the first one to the constructor on the second one so the second one can perform the creation of intents and start them. But I expect that the onActivityResult gets called on the activity side, the Fragment, but it never gets called. What I'm doing wrong?

Fragment class:

public class MyFragment extends Fragment
{
private static final String TAG = "Example";
private NonActivityClass nonActivityClass = null;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
RequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
nonActivityClass = new NonActivityClass(getActivity());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d(TAG, "ON RESULT");
if (requestCode == NonActivityClass.REQUEST && resultCode == RESULT_OK)
{
Log.d(TAG, "ON RESULT!");
}
}
}

Non-activity class:

public class NonActivityClass
{
private Activity activity;
static final int REQUEST = 1;
public NonActivityClass(Activity activity)
{
this.activity = activity;
}
private Activity getActivity()
{
return  this.activity;
}
public void DispatchTakePictureIntent()
{    
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(packageManager) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = CreateImageFile(); //this method creates the temporary file, shouldn't be relevant
}
catch (IOException ex)
{
Log.d(TAG, "Error occurred while creating the File:" + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null)
{
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
//THIS
getActivity().startActivityForResult(takePictureIntent, REQUEST);
//
}
}
}
}
}

EDIT:
Even following this answer: https://stackoverflow.com/questions/51100518/call-to-startactivityforresult-from-non-activity-class-and-getting-result-in-e

and instead of pasing the activity passing the fragment, it doesn't call onResult.

答案1

得分: 0

以下是您提供的内容的翻译:

在查看我在问题上发布的答案之后,我注意到问题在于我从Activity中调用了startActivityForResult(),而应该从片段(Fragment)中调用。因此,我按照答案中的方法进行了重构,改为在片段中使用。

因此,片段的代码将如下所示:

public class MyFragment extends Fragment {
    private static final String TAG = "Example";
    private NonActivityClass nonActivityClass = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        RequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        nonActivityClass = new NonActivityClass(this); //使用this,而不是getActivity()
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "ON RESULT");
        if (requestCode == NonActivityClass.REQUEST && resultCode == RESULT_OK) {
            Log.d(TAG, "ON RESULT!");
        }
    }
}

非活动类(NonActivityClass)如下:

public class NonActivityClass {
    private Fragment fragment;
    static final int REQUEST = 1;

    public NonActivityClass(Fragment fragment) {
        this.fragment = fragment;
    }

    private Activity getActivity() {
        return this.fragment.getActivity();
    }

    public void DispatchTakePictureIntent() {
        Log.d(TAG, "DISPATCH");

        PackageManager packageManager = getActivity().getPackageManager();
        if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            // 确保有相机活动来处理意图
            if (takePictureIntent.resolveActivity(packageManager) != null) {
                // 创建应存放照片的文件
                File photoFile = null;
                try {
                    photoFile = CreateImageFile(); //此方法创建临时文件,与问题无关
                } catch (IOException ex) {
                    Log.d(TAG, "创建文件时出错:" + ex.toString());
                }
                // 仅在成功创建文件时继续
                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(getActivity(),
                            "com.example.fileprovider",
                            photoFile);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                    // 在此处调用 startActivityForResult 方法
                    fragment.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
                    //
                }
            }
        }
    }
}
英文:

Looking close to the answer that I post on my question: https://stackoverflow.com/questions/51100518/call-to-startactivityforresult-from-non-activity-class-and-getting-result-in-e

I've noticed that the problem is that I was calling startActivityForResult() from Activity, and should be called from the fragment. So instead passing Activity to my class, I refractored like the answer to use Fragment.

So fragment code will look like:

public class MyFragment extends Fragment
{
private static final String TAG = "Example";
private NonActivityClass nonActivityClass = null;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
RequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
nonActivityClass = new NonActivityClass(this); //this, instead of getActivity()
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d(TAG, "ON RESULT");
if (requestCode == NonActivityClass.REQUEST && resultCode == RESULT_OK)
{
Log.d(TAG, "ON RESULT!");
}
}
}

And non-activity class like:

public class NonActivityClass
{
private Fragment fragment;
static final int REQUEST = 1;
public NonActivityClass(Fragment fragment)
{
this.fragment = fragment;
}
private Activity getActivity()
{
return  this.fragment.activity;
}
public void DispatchTakePictureIntent()
{
Log.d(TAG, "DISPATCH");
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(packageManager) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = CreateImageFile(); //this method creates the temporary file, shouldn't be relevant
}
catch (IOException ex)
{
Log.d(TAG, "Error occurred while creating the File:" + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null)
{
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
//THIS
fragment.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
//
}
}
}
}
}

huangapple
  • 本文由 发表于 2020年8月21日 00:14:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63509173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定