gpt4 book ai didi

android - 在我的案例中关闭已开始的 Activity

转载 作者:搜寻专家 更新时间:2023-11-01 09:28:33 26 4
gpt4 key购买 nike

我有一个不扩展 Activity 或 Fragment 的类。它是一个独立的类。我想使用该类来控制 Activity 的开始和结束。

public class MyActivityManager() {
public MyActivityManager(Context context) {
mContext = context;
}

public void startMainActivity() {
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}

public void closeMainActivity() {
// how can I close the started main activity from the other function here?
}

}

如您所见,我从一个函数启动了 MainActivity,在另一个函数中,我想关闭启动的 MainActivity。但是我怎样才能引用已启动的 MainActivity

(我的主要目的是让上层调用者使用这个MyActivityManager来启动和关闭MainActivity)

如果目前的方式不行,如何实现我想要的?

最佳答案

    //Try the below code and let me know if any issues.


package com.example.raghavendrapai.myapplication;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mCloseReceiver, new IntentFilter("close_main_activity"));
}

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mCloseReceiver);
}

private BroadcastReceiver mCloseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("close_main_activity")) {
finish();
}
}
};

}


// And in your class
package com.example.raghavendrapai.myapplication;

import android.content.Context;
import android.content.Intent;

/**
* Created by raghavendra.pai on 08/03/18.
*/

public class MyActivityManager {
private Context mContext;

public MyActivityManager(Context context) {
mContext = context;
}

public void startMainActivity() {
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}

public void closeMainActivity() {
Intent intent = new Intent("close_main_activity");
mContext.sendBroadcast(intent);

}

}

关于android - 在我的案例中关闭已开始的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49176086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com