我有一个不扩展活动或片段的课程。这是一个独立的阶级。我想使用该类来控制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
)
如果目前的方式无法实现,如何实现我的目标?
答案 0 :(得分:2)
//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);
}
}