2

我有一个不扩展 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开始的。但是我怎样才能参考 started MainActivity

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

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

4

1 回答 1

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

    }

}
于 2018-03-08T15:07:55.183 回答