简体   繁体   中英

Android structure: Two classes for one activity

I am a newbie in android and I am trying to find a good structure for my application but I am not sure how to do it.

I have one activity and one page only gathering information and doing something with it (Pushing it to the API, Calculations, etc...). But I simply do not want to put everything inside the MainActivity.java as it would become a long file with so many functions. So I would like to be able to call these functions from MainActivity.java , and preform them in other classes.

Is there a specific name or way of doing so ? what class would I extend if I create a new one for the same Main Activity to preform the functions being called from there, and keep MainActivity.java short and clean

You can read some knowledge about MVC or MVP. In short, try to separate your UI Module from Logic Module.There was some common ways you can refer:

  1. write your common api to a ***Util.java (with static functions), for example: FileUtil.java is a tool class which handle file manage, you can write
    • public static void saveFile(String path)
    • public static void deleteFile(String path)
    • public static void saveJpeg(String path, Bitmap b)
    • public static void delAllFiles(String folder) and so on.

You can write PreferenceUtil.java to handle android Preference management .

  1. If many activities have the same function, you want to use. Such as: showWaitingDialog() .Then you can write a BaseActivity.java , and realize showWaitingDialog() in it.

  2. Sometimes you need to use SinglePattern to realize your code. For example, you want have a User.java to manage all User things, including login , logout, check whether is login. Determine when to use SinglePattern , if your User.java must be used in many activities, and there must be only one instance in your memory.

Below is an example, LocationManager.java , is written by SinglePattern .In my app, many activities need call location module, and it must be one instance.

public class LocationManager implements AMapLocationListener {
    public interface OnLocationCallback{
        public void onLocateSuccess(double lng, double lat, String addr);
        public void onLocateFail(int code, String info);
    }
    private static volatile LocationManager mInstance = null;
    private Context context;
    public AMapLocationClient mLocationClient = null;
    private OnLocationCallback mCallback;

    private LocationManager(Context context){
        this.context = context;
        init(this.context);
    }

    public static LocationManager getInstance(Context context){
        if(mInstance == null){
            synchronized (LocationManager.class){
                if(mInstance == null){
                    mInstance = new LocationManager(context);
                }
            }
        }
        return mInstance;
    }

    private void init(Context context){
        mLocationClient = new AMapLocationClient(context);
        mLocationClient.setLocationListener(this);
        initLocationParams();

    }
    private void initLocationParams(){
        AMapLocationClientOption mLocationOption = null;
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setWifiActiveScan(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setInterval(2000);
        mLocationClient.setLocationOption(mLocationOption);
    }

    public void startLocation(OnLocationCallback callback){
        this.mCallback = callback;
        mLocationClient.startLocation();
    }
    public void stopLocation(){
        this.mCallback = null;
        mLocationClient.stopLocation();
    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                amapLocation.getLocationType();
                amapLocation.getLatitude();
                amapLocation.getLongitude();
                amapLocation.getAccuracy();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);
                amapLocation.getAddress();
                amapLocation.getCountry();
                amapLocation.getProvince();
                amapLocation.getCity();
                amapLocation.getDistrict();
                amapLocation.getRoad();
                amapLocation.getCityCode();
                amapLocation.getAdCode();

                if(mCallback != null){
                    mCallback.onLocateSuccess(amapLocation.getLongitude(), amapLocation.getLatitude(), amapLocation.getAddress());
                }
            } else {

                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
                if(mCallback != null){
                    mCallback.onLocateFail(amapLocation.getErrorCode(), amapLocation.getErrorInfo());
                }
            }
        }
    }
}

Call it by: LocationManager.getInstance(getApplicationContext()).startLocation(new LocationManager.OnLocationCallback(){})

  1. On some condition, your can write a ***Manager.java class to realize some logic things. As you mentioned Calculations , then you can write CalculationManager implements ICalculationInterface . Below is some example code:

ICalculateInterface.java:

public interface ICalculateInterface {
    int add(int a, int b);
    int sub(int a, int b);
}

CalculateManager.java

public class CalculateManager implements ICalculateInterface {
    @Override
    public int add(int a, int b) {
        return 0;
    }

    @Override
    public int sub(int a, int b) {
        return 0;
    }
}

I would suggest creating Utils class in which you can put all your methods that work with your data.

Example of one Utils class:

public class StringUtils {

  public static boolean isEmpty(String text) {
        return text == null || text.isEmpty() || text.trim().isEmpty();
    }
}

Follow the sane pattern and "outsource" all of the hard work that you can to reusable utils.

Also, if possible, try to use MVP structure for your future own sake.

You may use abstract .

Your base activity.

public abstract class BaseActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activityCreated();
    }

    public abstract void activityCreated();

    protected void myMethod() {}
    protected void myMethod2() {}
    protected void Log(String txt) {}
}

MainActivity

public class MainActivity extends BaseActivity {

    @Override
    public void activityCreated() {
        myMethod2();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM