diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5134e91c..f3949930 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -19,6 +19,9 @@ android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> + @@ -28,6 +31,7 @@ android:theme="@style/SplashTheme"> + diff --git a/app/src/main/java/com/aof/mcinabox/Launcher.java b/app/src/main/java/com/aof/mcinabox/Launcher.java index 5dabf0bc..32a0f02f 100644 --- a/app/src/main/java/com/aof/mcinabox/Launcher.java +++ b/app/src/main/java/com/aof/mcinabox/Launcher.java @@ -199,7 +199,8 @@ private ArgumentsSubstitutor createArgumentsSubstitutor(Profile profile, Account String path = new File(new File(assetsDirectory, "objects"), hash.substring(0, 2) + "/" + hash).getAbsolutePath(); map.put("asset=" + entry.getKey(), path); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } map.put("launcher_name", "MCinaBox"); map.put("launcher_version", BuildConfig.VERSION_NAME); map.put("natives_directory", nativeDirectory.getAbsolutePath()); diff --git a/app/src/main/java/com/aof/mcinabox/activity/LoginActivity.java b/app/src/main/java/com/aof/mcinabox/activity/LoginActivity.java new file mode 100644 index 00000000..35bba617 --- /dev/null +++ b/app/src/main/java/com/aof/mcinabox/activity/LoginActivity.java @@ -0,0 +1,19 @@ +package com.aof.mcinabox.activity; + +import android.os.Bundle; + +import androidx.appcompat.app.AppCompatActivity; + +import com.aof.mcinabox.databinding.ActivityLoginBinding; + +public class LoginActivity extends AppCompatActivity { + + private ActivityLoginBinding binding; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = ActivityLoginBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/aof/mcinabox/activity/OldMainActivity.java b/app/src/main/java/com/aof/mcinabox/activity/OldMainActivity.java index 7dbdfd3e..b45e9751 100644 --- a/app/src/main/java/com/aof/mcinabox/activity/OldMainActivity.java +++ b/app/src/main/java/com/aof/mcinabox/activity/OldMainActivity.java @@ -36,7 +36,7 @@ public class OldMainActivity extends BaseActivity { public ThemeManager mThemeManager; private ActivityOldMainBinding binding; private static final int REFRESH_DELAY = 0; //ms - private static final int REFRESH_PERIOD = 500; //ms + private static final int REFRESH_PERIOD = 1000; //ms public static SettingJson Setting; private boolean enableSettingChecker = false; diff --git a/app/src/main/java/com/aof/mcinabox/activity/SplashActivity.java b/app/src/main/java/com/aof/mcinabox/activity/SplashActivity.java index 74880456..c16b04bf 100644 --- a/app/src/main/java/com/aof/mcinabox/activity/SplashActivity.java +++ b/app/src/main/java/com/aof/mcinabox/activity/SplashActivity.java @@ -44,9 +44,9 @@ private boolean checkPermissions() { && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED) { return true; } else { - ActivityCompat.requestPermissions(this, new String[] { - Manifest.permission.WRITE_EXTERNAL_STORAGE, - Manifest.permission.READ_EXTERNAL_STORAGE}, + ActivityCompat.requestPermissions(this, new String[]{ + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); return false; } diff --git a/app/src/main/java/com/aof/mcinabox/adapter/SettingsAdapter.java b/app/src/main/java/com/aof/mcinabox/adapter/SettingsAdapter.java new file mode 100644 index 00000000..3f4128e3 --- /dev/null +++ b/app/src/main/java/com/aof/mcinabox/adapter/SettingsAdapter.java @@ -0,0 +1,34 @@ +package com.aof.mcinabox.adapter; + +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; +import androidx.viewpager2.adapter.FragmentStateAdapter; + +import com.aof.mcinabox.fragment.AccountSettingsFragment; +import com.aof.mcinabox.fragment.HomeFragment; + +public class SettingsAdapter extends FragmentStateAdapter { + + public SettingsAdapter(@NonNull Fragment fragment) { + super(fragment); + } + + @NonNull + @Override + public Fragment createFragment(int position) { + switch (position) { + case 0: + return new AccountSettingsFragment(); + case 1: + return new HomeFragment(); + case 2: + return new AccountSettingsFragment(); + } + return null; + } + + @Override + public int getItemCount() { + return 3; + } +} diff --git a/app/src/main/java/com/aof/mcinabox/filechooser/FileChooserDialog.java b/app/src/main/java/com/aof/mcinabox/filechooser/FileChooserDialog.java index 6f957862..e63f5386 100644 --- a/app/src/main/java/com/aof/mcinabox/filechooser/FileChooserDialog.java +++ b/app/src/main/java/com/aof/mcinabox/filechooser/FileChooserDialog.java @@ -42,10 +42,7 @@ private FileChooserDialog(Context context, String title, String startPath, Strin final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context) .setView(binding.getRoot()) .setNegativeButton("Cancel", null); - final String alertDialogTitle; - if (title != null) { - alertDialogTitle = title; - } else { + if (title == null) { title = "Select a file"; if (extension != null) { title += " (" + extension + ")"; diff --git a/app/src/main/java/com/aof/mcinabox/filechooser/model/MarginItemDecoration.java b/app/src/main/java/com/aof/mcinabox/filechooser/model/MarginItemDecoration.java index 02a03677..a49cbf5b 100644 --- a/app/src/main/java/com/aof/mcinabox/filechooser/model/MarginItemDecoration.java +++ b/app/src/main/java/com/aof/mcinabox/filechooser/model/MarginItemDecoration.java @@ -11,6 +11,7 @@ public class MarginItemDecoration extends RecyclerView.ItemDecoration { private static final int px = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 8, Resources.getSystem().getDisplayMetrics()); + @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { int position = parent.getChildLayoutPosition(view); diff --git a/app/src/main/java/com/aof/mcinabox/fragment/AccountSettingsFragment.java b/app/src/main/java/com/aof/mcinabox/fragment/AccountSettingsFragment.java new file mode 100644 index 00000000..c4381f88 --- /dev/null +++ b/app/src/main/java/com/aof/mcinabox/fragment/AccountSettingsFragment.java @@ -0,0 +1,15 @@ +package com.aof.mcinabox.fragment; + +import android.os.Bundle; + +import com.aof.mcinabox.R; + +public class AccountSettingsFragment extends BasePreferenceFragment { + private static final String TAG = "AccountSettingsFragment"; + + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + setPreferencesFromResource(R.xml.account_preferences, rootKey); + } + +} diff --git a/app/src/main/java/com/aof/mcinabox/fragment/BaseFragment.java b/app/src/main/java/com/aof/mcinabox/fragment/BaseFragment.java index 9cd539e4..9471644e 100644 --- a/app/src/main/java/com/aof/mcinabox/fragment/BaseFragment.java +++ b/app/src/main/java/com/aof/mcinabox/fragment/BaseFragment.java @@ -15,6 +15,6 @@ public BaseFragment(int contentLayoutId) { } public MCinaBox getMCinaBox() { - return (MCinaBox) getActivity().getApplication(); + return (MCinaBox) requireActivity().getApplication(); } } diff --git a/app/src/main/java/com/aof/mcinabox/fragment/BasePreferenceFragment.java b/app/src/main/java/com/aof/mcinabox/fragment/BasePreferenceFragment.java new file mode 100644 index 00000000..d1266927 --- /dev/null +++ b/app/src/main/java/com/aof/mcinabox/fragment/BasePreferenceFragment.java @@ -0,0 +1,16 @@ +package com.aof.mcinabox.fragment; + +import androidx.preference.PreferenceFragmentCompat; + +import com.aof.mcinabox.MCinaBox; + +public abstract class BasePreferenceFragment extends PreferenceFragmentCompat { + + public BasePreferenceFragment() { + super(); + } + + public MCinaBox getMCinaBox() { + return (MCinaBox) getActivity().getApplication(); + } +} diff --git a/app/src/main/java/com/aof/mcinabox/fragment/HomeFragment.java b/app/src/main/java/com/aof/mcinabox/fragment/HomeFragment.java index a4e0999c..559b39ac 100644 --- a/app/src/main/java/com/aof/mcinabox/fragment/HomeFragment.java +++ b/app/src/main/java/com/aof/mcinabox/fragment/HomeFragment.java @@ -19,7 +19,7 @@ import java.util.List; -public class HomeFragment extends BaseFragment implements VersionsManager.OnVersionsChangedListener, AccountsManager.OnAccountsChangedListener { +public class HomeFragment extends BaseFragment { private FragmentHomeBinding binding; private VersionAdapter versionAdapter; @@ -36,36 +36,48 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - binding.settingsButton.setOnClickListener(v -> { - Navigation.findNavController(v).navigate(HomeFragmentDirections.actionHomeFragmentToSettingsFragment()); - }); + binding.settingsButton.setOnClickListener(this::handleSettings); + binding.loginButton.setOnClickListener(this::handleLogin); final VersionsManager versionsManager = getMCinaBox().getVersionsManager(); versionAdapter = new VersionAdapter(getMCinaBox(), versionsManager.getProfiles()); - versionsManager.addOnVersionsChangedListener(this); + versionsManager.addOnVersionsChangedListener(versionsChangedListener); final AccountsManager accountsManager = getMCinaBox().getAccountsManager(); accountAdapter = new AccountAdapter(getMCinaBox(), accountsManager.getAccounts()); - accountsManager.addOnAccountsChangedListener(this); + accountsManager.addOnAccountsChangedListener(accountsChangedListener); binding.bottomBar.versionSpinner.setAdapter(versionAdapter); binding.bottomBar.accountSpinner.setAdapter(accountAdapter); } - @Override - public void onDestroyView() { - getMCinaBox().getVersionsManager().removeOnVersionsChangedListener(this); - getMCinaBox().getAccountsManager().removeOnAccountsChangedListener(this); - super.onDestroyView(); + private void handleSettings(View v) { + Navigation.findNavController(v) + .navigate(HomeFragmentDirections.actionHomeFragmentToSettingsFragment()); } - @Override - public void onVersionsChanged(List profiles) { - versionAdapter.notifyDataSetChanged(); + private void handleLogin(View v) { + } @Override - public void onAccountsChanged(List accounts) { - accountAdapter.notifyDataSetChanged(); + public void onDestroyView() { + getMCinaBox().getVersionsManager().removeOnVersionsChangedListener(versionsChangedListener); + getMCinaBox().getAccountsManager().removeOnAccountsChangedListener(accountsChangedListener); + super.onDestroyView(); } + + private final VersionsManager.OnVersionsChangedListener versionsChangedListener = new VersionsManager.OnVersionsChangedListener() { + @Override + public void onVersionsChanged(List profiles) { + versionAdapter.notifyDataSetChanged(); + } + }; + + private final AccountsManager.OnAccountsChangedListener accountsChangedListener = new AccountsManager.OnAccountsChangedListener() { + @Override + public void onAccountsChanged(List accounts) { + accountAdapter.notifyDataSetChanged(); + } + }; } diff --git a/app/src/main/java/com/aof/mcinabox/fragment/SettingsFragment.java b/app/src/main/java/com/aof/mcinabox/fragment/SettingsFragment.java index 416d5845..c6784fca 100644 --- a/app/src/main/java/com/aof/mcinabox/fragment/SettingsFragment.java +++ b/app/src/main/java/com/aof/mcinabox/fragment/SettingsFragment.java @@ -8,7 +8,9 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.aof.mcinabox.adapter.SettingsAdapter; import com.aof.mcinabox.databinding.FragmentSettingsBinding; +import com.google.android.material.tabs.TabLayoutMediator; public class SettingsFragment extends BaseFragment { @@ -25,5 +27,20 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); + binding.viewPager.setAdapter(new SettingsAdapter(this)); + + new TabLayoutMediator(binding.tabLayout, binding.viewPager, (tab, position) -> { + switch (position) { + case 0: + tab.setText("Tab 1"); + break; + case 1: + tab.setText("Tab 2"); + break; + case 2: + tab.setText("Tab 3"); + break; + } + }).attach(); } } \ No newline at end of file diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/CustomizeKeyboardEditorActivity.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/CustomizeKeyboardEditorActivity.java index ff0414cb..5e09aa80 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/CustomizeKeyboardEditorActivity.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/CustomizeKeyboardEditorActivity.java @@ -41,7 +41,7 @@ public class CustomizeKeyboardEditorActivity extends AppCompatActivity implement private int screenWidth; private int screenHeight; - private int pointer[] = new int[]{0, 0}; + private final int[] pointer = new int[]{0, 0}; private Controller mController; private boolean isGrabbed; private TimerTask systemUiTimerTask; @@ -135,7 +135,7 @@ public void init() { //禁用自定义键盘 this.custmoizeKeyboard.setEnabled(false); //先保存键盘文件 - ((CustomizeKeyboard)this.custmoizeKeyboard).mManager.autoSaveKeyboard(); + ((CustomizeKeyboard) this.custmoizeKeyboard).mManager.autoSaveKeyboard(); //卸载自定义键盘 this.removeInput(custmoizeKeyboard); //重写自定义键盘,并创建新的自定义键盘 diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManager.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManager.java index 4d9c5c27..5d7d9185 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManager.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManager.java @@ -57,7 +57,7 @@ public CkbManager(@NonNull Context context, @NonNull CallCustomizeKeyboard call, init(); } - public int[] getDisplaySize(){ + public int[] getDisplaySize() { return new int[]{displayWidth, displayHeight}; } @@ -193,7 +193,7 @@ public boolean exportKeyboard(String fileName) { return outputFile(kr, fileName); } - public static boolean outputFile(KeyboardRecorder kr, String fileName){ + public static boolean outputFile(KeyboardRecorder kr, String fileName) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); StringBuilder jsonString = new StringBuilder(gson.toJson(kr)); jsonString.insert(0, "/*\n *This file is craeted by MCinaBox\n *Please DON'T edit the file if you don't know how it works.\n*/\n"); @@ -217,7 +217,7 @@ public void autoLoadKeyboard() { loadKeyboard(LAST_KEYBOARD_LAYOUT_NAME + ".json"); } - public boolean loadKeyboard(File file){ + public boolean loadKeyboard(File file) { if (!file.exists()) { return false; } @@ -230,13 +230,13 @@ public boolean loadKeyboard(File file){ } catch (Exception e) { e.printStackTrace(); //当失败时尝试通过加载旧版的按键 - DialogUtils.createBothChoicesDialog(mContext, mContext.getString(R.string.title_note), mContext.getString(R.string.tips_try_to_convert_keyboard_layout), mContext.getString(R.string.title_ok), mContext.getString(R.string.title_cancel), new DialogSupports(){ + DialogUtils.createBothChoicesDialog(mContext, mContext.getString(R.string.title_note), mContext.getString(R.string.tips_try_to_convert_keyboard_layout), mContext.getString(R.string.title_ok), mContext.getString(R.string.title_cancel), new DialogSupports() { @Override public void runWhenPositive() { super.runWhenPositive(); - if(new GameButtonConverter(mContext).output(file)){ + if (new GameButtonConverter(mContext).output(file)) { DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_note), String.format(mContext.getString(R.string.tips_successed_to_convert_keyboard_file), file.getName() + "-new.json"), mContext.getString(R.string.title_ok), null); - }else{ + } else { DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_note), mContext.getString(R.string.tips_failed_to_convert_keyboard_file), mContext.getString(R.string.title_ok), null); } } @@ -252,7 +252,7 @@ public boolean loadKeyboard(String fileName) { return loadKeyboard(file); } - public boolean loadKeyboard(KeyboardRecorder kr){ + public boolean loadKeyboard(KeyboardRecorder kr) { GameButtonRecorder[] gbr; if (kr != null) { gbr = kr.getRecorderDatas(); @@ -260,9 +260,9 @@ public boolean loadKeyboard(KeyboardRecorder kr){ return false; } - switch ( kr.getVersionCode() ){ + switch (kr.getVersionCode()) { case KeyboardRecorder.VERSION_UNKNOWN: - for(GameButtonRecorder tgbr : gbr){ + for (GameButtonRecorder tgbr : gbr) { tgbr.keyPos[0] = DisplayUtils.getDpFromPx(mContext, tgbr.keyPos[0]); tgbr.keyPos[1] = DisplayUtils.getDpFromPx(mContext, tgbr.keyPos[1]); } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManagerDialog.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManagerDialog.java index 4e921a83..fc22d35e 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManagerDialog.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/CkbManagerDialog.java @@ -4,7 +4,6 @@ import android.content.Context; import android.content.DialogInterface; import android.os.FileObserver; -import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; @@ -92,11 +91,7 @@ private void initUI() { */ //当进入游戏的时候自动设定客制化键盘模式为生效,如果是编辑界面,则不自动设置 - if (mManager.getController() != null) { - radioGame.setChecked(true); - }else { - radioGame.setChecked(false); - } + radioGame.setChecked(mManager.getController() != null); } @@ -217,8 +212,8 @@ public void runWhenPositive() { }); } - if(v == buttonDefault){ - DialogUtils.createBothChoicesDialog(mContext, mContext.getString(R.string.title_warn),"您确定要使用默认键盘布局吗?", mContext.getString(R.string.title_ok), mContext.getString(R.string.title_cancel), new DialogSupports(){ + if (v == buttonDefault) { + DialogUtils.createBothChoicesDialog(mContext, mContext.getString(R.string.title_warn), "您确定要使用默认键盘布局吗?", mContext.getString(R.string.title_ok), mContext.getString(R.string.title_cancel), new DialogSupports() { @Override public void runWhenPositive() { super.runWhenPositive(); diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/GameButtonDialog.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/GameButtonDialog.java index 3ed1a2ce..354c79ff 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/GameButtonDialog.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/achieve/GameButtonDialog.java @@ -413,10 +413,10 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } } - if(buttonView == switchChars){ - if(isChecked){ + if (buttonView == switchChars) { + if (isChecked) { editChars.setVisibility(View.VISIBLE); - }else{ + } else { editChars.setVisibility(View.INVISIBLE); } mGameButton.setInputChars(isChecked); diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButton.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButton.java index 4f79c127..3c0dbd68 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButton.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButton.java @@ -146,7 +146,7 @@ private void initAttribute() { this.setTextSize(DEFAULT_TEXT_SIZE_SP); String[] strs = new String[MAX_KEYMAP_SIZE]; - Arrays.fill(strs,""); + Arrays.fill(strs, ""); this.setKeyMaps(strs); this.setKeyTypes(new int[]{KEY_TYPE, KEY_TYPE, KEY_TYPE, KEY_TYPE}); @@ -165,25 +165,25 @@ private void initAttribute() { } - public GameButton setInputChars(boolean b){ + public GameButton setInputChars(boolean b) { this.isChars = b; return this; } - public boolean isInputChars(){ + public boolean isInputChars() { return this.isChars; } - public boolean setChars(String chars){ - if (chars != null){ + public boolean setChars(String chars) { + if (chars != null) { this.keyChars = chars; return true; - }else{ + } else { return false; } } - public String getChars(){ + public String getChars() { return this.keyChars; } @@ -267,8 +267,8 @@ public float[] setKeyPos(float x, float y) { float rx, ry; //Clamp between two extremes - rx = clamp(xPx,0f,(float)(screenWidth - viewWidth)); - ry = clamp(yPx,0f,(float)(screenHeight - viewHeight)); + rx = clamp(xPx, 0f, (float) (screenWidth - viewWidth)); + ry = clamp(yPx, 0f, (float) (screenHeight - viewHeight)); this.setX(rx); this.setY(ry); @@ -432,7 +432,7 @@ private void inputPointerEvent(MotionEvent e) { initialY = (int) e.getY(); break; case MotionEvent.ACTION_MOVE: - mController.sendKey(new BaseKeyEvent(TAG, null, false, MOUSE_POINTER_INC, new int[]{(int) (e.getX() - initialX), (int)(e.getY() - initialY)})); + mController.sendKey(new BaseKeyEvent(TAG, null, false, MOUSE_POINTER_INC, new int[]{(int) (e.getX() - initialX), (int) (e.getY() - initialY)})); initialX = (int) e.getX(); initialY = (int) e.getY(); break; @@ -475,7 +475,7 @@ private void inputKeyEvent(MotionEvent e) { } else { isBeingPressed = true; } - } else if(isChars) { + } else if (isChars) { mController.typeWords(convertStringWithASCII(this.keyChars)); } else { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { @@ -490,8 +490,8 @@ private void inputKeyEvent(MotionEvent e) { } } - private String convertStringWithASCII(String str){ - if(str == null) return null; + private String convertStringWithASCII(String str) { + if (str == null) return null; return StringEscapeUtils.unescapeJava(str); } @@ -512,8 +512,8 @@ private void editView(MotionEvent e) { //int lastPosX = DisplayUtils.getPxFromDp(mContext, getKeyPos()[0]); //int lastPosY = DisplayUtils.getPxFromDp(mContext, getKeyPos()[1]); //直接读入px的数值,而不是通过DisplayUtils进行转换,也许可以更精确 - int lastPosX = (int)this.getX(); - int lastPosY = (int)this.getY(); + int lastPosX = (int) this.getX(); + int lastPosY = (int) this.getY(); int dx = tmpTouchPosX - touchPosX; int dy = tmpTouchPosY - touchPosY; int viewWidth = getLayoutParams().width; diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButtonOld.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButtonOld.java index 4a6c4178..d45fd4fa 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButtonOld.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButtonOld.java @@ -19,7 +19,7 @@ public class GameButtonOld { private String TextColorHex; private int cornerRadius; - public GameButtonOld(){ + public GameButtonOld() { super(); } @@ -43,17 +43,29 @@ public GameButtonOld(String keyName, int keySizeW, int keySizeH, float keyLX, fl cornerRadius = radius; } - public int getKeySizeH() { return KeySizeH; } + public int getKeySizeH() { + return KeySizeH; + } - public void setKeySizeH(int keySizeH) { KeySizeH = keySizeH; } + public void setKeySizeH(int keySizeH) { + KeySizeH = keySizeH; + } - public String getTextColorHex() { return TextColorHex; } + public String getTextColorHex() { + return TextColorHex; + } - public void setTextColorHex(String textColorHex) { TextColorHex = textColorHex; } + public void setTextColorHex(String textColorHex) { + TextColorHex = textColorHex; + } - public int getCornerRadius() { return cornerRadius; } + public int getCornerRadius() { + return cornerRadius; + } - public void setCornerRadius(int cornerRadius) { this.cornerRadius = cornerRadius; } + public void setCornerRadius(int cornerRadius) { + this.cornerRadius = cornerRadius; + } public String getKeyName() { return KeyName; @@ -159,7 +171,11 @@ public void setSpecialTwoPos(int specialTwoPos) { SpecialTwoPos = specialTwoPos; } - public String getColorhex() { return colorhex; } + public String getColorhex() { + return colorhex; + } - public void setColorhex(String colorhex) { this.colorhex = colorhex; } + public void setColorhex(String colorhex) { + this.colorhex = colorhex; + } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/CustomizeKeyboardMaker.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/CustomizeKeyboardMaker.java index 0e6f82d0..7e965d09 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/CustomizeKeyboardMaker.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/CustomizeKeyboardMaker.java @@ -14,7 +14,7 @@ public class CustomizeKeyboardMaker { - private Context mContext; + private final Context mContext; public CustomizeKeyboardMaker(Context context) { this.mContext = context; @@ -31,7 +31,7 @@ public KeyboardRecorder createDefaultKeyboard() { //添加默认按键 defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(5,5,0,0) + .setMargin(5, 5, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_ESC) .setKeyTypes(KEYBOARD_BUTTON) .setTheme() @@ -39,7 +39,7 @@ public KeyboardRecorder createDefaultKeyboard() { .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(60,5,0,0) + .setMargin(60, 5, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_F3) .setKeyTypes(KEYBOARD_BUTTON) .setTheme() @@ -47,23 +47,23 @@ public KeyboardRecorder createDefaultKeyboard() { .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(115,5,0,0) + .setMargin(115, 5, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_T) .setKeyTypes(KEYBOARD_BUTTON) .setTheme() - .setAttribute("T",false,false,GameButton.SHOW_IN_GAME) + .setAttribute("T", false, false, GameButton.SHOW_IN_GAME) .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(170,5,0,0) + .setMargin(170, 5, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_Q) .setKeyTypes(KEYBOARD_BUTTON) .setTheme() - .setAttribute("Q",false,false,GameButton.SHOW_IN_GAME) + .setAttribute("Q", false, false, GameButton.SHOW_IN_GAME) .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(170,0,0,5) + .setMargin(170, 0, 0, 5) .setKeyMap(KeyMap.KEYMAP_KEY_E) .setKeyTypes(KEYBOARD_BUTTON) .setTheme() @@ -71,15 +71,15 @@ public KeyboardRecorder createDefaultKeyboard() { .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(0,180,130,0) + .setMargin(0, 180, 130, 0) .setKeyMap(KeyMap.KEYMAP_KEY_SPACE) .setKeyTypes(KEYBOARD_BUTTON) - .setTheme(2,4,15,70,"#FFFFFF","#FFFFFF") + .setTheme(2, 4, 15, 70, "#FFFFFF", "#FFFFFF") .setAttribute("SPACE") .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(0,180,185,0) + .setMargin(0, 180, 185, 0) .setKeyMap(MouseMap.MOUSEMAP_BUTTON_LEFT) .setKeyTypes(MOUSE_BUTTON) .setTheme() @@ -87,7 +87,7 @@ public KeyboardRecorder createDefaultKeyboard() { .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(0,180,75,0) + .setMargin(0, 180, 75, 0) .setKeyMap(MouseMap.MOUSEMAP_BUTTON_RIGHT) .setKeyTypes(MOUSE_BUTTON) .setTheme() @@ -95,31 +95,31 @@ public KeyboardRecorder createDefaultKeyboard() { .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(0,125,130,0) + .setMargin(0, 125, 130, 0) .setKeyMap(MouseMap.MOUSEMAP_WHEEL_UP) .setKeyTypes(MOUSE_BUTTON) - .setTheme(2,2,15,70,"#FFFFFF","#FFFFFF") + .setTheme(2, 2, 15, 70, "#FFFFFF", "#FFFFFF") .setAttribute("WHEELP.UP") .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(0,235,130,0) + .setMargin(0, 235, 130, 0) .setKeyMap(MouseMap.MOUSEMAP_WHEEL_DOWN) .setKeyTypes(MOUSE_BUTTON) - .setTheme(2,2,15,70,"#FFFFFF","#FFFFFF") + .setTheme(2, 2, 15, 70, "#FFFFFF", "#FFFFFF") .setAttribute("WHEELP.DOWN") .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(225,5,0,0) + .setMargin(225, 5, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_ENTER) .setKeyTypes(KEYBOARD_BUTTON) - .setTheme(2,4,15,70,"#FFFFFF","#FFFFFF") + .setTheme(2, 4, 15, 70, "#FFFFFF", "#FFFFFF") .setAttribute("ENTER") .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(5,60,0,0) + .setMargin(5, 60, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_TAB) .setKeyTypes(KEYBOARD_BUTTON) .setTheme() @@ -127,11 +127,11 @@ public KeyboardRecorder createDefaultKeyboard() { .build()); defGBRs.add(new GameButtonBuilder(mContext) .setSize() - .setMargin(60,60,0,0) + .setMargin(60, 60, 0, 0) .setKeyMap(KeyMap.KEYMAP_KEY_W, MouseMap.MOUSEMAP_BUTTON_LEFT) .setKeyTypes(KEYBOARD_BUTTON, MOUSE_BUTTON) - .setTheme(2,4,15,70,"#FFFFFF","#FFFFFF") - .setAttribute("CRAZY", true,false,GameButton.SHOW_IN_GAME) + .setTheme(2, 4, 15, 70, "#FFFFFF", "#FFFFFF") + .setAttribute("CRAZY", true, false, GameButton.SHOW_IN_GAME) .build()); defKR.setRecorderDatas(defGBRs.toArray(new GameButtonRecorder[0])); return defKR; @@ -160,10 +160,10 @@ public GameButtonBuilder setMargin(int leftDp, int topDp, int rightDp, int botto resultLeft = (int) (sizeDp[0] - gbr.keySize[0] - rightDp); } - if(topDp != 0){ + if (topDp != 0) { resultTop = topDp; - } else if(bottomDp != 0){ - resultTop = (int)(sizeDp[1] - gbr.keySize[1] - bottomDp); + } else if (bottomDp != 0) { + resultTop = (int) (sizeDp[1] - gbr.keySize[1] - bottomDp); } gbr.keyPos = new float[]{resultLeft, resultTop}; @@ -231,7 +231,7 @@ public GameButtonBuilder setAttribute(String keyName) { return setAttribute(keyName, false, false, GameButton.SHOW_ALL); } - public GameButtonBuilder setShow(int show){ + public GameButtonBuilder setShow(int show) { gbr.show = show; return this; } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/GameButtonConverter.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/GameButtonConverter.java index e11cb3f8..16017614 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/GameButtonConverter.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/GameButtonConverter.java @@ -24,29 +24,29 @@ public class GameButtonConverter { private final Context mContext; private final static String TAG = "GameButtonConverter"; - public GameButtonConverter(Context context){ + public GameButtonConverter(Context context) { this.mContext = context; } - public boolean output(File file){ + public boolean output(File file) { StringBuilder fileName = new StringBuilder(); - for(int i = 0; i < file.getName().length() - 5; i++){ + for (int i = 0; i < file.getName().length() - 5; i++) { fileName.append(file.getName().charAt(i)); } try { CkbManager.outputFile(getNewKeyboardFromOldKeyboard(getOldKeyboardFormJson(file)), fileName.toString() + "-new"); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); return false; } return true; } - public GameButtonOld[] getOldKeyboardFormJson(File file){ + public GameButtonOld[] getOldKeyboardFormJson(File file) { InputStream inputStream; Gson gson = new Gson(); File jsonFile = file; - if(!jsonFile.exists()){ + if (!jsonFile.exists()) { return null; } try { @@ -54,9 +54,9 @@ public GameButtonOld[] getOldKeyboardFormJson(File file){ Reader reader = new InputStreamReader(inputStream); GameButtonOld[] jsonArray = new Gson().fromJson(reader, GameButtonOld[].class); List tempList1 = Arrays.asList(jsonArray); - if(tempList1.size() != 0){ + if (tempList1.size() != 0) { return (GameButtonOld[]) tempList1.toArray(); - }else{ + } else { return new GameButtonOld[]{}; } } catch (FileNotFoundException e) { @@ -65,10 +65,10 @@ public GameButtonOld[] getOldKeyboardFormJson(File file){ } } - public KeyboardRecorder getNewKeyboardFromOldKeyboard(GameButtonOld[] gbos){ + public KeyboardRecorder getNewKeyboardFromOldKeyboard(GameButtonOld[] gbos) { KeyboardRecorder kr = new KeyboardRecorder(); GameButtonRecorder[] gbrs = new GameButtonRecorder[gbos.length]; - for(int i = 0; i < gbrs.length; i++){ + for (int i = 0; i < gbrs.length; i++) { gbrs[i] = getGameButtonRecoderFromOldKeyboardModel(gbos[i]); } kr.setRecorderDatas(gbrs); @@ -78,7 +78,7 @@ public KeyboardRecorder getNewKeyboardFromOldKeyboard(GameButtonOld[] gbos){ return kr; } - private GameButtonRecorder getGameButtonRecoderFromOldKeyboardModel(GameButtonOld gbo){ + private GameButtonRecorder getGameButtonRecoderFromOldKeyboardModel(GameButtonOld gbo) { final String OLD_MOUSE_PRI = "MOUSE_Pri"; final String OLD_MOUSE_SEC = "MOUSE_Sec"; @@ -88,7 +88,7 @@ private GameButtonRecorder getGameButtonRecoderFromOldKeyboardModel(GameButtonOl gbr.keySize = new float[]{gbo.getKeySizeW(), gbo.getKeySizeH()}; gbr.isChars = false; Log.e(TAG, "透明度" + ColorUtils.int2rgba(ColorUtils.hex2Int(gbo.getColorhex()))[3]); - gbr.alphaSize = (int)((ColorUtils.int2rgba(ColorUtils.hex2Int(gbo.getColorhex()))[3]) / 255f * 100); //透明度从颜色值Hex中取出,然后转为不透明度的百分比 + gbr.alphaSize = (int) ((ColorUtils.int2rgba(ColorUtils.hex2Int(gbo.getColorhex()))[3]) / 255f * 100); //透明度从颜色值Hex中取出,然后转为不透明度的百分比 gbr.cornerRadius = (gbo.getCornerRadius() / 180) * 100; //圆角值转化为百分比 gbr.designIndex = GameButton.DEFAULT_DESIGN_INDEX; //主题采用默认值 gbr.isHide = gbo.isHide(); @@ -99,35 +99,35 @@ private GameButtonRecorder getGameButtonRecoderFromOldKeyboardModel(GameButtonOl Arrays.fill(keyMap, ""); int[] keyTypes = new int[GameButton.MAX_KEYMAP_SIZE]; - if (gbo.getKeyMain().equals(OLD_MOUSE_PRI)){ + if (gbo.getKeyMain().equals(OLD_MOUSE_PRI)) { keyMap[0] = MouseMap.MOUSEMAP_BUTTON_LEFT; keyTypes[0] = GameButton.MOUSE_TYPE; - }else if (gbo.getKeyMain().equals(OLD_MOUSE_SEC)){ + } else if (gbo.getKeyMain().equals(OLD_MOUSE_SEC)) { keyMap[0] = MouseMap.MOUSEMAP_BUTTON_RIGHT; keyTypes[0] = GameButton.MOUSE_TYPE; - }else if(!gbo.getKeyMain().equals("空")){ + } else if (!gbo.getKeyMain().equals("空")) { keyMap[0] = gbo.getKeyMain(); keyTypes[0] = GameButton.KEY_TYPE; } - if (gbo.isMult()){ - if (gbo.getSpecialOne().equals(OLD_MOUSE_PRI)){ + if (gbo.isMult()) { + if (gbo.getSpecialOne().equals(OLD_MOUSE_PRI)) { keyMap[1] = MouseMap.MOUSEMAP_BUTTON_LEFT; keyTypes[1] = GameButton.MOUSE_TYPE; - }else if (gbo.getSpecialOne().equals(OLD_MOUSE_SEC)){ + } else if (gbo.getSpecialOne().equals(OLD_MOUSE_SEC)) { keyMap[1] = MouseMap.MOUSEMAP_BUTTON_RIGHT; keyTypes[1] = GameButton.MOUSE_TYPE; - }else if (!gbo.getSpecialOne().equals("空")){ + } else if (!gbo.getSpecialOne().equals("空")) { keyMap[1] = gbo.getKeyMain(); keyTypes[1] = GameButton.KEY_TYPE; } - if (gbo.getSpecialTwo().equals(OLD_MOUSE_PRI)){ + if (gbo.getSpecialTwo().equals(OLD_MOUSE_PRI)) { keyMap[2] = MouseMap.MOUSEMAP_BUTTON_LEFT; keyTypes[2] = GameButton.MOUSE_TYPE; - }else if (gbo.getSpecialOne().equals(OLD_MOUSE_SEC)){ + } else if (gbo.getSpecialOne().equals(OLD_MOUSE_SEC)) { keyMap[2] = MouseMap.MOUSEMAP_BUTTON_RIGHT; keyTypes[2] = GameButton.MOUSE_TYPE; - }else if (!gbo.getSpecialTwo().equals("空")){ + } else if (!gbo.getSpecialTwo().equals("空")) { keyMap[2] = gbo.getKeyMain(); keyTypes[2] = GameButton.KEY_TYPE; } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/KeyboardRecorder.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/KeyboardRecorder.java index c3d5b816..d3ae357e 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/KeyboardRecorder.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/support/KeyboardRecorder.java @@ -29,12 +29,12 @@ public int[] getScreenData() { return new int[]{screenWidth, screenHeight}; } - public KeyboardRecorder setVersionCode(int version){ + public KeyboardRecorder setVersionCode(int version) { this.versionCode = version; return this; } - public int getVersionCode(){ + public int getVersionCode() { return this.versionCode; } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/client/Client.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/client/Client.java index 39c988d9..0e20ceae 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/client/Client.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/client/Client.java @@ -7,18 +7,30 @@ import com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent; public interface Client extends KeyEvent { - void setKey(int keyCode,boolean pressed); - void setMouseButton(int mouseCode,boolean pressed); - void setPointer(int x,int y); + void setKey(int keyCode, boolean pressed); + + void setMouseButton(int mouseCode, boolean pressed); + + void setPointer(int x, int y); + void setPointerInc(int xInc, int yInc); + Activity getActivity(); + void addView(View v); - void addContentView(View view,ViewGroup.LayoutParams params); + + void addContentView(View view, ViewGroup.LayoutParams params); + void typeWords(String str); + //void addControllerView(View v); int[] getGrabbedPointer(); + int[] getLoosenPointer(); + ViewGroup getViewsParent(); + View getSurfaceLayerView(); + boolean isGrabbed(); } \ No newline at end of file diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/codes/XKeyMap.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/codes/XKeyMap.java index c3fe61c8..3183f165 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/codes/XKeyMap.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/codes/XKeyMap.java @@ -10,7 +10,6 @@ import static com.aof.mcinabox.gamecontroller.codes.BoatMousecodes.BOAT_MOUSE_BUTTON_right; import static com.aof.mcinabox.gamecontroller.codes.BoatMousecodes.BOAT_MOUSE_WHEEL_down; import static com.aof.mcinabox.gamecontroller.codes.BoatMousecodes.BOAT_MOUSE_WHEEL_up; -import static com.aof.mcinabox.gamecontroller.definitions.map.KeyMap.*; import static com.aof.mcinabox.gamecontroller.definitions.map.MouseMap.MOUSEMAP_BUTTON_LEFT; import static com.aof.mcinabox.gamecontroller.definitions.map.MouseMap.MOUSEMAP_BUTTON_MIDDLE; import static com.aof.mcinabox.gamecontroller.definitions.map.MouseMap.MOUSEMAP_BUTTON_RIGHT; diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/BaseController.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/BaseController.java index 0e792fda..0a2bb412 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/BaseController.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/BaseController.java @@ -19,9 +19,9 @@ public abstract class BaseController implements Controller { public Context context; private Timer mTimer; private final static int DEFAULT_INTERVAL_TIME = 5000; - private int internalTime; - private Config mConfig; - private boolean isTimerEnable; + private final int internalTime; + private final Config mConfig; + private final boolean isTimerEnable; public BaseController(Client client, int intervalTime, boolean enableTimer) { this.client = client; @@ -30,12 +30,12 @@ public BaseController(Client client, int intervalTime, boolean enableTimer) { this.internalTime = intervalTime; this.mConfig = new Config(DisplayUtils.getDisplayWindowSize(context)[0], DisplayUtils.getDisplayWindowSize(context)[1]); this.isTimerEnable = enableTimer; - if(enableTimer){ + if (enableTimer) { createAutoSaveTimer(); } } - public BaseController(Client client,boolean enableTimer){ + public BaseController(Client client, boolean enableTimer) { this(client, BaseController.DEFAULT_INTERVAL_TIME, enableTimer); } @@ -148,27 +148,27 @@ public Client getClient() { @Override public void onPaused() { - if(mTimer != null){ + if (mTimer != null) { mTimer.cancel(); mTimer = null; } - for (Input i : inputs){ + for (Input i : inputs) { i.onPaused(); } } @Override public void onResumed() { - if(isTimerEnable){ + if (isTimerEnable) { createAutoSaveTimer(); } - for (Input i : inputs){ + for (Input i : inputs) { i.onResumed(); } } - private void createAutoSaveTimer(){ - if(mTimer != null) return; + private void createAutoSaveTimer() { + if (mTimer != null) return; mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override @@ -179,7 +179,7 @@ public void run() { } @Override - public int[] getLossenPointer(){ + public int[] getLossenPointer() { return client.getLoosenPointer(); } @@ -188,7 +188,7 @@ public Config getConfig() { return this.mConfig; } - public boolean isTimerEnabled(){ + public boolean isTimerEnabled() { return this.isTimerEnable; } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/Controller.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/Controller.java index 26fff4f9..98696ad9 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/Controller.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/Controller.java @@ -47,20 +47,20 @@ public interface Controller { Config getConfig(); - class Config{ + class Config { private final int screenWidth; private final int screenHeight; - public Config(int screenWidth, int screenHeight){ + public Config(int screenWidth, int screenHeight) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; } - public int getScreenWidth(){ + public int getScreenWidth() { return screenWidth; } - public int getScreenHeight(){ + public int getScreenHeight() { return screenHeight; } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/HardwareController.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/HardwareController.java index ff9bd996..43fc6721 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/HardwareController.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/HardwareController.java @@ -5,13 +5,11 @@ import android.content.Intent; import android.content.IntentFilter; import android.hardware.input.InputManager; -import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; -import android.widget.Toast; import com.aof.mcinabox.gamecontroller.client.Client; import com.aof.mcinabox.gamecontroller.codes.AndroidKeyMap; diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/VirtualController.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/VirtualController.java index 42c693ee..ed103785 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/VirtualController.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/controller/VirtualController.java @@ -70,8 +70,8 @@ public class VirtualController extends BaseController implements View.OnClickLis //Dialog的控件 private final String TAG = "VirtualController"; private final Translation mTranslation; - private int screenWidth; - private int screenHeight; + private final int screenWidth; + private final int screenHeight; public OnscreenInput crossKeyboard; public OnscreenInput itemBar; public OnscreenInput onscreenKeyboard; @@ -437,7 +437,7 @@ private void loadConfigFromFile() { switchDebugInfo.setChecked(sp.getBoolean(sp_enable_debuginfo, false)); if (!sp.contains(sp_first_loadder)) { resetAllPosOnScreen(); - ((CustomizeKeyboard)custmoizeKeyboard).mManager.loadKeyboard(new CustomizeKeyboardMaker(context).createDefaultKeyboard()); + ((CustomizeKeyboard) custmoizeKeyboard).mManager.loadKeyboard(new CustomizeKeyboardMaker(context).createDefaultKeyboard()); } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/event/BaseKeyEvent.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/event/BaseKeyEvent.java index 85d0933f..f9d84886 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/event/BaseKeyEvent.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/event/BaseKeyEvent.java @@ -49,7 +49,7 @@ public BaseKeyEvent setChars(String str) { @NotNull @Override - public String toString(){ + public String toString() { return String.format("BaseKeyEvent { tag = \"%s\", keyName = \"%s\", pressed = %s, type = %s, pointer = %s }", this.tag, this.keyName, this.pressed, this.type, "[0]: " + this.mPointer[0] + "[1]: " + this.mPointer[1]); } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/log/DebugInfo.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/log/DebugInfo.java index 3b39ef1c..ec69fb6d 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/log/DebugInfo.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/log/DebugInfo.java @@ -113,9 +113,9 @@ public boolean isEnabled() { @Override public void setEnabled(boolean enabled) { this.isEnabled = enabled; - if(enabled){ + if (enabled) { mLogView.setVisibility(View.VISIBLE); - }else{ + } else { mLogView.setVisibility(View.GONE); } /* @@ -163,13 +163,14 @@ public void onClick(View v) { private boolean firstWrite = true; private boolean isWrite = true; - private void writeLog(String log){ - if(!isWrite) + + private void writeLog(String log) { + if (!isWrite) return; File logFile = new File(AppManifest.BOAT_LOG_FILE); - if(!logFile.exists()) { + if (!logFile.exists()) { try { - if(!logFile.createNewFile()){ + if (!logFile.createNewFile()) { isWrite = false; } } catch (IOException e) { diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/GamePad.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/GamePad.java index d19af56a..adb23f15 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/GamePad.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/GamePad.java @@ -1,7 +1,6 @@ package com.aof.mcinabox.gamecontroller.input.otg; import android.content.Context; -import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; @@ -11,9 +10,9 @@ import com.aof.mcinabox.gamecontroller.event.BaseKeyEvent; import com.aof.mcinabox.gamecontroller.input.HwInput; -import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_POINTER_INC; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.KEYBOARD_BUTTON; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_BUTTON; +import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_POINTER_INC; public class GamePad implements HwInput { @@ -31,21 +30,22 @@ public class GamePad implements HwInput { private final static int type_3 = MOUSE_POINTER_INC; private boolean G_B_PRESS; + @Override public boolean onKey(KeyEvent event) { - if (mController.isGrabbed()){ - switch(event.getKeyCode()){ + if (mController.isGrabbed()) { + switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BUTTON_A: //跳跃 sendEvent(KeyMap.KEYMAP_KEY_SPACE, event, type_1); break; case KeyEvent.KEYCODE_BUTTON_B: //潜行(保持) - if(event.getAction() == KeyEvent.ACTION_UP){ - if(G_B_PRESS){ + if (event.getAction() == KeyEvent.ACTION_UP) { + if (G_B_PRESS) { G_B_PRESS = false; sendEvent(KeyMap.KEYMAP_KEY_LSHIFT, false, type_1); - }else{ + } else { G_B_PRESS = true; sendEvent(KeyMap.KEYMAP_KEY_LSHIFT, true, type_1); } @@ -72,9 +72,9 @@ public boolean onKey(KeyEvent event) { sendEvent(KeyMap.KEYMAP_KEY_LSHIFT, event, type_1); break; } - } else{ + } else { - switch(event.getKeyCode()){ + switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BUTTON_A: //跳跃 sendEvent(KeyMap.KEYMAP_KEY_SPACE, event, type_1); @@ -106,9 +106,9 @@ public boolean onKey(KeyEvent event) { return true; } - private void sendEvent(String keyName, KeyEvent keyEvent, int keyType){ + private void sendEvent(String keyName, KeyEvent keyEvent, int keyType) { boolean pressed; - switch(keyEvent.getAction()){ + switch (keyEvent.getAction()) { case KeyEvent.ACTION_DOWN: pressed = true; break; @@ -121,7 +121,7 @@ private void sendEvent(String keyName, KeyEvent keyEvent, int keyType){ sendEvent(keyName, pressed, keyType); } - private void sendEvent(String keyName, boolean pressed, int keyType){ + private void sendEvent(String keyName, boolean pressed, int keyType) { mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, keyType, null)); } @@ -167,81 +167,81 @@ public boolean onMotionKey(MotionEvent event) { //应该顺序处理每一个轴的数据 //由于响应时间的要求,我们先处理耗时短的轴的数据 - if (mController.isGrabbed()){ + if (mController.isGrabbed()) { //LT: AXIS_LTRIGGER //RT: AXIS_RTRIGGER - if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) >= G_LT_THR_VALUE && !G_LT_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) >= G_LT_THR_VALUE && !G_LT_PRESS) { G_LT_PRESS = true; sendEvent(MouseMap.MOUSEMAP_BUTTON_RIGHT, true, type_2); - } else if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) < G_LT_THR_VALUE && G_LT_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) < G_LT_THR_VALUE && G_LT_PRESS) { G_LT_PRESS = false; sendEvent(MouseMap.MOUSEMAP_BUTTON_RIGHT, false, type_2); } - if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) >= G_RT_THR_VALUE && !G_RT_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) >= G_RT_THR_VALUE && !G_RT_PRESS) { G_RT_PRESS = true; sendEvent(MouseMap.MOUSEMAP_BUTTON_LEFT, true, type_2); - } else if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) < G_RT_THR_VALUE && G_RT_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) < G_RT_THR_VALUE && G_RT_PRESS) { G_RT_PRESS = false; sendEvent(MouseMap.MOUSEMAP_BUTTON_LEFT, false, type_2); } //左摇杆X: AXIS_X //左摇杆Y: AXIS_Y - if (event.getAxisValue(MotionEvent.AXIS_X) >= G_L_B_THR_POSITIVE){ - if (!G_L_B_X_POSITIVE_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_X) >= G_L_B_THR_POSITIVE) { + if (!G_L_B_X_POSITIVE_PRESS) { G_L_B_X_POSITIVE_PRESS = true; sendEvent(G_L_B_X_POSITIVE_KEY, true, type_1); } - if (G_L_B_X_NEGATIVE_PRESS){ + if (G_L_B_X_NEGATIVE_PRESS) { G_L_B_X_NEGATIVE_PRESS = false; sendEvent(G_L_B_X_NEGATIVE_KEY, false, type_1); } - } else if (event.getAxisValue(MotionEvent.AXIS_X) <= G_L_B_THR_NEGATIVE){ - if(!G_L_B_X_NEGATIVE_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_X) <= G_L_B_THR_NEGATIVE) { + if (!G_L_B_X_NEGATIVE_PRESS) { G_L_B_X_NEGATIVE_PRESS = true; sendEvent(G_L_B_X_NEGATIVE_KEY, true, type_1); } - if(G_L_B_X_POSITIVE_PRESS){ + if (G_L_B_X_POSITIVE_PRESS) { G_L_B_X_POSITIVE_PRESS = false; sendEvent(G_L_B_X_POSITIVE_KEY, false, type_1); } } else { - if(G_L_B_X_POSITIVE_PRESS){ + if (G_L_B_X_POSITIVE_PRESS) { G_L_B_X_POSITIVE_PRESS = false; sendEvent(G_L_B_X_POSITIVE_KEY, false, type_1); } - if(G_L_B_X_NEGATIVE_PRESS){ + if (G_L_B_X_NEGATIVE_PRESS) { G_L_B_X_NEGATIVE_PRESS = false; sendEvent(G_L_B_X_NEGATIVE_KEY, false, type_1); } } - if (event.getAxisValue(MotionEvent.AXIS_Y) >= G_L_B_THR_POSITIVE){ - if (!G_L_B_Y_POSITIVE_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_Y) >= G_L_B_THR_POSITIVE) { + if (!G_L_B_Y_POSITIVE_PRESS) { G_L_B_Y_POSITIVE_PRESS = true; sendEvent(G_L_B_Y_POSITIVE_KEY, true, type_1); } - if (G_L_B_Y_NEGATIVE_PRESS){ + if (G_L_B_Y_NEGATIVE_PRESS) { G_L_B_Y_NEGATIVE_PRESS = false; sendEvent(G_L_B_Y_NEGATIVE_KEY, false, type_1); } - } else if (event.getAxisValue(MotionEvent.AXIS_Y) <= G_L_B_THR_NEGATIVE){ - if(!G_L_B_Y_NEGATIVE_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_Y) <= G_L_B_THR_NEGATIVE) { + if (!G_L_B_Y_NEGATIVE_PRESS) { G_L_B_Y_NEGATIVE_PRESS = true; sendEvent(G_L_B_Y_NEGATIVE_KEY, true, type_1); } - if(G_L_B_Y_POSITIVE_PRESS){ + if (G_L_B_Y_POSITIVE_PRESS) { G_L_B_Y_POSITIVE_PRESS = false; sendEvent(G_L_B_Y_POSITIVE_KEY, false, type_1); } } else { - if(G_L_B_Y_POSITIVE_PRESS){ + if (G_L_B_Y_POSITIVE_PRESS) { G_L_B_Y_POSITIVE_PRESS = false; sendEvent(G_L_B_Y_POSITIVE_KEY, false, type_1); } - if(G_L_B_Y_NEGATIVE_PRESS){ + if (G_L_B_Y_NEGATIVE_PRESS) { G_L_B_Y_NEGATIVE_PRESS = false; sendEvent(G_L_B_Y_NEGATIVE_KEY, false, type_1); } @@ -249,59 +249,59 @@ public boolean onMotionKey(MotionEvent event) { //苦力帽X: AXIS_HAT_X //苦力帽Y: AXIS_HAT_Y - if (event.getAxisValue(MotionEvent.AXIS_HAT_X) >= G_HAT_THR_POSITIVE){ - if (!G_HAT_X_POSITIVE_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_HAT_X) >= G_HAT_THR_POSITIVE) { + if (!G_HAT_X_POSITIVE_PRESS) { G_HAT_X_POSITIVE_PRESS = true; sendEvent(G_HAT_X_POSITIVE_KEY, true, type_1); } - if (G_HAT_X_NEGATIVE_PRESS){ + if (G_HAT_X_NEGATIVE_PRESS) { G_HAT_X_NEGATIVE_PRESS = false; sendEvent(G_HAT_X_NEGATIVE_KEY, false, type_1); } - } else if (event.getAxisValue(MotionEvent.AXIS_HAT_X) <= G_HAT_THR_NEGATIVE){ - if(!G_HAT_X_NEGATIVE_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_HAT_X) <= G_HAT_THR_NEGATIVE) { + if (!G_HAT_X_NEGATIVE_PRESS) { G_HAT_X_NEGATIVE_PRESS = true; sendEvent(G_HAT_X_NEGATIVE_KEY, true, type_1); } - if(G_HAT_X_POSITIVE_PRESS){ + if (G_HAT_X_POSITIVE_PRESS) { G_HAT_X_POSITIVE_PRESS = false; sendEvent(G_HAT_X_POSITIVE_KEY, false, type_1); } } else { - if(G_HAT_X_POSITIVE_PRESS){ + if (G_HAT_X_POSITIVE_PRESS) { G_HAT_X_POSITIVE_PRESS = false; sendEvent(G_HAT_X_POSITIVE_KEY, false, type_1); } - if(G_HAT_X_NEGATIVE_PRESS){ + if (G_HAT_X_NEGATIVE_PRESS) { G_HAT_X_NEGATIVE_PRESS = false; sendEvent(G_HAT_X_NEGATIVE_KEY, false, type_1); } } - if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) >= G_HAT_THR_POSITIVE){ - if (!G_HAT_Y_POSITIVE_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) >= G_HAT_THR_POSITIVE) { + if (!G_HAT_Y_POSITIVE_PRESS) { G_HAT_Y_POSITIVE_PRESS = true; sendEvent(G_HAT_Y_POSITIVE_KEY, true, type_1); } - if (G_HAT_Y_NEGATIVE_PRESS){ + if (G_HAT_Y_NEGATIVE_PRESS) { G_HAT_Y_NEGATIVE_PRESS = false; sendEvent(G_HAT_Y_NEGATIVE_KEY, false, type_1); } - } else if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) <= G_HAT_THR_NEGATIVE){ - if(!G_HAT_Y_NEGATIVE_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) <= G_HAT_THR_NEGATIVE) { + if (!G_HAT_Y_NEGATIVE_PRESS) { G_HAT_Y_NEGATIVE_PRESS = true; sendEvent(G_HAT_Y_NEGATIVE_KEY, true, type_1); } - if(G_HAT_Y_POSITIVE_PRESS){ + if (G_HAT_Y_POSITIVE_PRESS) { G_HAT_Y_POSITIVE_PRESS = false; sendEvent(G_HAT_Y_POSITIVE_KEY, false, type_1); } } else { - if(G_HAT_Y_POSITIVE_PRESS){ + if (G_HAT_Y_POSITIVE_PRESS) { G_HAT_Y_POSITIVE_PRESS = false; sendEvent(G_HAT_Y_POSITIVE_KEY, false, type_1); } - if(G_HAT_Y_NEGATIVE_PRESS){ + if (G_HAT_Y_NEGATIVE_PRESS) { G_HAT_Y_NEGATIVE_PRESS = false; sendEvent(G_HAT_Y_NEGATIVE_KEY, false, type_1); } @@ -310,23 +310,23 @@ public boolean onMotionKey(MotionEvent event) { //右摇杆Z: AXIS_Z //右摇杆RZ: AXIS_RZ - if (mGamePadThread != null){ + if (mGamePadThread != null) { int xInc = 0, yInc = 0; - if(event.getAxisValue(MotionEvent.AXIS_Z) >= G_R_B_THR_POSITIVE){ - xInc = (int)((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_POSITIVE) * G_R_B_NUM_TIMES); - } else if (event.getAxisValue(MotionEvent.AXIS_Z) <= G_R_B_THR_NEGATIVE){ - xInc = (int)((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); + if (event.getAxisValue(MotionEvent.AXIS_Z) >= G_R_B_THR_POSITIVE) { + xInc = (int) ((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_POSITIVE) * G_R_B_NUM_TIMES); + } else if (event.getAxisValue(MotionEvent.AXIS_Z) <= G_R_B_THR_NEGATIVE) { + xInc = (int) ((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); } - if(event.getAxisValue(MotionEvent.AXIS_RZ) >= G_R_B_THR_POSITIVE){ - yInc = (int)((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_POSITIVE)* G_R_B_NUM_TIMES); - } else if (event.getAxisValue(MotionEvent.AXIS_RZ) <= G_R_B_THR_NEGATIVE){ - yInc = (int)((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); + if (event.getAxisValue(MotionEvent.AXIS_RZ) >= G_R_B_THR_POSITIVE) { + yInc = (int) ((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_POSITIVE) * G_R_B_NUM_TIMES); + } else if (event.getAxisValue(MotionEvent.AXIS_RZ) <= G_R_B_THR_NEGATIVE) { + yInc = (int) ((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); } - if( event.getAxisValue(MotionEvent.AXIS_Z) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_Z) < G_R_B_THR_POSITIVE && event.getAxisValue(MotionEvent.AXIS_RZ) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_RZ) < G_R_B_THR_POSITIVE) + if (event.getAxisValue(MotionEvent.AXIS_Z) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_Z) < G_R_B_THR_POSITIVE && event.getAxisValue(MotionEvent.AXIS_RZ) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_RZ) < G_R_B_THR_POSITIVE) mGamePadThread.setPaused(true); - else{ + else { mGamePadThread.getRunnable().setIncs(xInc, yInc); mGamePadThread.setPaused(false); } @@ -336,77 +336,77 @@ public boolean onMotionKey(MotionEvent event) { //LT: AXIS_LTRIGGER //RT: AXIS_RTRIGGER - if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) >= G_LT_THR_VALUE && !G_LT_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) >= G_LT_THR_VALUE && !G_LT_PRESS) { G_LT_PRESS = true; sendEvent(MouseMap.MOUSEMAP_BUTTON_RIGHT, true, type_2); - } else if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) < G_LT_THR_VALUE && G_LT_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_LTRIGGER) < G_LT_THR_VALUE && G_LT_PRESS) { G_LT_PRESS = false; sendEvent(MouseMap.MOUSEMAP_BUTTON_RIGHT, false, type_2); } - if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) >= G_RT_THR_VALUE && !G_RT_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) >= G_RT_THR_VALUE && !G_RT_PRESS) { G_RT_PRESS = true; sendEvent(MouseMap.MOUSEMAP_BUTTON_LEFT, true, type_2); - } else if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) < G_RT_THR_VALUE && G_RT_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_RTRIGGER) < G_RT_THR_VALUE && G_RT_PRESS) { G_RT_PRESS = false; sendEvent(MouseMap.MOUSEMAP_BUTTON_LEFT, false, type_2); } //苦力帽X: AXIS_HAT_X //苦力帽Y: AXIS_HAT_Y - if (event.getAxisValue(MotionEvent.AXIS_HAT_X) >= G_HAT_THR_POSITIVE){ - if (!G_HAT_X_POSITIVE_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_HAT_X) >= G_HAT_THR_POSITIVE) { + if (!G_HAT_X_POSITIVE_PRESS) { G_HAT_X_POSITIVE_PRESS = true; sendEvent(G_HAT_X_POSITIVE_KEY, true, type_1); } - if (G_HAT_X_NEGATIVE_PRESS){ + if (G_HAT_X_NEGATIVE_PRESS) { G_HAT_X_NEGATIVE_PRESS = false; sendEvent(G_HAT_X_NEGATIVE_KEY, false, type_1); } - } else if (event.getAxisValue(MotionEvent.AXIS_HAT_X) <= G_HAT_THR_NEGATIVE){ - if(!G_HAT_X_NEGATIVE_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_HAT_X) <= G_HAT_THR_NEGATIVE) { + if (!G_HAT_X_NEGATIVE_PRESS) { G_HAT_X_NEGATIVE_PRESS = true; sendEvent(G_HAT_X_NEGATIVE_KEY, true, type_1); } - if(G_HAT_X_POSITIVE_PRESS){ + if (G_HAT_X_POSITIVE_PRESS) { G_HAT_X_POSITIVE_PRESS = false; sendEvent(G_HAT_X_POSITIVE_KEY, false, type_1); } } else { - if(G_HAT_X_POSITIVE_PRESS){ + if (G_HAT_X_POSITIVE_PRESS) { G_HAT_X_POSITIVE_PRESS = false; sendEvent(G_HAT_X_POSITIVE_KEY, false, type_1); } - if(G_HAT_X_NEGATIVE_PRESS){ + if (G_HAT_X_NEGATIVE_PRESS) { G_HAT_X_NEGATIVE_PRESS = false; sendEvent(G_HAT_X_NEGATIVE_KEY, false, type_1); } } - if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) >= G_HAT_THR_POSITIVE){ - if (!G_HAT_Y_POSITIVE_PRESS){ + if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) >= G_HAT_THR_POSITIVE) { + if (!G_HAT_Y_POSITIVE_PRESS) { G_HAT_Y_POSITIVE_PRESS = true; sendEvent(G_HAT_Y_POSITIVE_KEY, true, type_1); } - if (G_HAT_Y_NEGATIVE_PRESS){ + if (G_HAT_Y_NEGATIVE_PRESS) { G_HAT_Y_NEGATIVE_PRESS = false; sendEvent(G_HAT_Y_NEGATIVE_KEY, false, type_1); } - } else if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) <= G_HAT_THR_NEGATIVE){ - if(!G_HAT_Y_NEGATIVE_PRESS){ + } else if (event.getAxisValue(MotionEvent.AXIS_HAT_Y) <= G_HAT_THR_NEGATIVE) { + if (!G_HAT_Y_NEGATIVE_PRESS) { G_HAT_Y_NEGATIVE_PRESS = true; sendEvent(G_HAT_Y_NEGATIVE_KEY, true, type_1); } - if(G_HAT_Y_POSITIVE_PRESS){ + if (G_HAT_Y_POSITIVE_PRESS) { G_HAT_Y_POSITIVE_PRESS = false; sendEvent(G_HAT_Y_POSITIVE_KEY, false, type_1); } } else { - if(G_HAT_Y_POSITIVE_PRESS){ + if (G_HAT_Y_POSITIVE_PRESS) { G_HAT_Y_POSITIVE_PRESS = false; sendEvent(G_HAT_Y_POSITIVE_KEY, false, type_1); } - if(G_HAT_Y_NEGATIVE_PRESS){ + if (G_HAT_Y_NEGATIVE_PRESS) { G_HAT_Y_NEGATIVE_PRESS = false; sendEvent(G_HAT_Y_NEGATIVE_KEY, false, type_1); } @@ -414,23 +414,23 @@ public boolean onMotionKey(MotionEvent event) { //右摇杆Z: AXIS_Z //右摇杆RZ: AXIS_RZ - if (mGamePadThread != null){ + if (mGamePadThread != null) { int xInc = 0, yInc = 0; - if(event.getAxisValue(MotionEvent.AXIS_Z) >= G_R_B_THR_POSITIVE){ - xInc = (int)((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_POSITIVE) * G_R_B_NUM_TIMES); - } else if (event.getAxisValue(MotionEvent.AXIS_Z) <= G_R_B_THR_NEGATIVE){ - xInc = (int)((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); + if (event.getAxisValue(MotionEvent.AXIS_Z) >= G_R_B_THR_POSITIVE) { + xInc = (int) ((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_POSITIVE) * G_R_B_NUM_TIMES); + } else if (event.getAxisValue(MotionEvent.AXIS_Z) <= G_R_B_THR_NEGATIVE) { + xInc = (int) ((event.getAxisValue(MotionEvent.AXIS_Z) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); } - if(event.getAxisValue(MotionEvent.AXIS_RZ) >= G_R_B_THR_POSITIVE){ - yInc = (int)((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_POSITIVE)* G_R_B_NUM_TIMES); - } else if (event.getAxisValue(MotionEvent.AXIS_RZ) <= G_R_B_THR_NEGATIVE){ - yInc = (int)((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); + if (event.getAxisValue(MotionEvent.AXIS_RZ) >= G_R_B_THR_POSITIVE) { + yInc = (int) ((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_POSITIVE) * G_R_B_NUM_TIMES); + } else if (event.getAxisValue(MotionEvent.AXIS_RZ) <= G_R_B_THR_NEGATIVE) { + yInc = (int) ((event.getAxisValue(MotionEvent.AXIS_RZ) - G_R_B_THR_NEGATIVE) * G_R_B_NUM_TIMES); } - if( event.getAxisValue(MotionEvent.AXIS_Z) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_Z) < G_R_B_THR_POSITIVE && event.getAxisValue(MotionEvent.AXIS_RZ) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_RZ) < G_R_B_THR_POSITIVE) + if (event.getAxisValue(MotionEvent.AXIS_Z) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_Z) < G_R_B_THR_POSITIVE && event.getAxisValue(MotionEvent.AXIS_RZ) > G_R_B_THR_NEGATIVE && event.getAxisValue(MotionEvent.AXIS_RZ) < G_R_B_THR_POSITIVE) mGamePadThread.setPaused(true); - else{ + else { mGamePadThread.getRunnable().setIncs(xInc, yInc); mGamePadThread.setPaused(false); } @@ -460,7 +460,7 @@ public boolean load(Context context, Controller controller) { @Override public boolean unload() { //销毁输入进程 - if(mGamePadThread != null && !mGamePadThread.isInterrupted()) + if (mGamePadThread != null && !mGamePadThread.isInterrupted()) mGamePadThread.interrupt(); return true; } @@ -492,14 +492,14 @@ public void setEnabled(boolean enabled) { @Override public void onPaused() { //销毁输入进程 - if(mGamePadThread != null && !mGamePadThread.isInterrupted()) + if (mGamePadThread != null && !mGamePadThread.isInterrupted()) mGamePadThread.interrupt(); } @Override public void onResumed() { //重建输入进程 - if(mGamePadThread == null || mGamePadThread.isInterrupted()){ + if (mGamePadThread == null || mGamePadThread.isInterrupted()) { mGamePadThread = new GamePadThread(); mGamePadThread.start(); } @@ -510,7 +510,7 @@ public Controller getController() { return this.mController; } - private class GamePadThread extends Thread{ + private class GamePadThread extends Thread { private class GamePadRunnable implements Runnable { private int xInc; @@ -518,20 +518,20 @@ private class GamePadRunnable implements Runnable { private long lastPointerTime; private final GamePadThread mThread; - public GamePadRunnable(GamePadThread thread){ + public GamePadRunnable(GamePadThread thread) { this.mThread = thread; } @Override public void run() { - while (true){ - if(mThread.isPaused()){ + while (true) { + if (mThread.isPaused()) { continue; } - if(Thread.currentThread().isInterrupted()){ + if (Thread.currentThread().isInterrupted()) { return; } - if(System.currentTimeMillis() - this.lastPointerTime >= POINTER_SEND_LAG){ + if (System.currentTimeMillis() - this.lastPointerTime >= POINTER_SEND_LAG) { //Log.e(TAG, "Thread: do." + " xInc: " + xInc + " yInc: " + yInc); this.lastPointerTime = System.currentTimeMillis(); mController.sendKey(new BaseKeyEvent(TAG, null, false, type_3, new int[]{xInc, yInc})); @@ -539,7 +539,8 @@ public void run() { } } } - public void setIncs(int xInc, int yInc){ + + public void setIncs(int xInc, int yInc) { //Log.e(TAG, "Thread: setIncs." + " xInc: " + xInc + " yInc: " + yInc); this.xInc = xInc; this.yInc = yInc; @@ -554,19 +555,19 @@ public void run() { mRunnable.run(); } - public void setPaused(boolean b){ + public void setPaused(boolean b) { //Log.e(TAG, "Thread: setPaused." + isPaused); this.isPaused = b; } - public boolean isPaused(){ + public boolean isPaused() { return this.isPaused; } private GamePadRunnable mRunnable; private boolean isPaused = true; - public GamePadRunnable getRunnable(){ + public GamePadRunnable getRunnable() { return this.mRunnable; } } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/Mouse.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/Mouse.java index f80a7fd8..d2cbbb74 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/Mouse.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/otg/Mouse.java @@ -44,7 +44,7 @@ public boolean load(Context context, Controller controller) { this.mController = controller; //设定鼠标监听器(SDK >= 26) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - mCapturedPointerListener = new View.OnCapturedPointerListener(){ + mCapturedPointerListener = new View.OnCapturedPointerListener() { @Override public boolean onCapturedPointer(View view, MotionEvent event) { Mouse.this.onMotionKey(event); @@ -84,9 +84,9 @@ private void sendPointerInc(int x, int y) { mController.sendKey(new BaseKeyEvent(TAG, null, false, type1, new int[]{x, y})); } - private void sendKeyEvent(String keyName, boolean pressed, int type){ - if(keyName == null) return; - mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, type,null)); + private void sendKeyEvent(String keyName, boolean pressed, int type) { + if (keyName == null) return; + mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, type, null)); } //配置信息处理 @@ -108,19 +108,19 @@ public boolean onKey(KeyEvent event) { @Override public boolean onMotionKey(MotionEvent event) { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { doMotion(event); } return true; } //主要的控制逻辑处理 - private void doMotion(MotionEvent event){ - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){ + private void doMotion(MotionEvent event) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return; } - switch(event.getActionMasked()){ + switch (event.getActionMasked()) { case MotionEvent.ACTION_BUTTON_PRESS: sendKeyEvent(mapCovert(event.getActionButton()), true, type2); break; @@ -129,9 +129,9 @@ private void doMotion(MotionEvent event){ break; case MotionEvent.ACTION_SCROLL: String keyName; - if(event.getAxisValue(MotionEvent.AXIS_VSCROLL) > 0){ + if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) > 0) { keyName = MouseMap.MOUSEMAP_WHEEL_UP; - }else{ + } else { keyName = MouseMap.MOUSEMAP_WHEEL_DOWN; } sendKeyEvent(keyName, true, type2); @@ -141,18 +141,18 @@ private void doMotion(MotionEvent event){ case MotionEvent.ACTION_HOVER_MOVE: case MotionEvent.ACTION_HOVER_EXIT: case MotionEvent.ACTION_MOVE: - if(mController.isGrabbed()){ - sendPointerInc((int)event.getAxisValue(MotionEvent.AXIS_X) * CURSOR_EXTRA_GRABBED , (int)event.getAxisValue(MotionEvent.AXIS_Y) * CURSOR_EXTRA_GRABBED); - }else{ - sendPointerInc((int)event.getAxisValue(MotionEvent.AXIS_X) * CURSOR_EXTRA_RELEASE , (int)event.getAxisValue(MotionEvent.AXIS_Y) * CURSOR_EXTRA_RELEASE); + if (mController.isGrabbed()) { + sendPointerInc((int) event.getAxisValue(MotionEvent.AXIS_X) * CURSOR_EXTRA_GRABBED, (int) event.getAxisValue(MotionEvent.AXIS_Y) * CURSOR_EXTRA_GRABBED); + } else { + sendPointerInc((int) event.getAxisValue(MotionEvent.AXIS_X) * CURSOR_EXTRA_RELEASE, (int) event.getAxisValue(MotionEvent.AXIS_Y) * CURSOR_EXTRA_RELEASE); } break; } } - private String mapCovert(int actionButton){ - switch(actionButton){ + private String mapCovert(int actionButton) { + switch (actionButton) { case MotionEvent.BUTTON_PRIMARY: return MouseMap.MOUSEMAP_BUTTON_LEFT; case MotionEvent.BUTTON_TERTIARY: @@ -166,14 +166,14 @@ private String mapCovert(int actionButton){ @Override public void onPaused() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { cancelTimer(); } } @Override public void onResumed() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createTimer(); } } @@ -185,15 +185,15 @@ public Controller getController() { private Timer mTimer; - private void createTimer(){ - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ + private void createTimer() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { - if(!mController.getClient().getViewsParent().isFocusable()) + if (!mController.getClient().getViewsParent().isFocusable()) mController.getClient().getViewsParent().setFocusable(true); - if(!mController.getClient().getViewsParent().hasPointerCapture()){ + if (!mController.getClient().getViewsParent().hasPointerCapture()) { mController.getClient().getViewsParent().requestPointerCapture(); } } @@ -201,21 +201,21 @@ public void run() { } } - private void cancelTimer(){ + private void cancelTimer() { try { mTimer.cancel(); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } //鼠标加速分段算法 - private float mouseAcceleration(float d){ + private float mouseAcceleration(float d) { float MAX_D = 0.05f; float MAX_S = 1.2f; float tmp = Math.abs(d); int times = 1; - while(tmp >= MAX_D){ + while (tmp >= MAX_D) { tmp %= MAX_D; times++; } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/CrossKeyboard.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/CrossKeyboard.java index f09ac67a..09f2a198 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/CrossKeyboard.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/CrossKeyboard.java @@ -369,10 +369,10 @@ private void makeKeyEvent(int location, MotionEvent e) { case 5: keyName = KEYMAP_KEY_LSHIFT; if (lastKeyName.equals("") && e.getAction() == MotionEvent.ACTION_DOWN) { - if(shift){ - sendKeyEvent(keyName, false); - shift = false; - } else{ + if (shift) { + sendKeyEvent(keyName, false); + shift = false; + } else { sendKeyEvent(keyName, true); shift = true; } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/InputBox.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/InputBox.java index 3a0340b9..7ae97dcb 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/InputBox.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/InputBox.java @@ -337,12 +337,12 @@ public InputDialog(@NonNull Context context, Controller controller) { this.buttonCancel = findViewById(R.id.dialog_input_button_cancel); this.multi_line = mContext.getSharedPreferences(InputBoxConfigDialog.spFileName, InputBoxConfigDialog.spMode).getBoolean(InputBoxConfigDialog.sp_multi_line_name, true); - editBox.setOnKeyListener(new View.OnKeyListener(){ + editBox.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, android.view.KeyEvent event) { //当输入框为空的时候,拦截Backspace的按键事件,然后向控制器发送退格事件 - if(event.getAction() == android.view.KeyEvent.ACTION_DOWN && keyCode == android.view.KeyEvent.KEYCODE_BACK && editBox.getText().toString().equals("")){ + if (event.getAction() == android.view.KeyEvent.ACTION_DOWN && keyCode == android.view.KeyEvent.KEYCODE_BACK && editBox.getText().toString().equals("")) { sendKey(KeyMap.KEYMAP_KEY_BACKSPACE); return true; } diff --git a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/OnscreenTouchpad.java b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/OnscreenTouchpad.java index 2b13f328..8b97e10c 100644 --- a/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/OnscreenTouchpad.java +++ b/app/src/main/java/com/aof/mcinabox/gamecontroller/input/screen/OnscreenTouchpad.java @@ -98,8 +98,9 @@ public boolean onTouch(View v, MotionEvent event) { private int initX = 0; private int initY = 0; + private void locateCursor(MotionEvent event) { - if(mController.isGrabbed()){ + if (mController.isGrabbed()) { switch (event.getAction()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: @@ -110,7 +111,7 @@ private void locateCursor(MotionEvent event) { } initX = (int) event.getX(); initY = (int) event.getY(); - }else{ + } else { switch (touchpadMode) { case TOUCHPAD_MODE_POINT: sendPointer((int) event.getX(), (int) event.getY(), type_2); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/download/DownloadManager.java b/app/src/main/java/com/aof/mcinabox/launcher/download/DownloadManager.java index 1f5f7142..070f9e21 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/download/DownloadManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/download/DownloadManager.java @@ -16,8 +16,8 @@ public class DownloadManager { - private DownloadSupport mSupport; - private Context mContext; + private final DownloadSupport mSupport; + private final Context mContext; private FileDownloadQueueSet mQueueSet; private DownloaderDialog mDialog; @@ -48,10 +48,10 @@ public DownloadManager(Context context) { /** * [启动预设下载任务] **/ - private ArrayList tasks = new ArrayList<>(); + private final ArrayList tasks = new ArrayList<>(); public void startPresetDownload(int presetId, String id) { - if(! this.enablePreset) { + if (!this.enablePreset) { this.enablePreset = true; } this.currentPresetId = presetId; @@ -68,11 +68,11 @@ public void startPresetDownload(int presetId, String id) { current = 1; break; case DOWNLOAD_PRESET_VERSION_JSON: - this.mDialog = new DownloaderDialog(mContext,this); + this.mDialog = new DownloaderDialog(mContext, this); tasks.add(mSupport.createVersionJsonDownloadTask(id)); pgName = mContext.getString(R.string.tips_downloading_version_json); all = 5; - current =1; + current = 1; break; case DOWNLOAD_PRESET_VERSION_LIBS: tasks.addAll(mSupport.createLibrariesDownloadTask(id)); @@ -111,7 +111,7 @@ public void startPresetDownload(int presetId, String id) { mQueueSet = new FileDownloadQueueSet(mFileDownloadListener); mQueueSet.downloadSequentially(tasks); mQueueSet.start(); - updateDialogUi(id,pgName,all,current); + updateDialogUi(id, pgName, all, current); } private void updateDialogUi(String versionId, String title, int all, int current) { @@ -120,29 +120,29 @@ private void updateDialogUi(String versionId, String title, int all, int current } mDialog.setId(versionId) .setTitle(title) - .setTotalProgress(all,current); + .setTotalProgress(all, current); } - private void updateDialogUi(boolean success){ - if(success){ + private void updateDialogUi(boolean success) { + if (success) { mDialog.setFinished(); - }else{ + } else { mDialog.setFailed(); this.cancelDownload(); } } - public void startDownload(String title, String pgName, int all, int current, BaseDownloadTask[] tasks, Runable runable){ + public void startDownload(String title, String pgName, int all, int current, BaseDownloadTask[] tasks, Runable runable) { this.taskFinished = 0; this.mRunable = runable; this.taskCounts = tasks.length; mQueueSet = new FileDownloadQueueSet(mFileDownloadListener); mQueueSet.downloadSequentially(tasks); mQueueSet.start(); - updateDialogUi(title,pgName,all,current); + updateDialogUi(title, pgName, all, current); } - private FileDownloadListener mFileDownloadListener = new FileDownloadListener() { + private final FileDownloadListener mFileDownloadListener = new FileDownloadListener() { @Override protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { @@ -152,12 +152,12 @@ protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { @Override protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { //反馈下载速度 - if(!enablePreset || currentPresetId == DOWNLOAD_PRESET_VERSION_JSON || currentPresetId == DOWNLOAD_PRESET_VERSION_JAR || currentPresetId == DOWNLOAD_PRESET_ASSETS_INDEX){ - mDialog.setCurrentProgress(soFarBytes *100 / totalBytes); - mDialog.setSpeed(FormatUtils.formatDataTransferSpeed(task.getSpeed(),FormatUtils.CAPACITY_TYPE_KBYTE,FormatUtils.DTS_TYPE_S)); + if (!enablePreset || currentPresetId == DOWNLOAD_PRESET_VERSION_JSON || currentPresetId == DOWNLOAD_PRESET_VERSION_JAR || currentPresetId == DOWNLOAD_PRESET_ASSETS_INDEX) { + mDialog.setCurrentProgress(soFarBytes * 100 / totalBytes); + mDialog.setSpeed(FormatUtils.formatDataTransferSpeed(task.getSpeed(), FormatUtils.CAPACITY_TYPE_KBYTE, FormatUtils.DTS_TYPE_S)); } //反馈文件名称 - if(!enablePreset || currentPresetId != DOWNLOAD_PRESET_MANIFEST){ + if (!enablePreset || currentPresetId != DOWNLOAD_PRESET_MANIFEST) { mDialog.setFileName(task.getFilename()); } } @@ -165,24 +165,24 @@ protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { @Override protected void completed(BaseDownloadTask task) { taskFinished++; - if(enablePreset){ - if(currentPresetId == DOWNLOAD_FORGE_LIBS || currentPresetId == DOWNLOAD_PRESET_VERSION_LIBS || currentPresetId == DOWNLOAD_PRESET_ASSETS_OBJS){ - mDialog.setSpeed(FormatUtils.formatDataTransferSpeed(task.getSpeed(),FormatUtils.CAPACITY_TYPE_KBYTE,FormatUtils.DTS_TYPE_S)); + if (enablePreset) { + if (currentPresetId == DOWNLOAD_FORGE_LIBS || currentPresetId == DOWNLOAD_PRESET_VERSION_LIBS || currentPresetId == DOWNLOAD_PRESET_ASSETS_OBJS) { + mDialog.setSpeed(FormatUtils.formatDataTransferSpeed(task.getSpeed(), FormatUtils.CAPACITY_TYPE_KBYTE, FormatUtils.DTS_TYPE_S)); } mDialog.setCurrentProgress(taskFinished * 100 / taskCounts); - if(taskCounts == taskFinished){ + if (taskCounts == taskFinished) { taskFinished = 0; - if(currentPresetId != DOWNLOAD_PRESET_ASSETS_OBJS && currentPresetId != DOWNLOAD_FORGE_LIBS){ + if (currentPresetId != DOWNLOAD_PRESET_ASSETS_OBJS && currentPresetId != DOWNLOAD_FORGE_LIBS) { startPresetDownload(currentPresetId + 1, currentVersionId); - }else{ + } else { updateDialogUi(true); } } - }else{ - if(taskCounts == taskFinished){ + } else { + if (taskCounts == taskFinished) { updateDialogUi(true); } - if(mRunable != null){ + if (mRunable != null) { mRunable.run(); } } @@ -196,8 +196,8 @@ protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) { @Override protected void error(BaseDownloadTask task, Throwable e) { updateDialogUi(false); - Log.e(TAG,"failed:" + task.getFilename()); - Log.e(TAG,"message: " + e.getMessage() + " cause: " + e.getCause()); + Log.e(TAG, "failed:" + task.getFilename()); + Log.e(TAG, "message: " + e.getMessage() + " cause: " + e.getCause()); } @Override @@ -207,18 +207,20 @@ protected void warn(BaseDownloadTask task) { }; private Runable mRunable; - public void downloadManifestAndUpdateGameListUi(Runable r){ + + public void downloadManifestAndUpdateGameListUi(Runable r) { mQueueSet = new FileDownloadQueueSet(mFileDownloadListener); mQueueSet.downloadSequentially(mSupport.createVersionManifestDownloadTask()); mQueueSet.start(); this.mRunable = r; } - public class Runable{ - public void run(){} + public class Runable { + public void run() { + } } - public void cancelDownload(){ + public void cancelDownload() { new FileDownloader().pauseAll(); } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibManifestResponse.java b/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibManifestResponse.java index b1956664..fd46d75f 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibManifestResponse.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibManifestResponse.java @@ -4,7 +4,7 @@ public class AuthlibManifestResponse { String lastest_build_number; Artifact[] artifacts; - class Artifact{ + class Artifact { public String build_number; public String version; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibVersionResponse.java b/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibVersionResponse.java index 552d362a..b3e3ebe5 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibVersionResponse.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/AuthlibVersionResponse.java @@ -6,7 +6,7 @@ public class AuthlibVersionResponse { String download_url; Checksum checksums; - class Checksum{ + class Checksum { public String sha256; } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/Request.java b/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/Request.java index 72225cd9..d52d7ce3 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/Request.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/download/authlib/Request.java @@ -1,9 +1,6 @@ package com.aof.mcinabox.launcher.download.authlib; -import android.annotation.SuppressLint; import android.content.Context; -import android.os.Handler; -import android.os.Message; import com.aof.mcinabox.R; import com.aof.mcinabox.activity.OldMainActivity; @@ -31,10 +28,8 @@ public class Request { private final static String AUTHLIB_INJECTOR = "authlib-injector"; private final static int REQUEST_DOWNLOAD = 1; private final static int REQUEST_FAILED = 2; - private AuthlibVersionResponse mVersionResponse; private final Context mContext; private final SettingJson mSetting; - private Exception mException; public Request(Context context) { this(context, OldMainActivity.Setting); @@ -61,44 +56,24 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } private void onFailure(Exception e) { - Request.this.mException = e; - Message msg = new Message(); - msg.what = REQUEST_FAILED; - mHandler.sendMessage(msg); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> + DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_error), String.format(mContext.getString(R.string.tips_error), e.getMessage()), mContext.getString(R.string.title_ok), null)); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) { - try { - mVersionResponse = gson.fromJson(response.body().string(), AuthlibVersionResponse.class); - } catch (Exception e) { - e.printStackTrace(); - onFailure(e); - return; - } - Message msg = new Message(); - msg.what = REQUEST_DOWNLOAD; - mHandler.sendMessage(msg); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> { + try { + requestDownload(gson.fromJson(response.body().string(), AuthlibVersionResponse.class)); + } catch (IOException e) { + e.printStackTrace(); + onFailure(e); + } + }); } }); } - @SuppressLint("HandlerLeak") - private final Handler mHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case REQUEST_DOWNLOAD: - requestDownload(mVersionResponse); - break; - case REQUEST_FAILED: - DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_error), String.format(mContext.getString(R.string.tips_error), mException.getMessage()), mContext.getString(R.string.title_ok), null); - break; - } - super.handleMessage(msg); - } - }; - private void requestDownload(AuthlibVersionResponse response) { BaseDownloadTask[] tasks = {DownloadHelper.createDownloadTask(AppManifest.AUTHLIB_INJETOR_JAR, response.download_url, null)}; new DownloadManager(mContext).startDownload(AUTHLIB_INJECTOR, mContext.getString(R.string.tips_downloading_authlib_injector), 1, 0, tasks, null); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/download/support/DownloaderDialog.java b/app/src/main/java/com/aof/mcinabox/launcher/download/support/DownloaderDialog.java index 64256794..c68cf63c 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/download/support/DownloaderDialog.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/download/support/DownloaderDialog.java @@ -16,10 +16,10 @@ import com.aof.mcinabox.utils.dialog.DialogUtils; import com.aof.mcinabox.utils.dialog.support.DialogSupports; -public class DownloaderDialog extends Dialog implements Dialog.OnCancelListener, View.OnClickListener{ +public class DownloaderDialog extends Dialog implements Dialog.OnCancelListener, View.OnClickListener { - private Context mContext; - private DownloadManager mDownloadManager; + private final Context mContext; + private final DownloadManager mDownloadManager; private final static String TAG = "DownloaderDialog"; private Button buttonOK; @@ -43,7 +43,7 @@ public DownloaderDialog(@NonNull Context context, DownloadManager manager) { init(); } - private void init(){ + private void init() { buttonOK = findViewById(R.id.dialog_download_button_ok); buttonCancel = findViewById(R.id.dialog_download_button_cancle); ivFinish = findViewById(R.id.dialog_download_image_finish); @@ -57,7 +57,7 @@ private void init(){ pbTotal = findViewById(R.id.dialog_download_processbar_total); //设置监听器 - for(View v : new View[]{buttonCancel,buttonOK}){ + for (View v : new View[]{buttonCancel, buttonOK}) { v.setOnClickListener(this); } //设置控件属性 @@ -75,48 +75,48 @@ public void onCancel(DialogInterface dialog) { @Override public void onClick(View v) { - if(v == buttonOK){ + if (v == buttonOK) { dismiss(); } - if(v == buttonCancel){ - DialogUtils.createBothChoicesDialog(mContext,mContext.getString(R.string.title_warn),mContext.getString(R.string.tips_are_you_sure_to_cancel_download_task),mContext.getString(R.string.title_ok),mContext.getString(R.string.title_cancel),new DialogSupports(){ + if (v == buttonCancel) { + DialogUtils.createBothChoicesDialog(mContext, mContext.getString(R.string.title_warn), mContext.getString(R.string.tips_are_you_sure_to_cancel_download_task), mContext.getString(R.string.title_ok), mContext.getString(R.string.title_cancel), new DialogSupports() { @Override - public void runWhenPositive(){ + public void runWhenPositive() { DownloaderDialog.this.cancel(); } }); } } - public DownloaderDialog setId(String id){ + public DownloaderDialog setId(String id) { this.textVersionId.setText(id); return this; } - public DownloaderDialog setTitle(String title){ + public DownloaderDialog setTitle(String title) { this.textProgressName.setText(title); return this; } - public DownloaderDialog setTotalProgress(int all, int current){ - this.pbTotal.setProgress(current *100 / all); + public DownloaderDialog setTotalProgress(int all, int current) { + this.pbTotal.setProgress(current * 100 / all); this.textProgress.setText(current + "/" + all); return this; } - public DownloaderDialog setTotalProgress(int progress){ + public DownloaderDialog setTotalProgress(int progress) { this.pbTotal.setProgress(progress); return this; } - public DownloaderDialog setCurrentProgress(int progress){ + public DownloaderDialog setCurrentProgress(int progress) { this.pbCurrent.setProgress(progress); this.textCurrentPrecentage.setText(progress + "%"); return this; } - public DownloaderDialog setFinished(){ + public DownloaderDialog setFinished() { this.ivFinish.setVisibility(View.VISIBLE); this.textProgress.setVisibility(View.GONE); this.textProgressName.setText(mContext.getString(R.string.tips_download_finished)); @@ -127,27 +127,27 @@ public DownloaderDialog setFinished(){ return this; } - public DownloaderDialog setFailed(){ + public DownloaderDialog setFailed() { this.textProgressName.setText(mContext.getString(R.string.tips_download_failed)); return this; } - public DownloaderDialog restoreStat(){ + public DownloaderDialog restoreStat() { this.ivFinish.setVisibility(View.GONE); this.textProgress.setVisibility(View.VISIBLE); setTitle(""); setId(""); setCurrentProgress(0); - setTotalProgress(1,0); - return this; + setTotalProgress(1, 0); + return this; } - public DownloaderDialog setSpeed(String speed){ + public DownloaderDialog setSpeed(String speed) { this.textSpeed.setText(speed); return this; } - public DownloaderDialog setFileName(String name){ + public DownloaderDialog setFileName(String name) { this.textFileName.setText(name); return this; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/download/support/UrlSource.java b/app/src/main/java/com/aof/mcinabox/launcher/download/support/UrlSource.java index 2935a051..1411aad6 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/download/support/UrlSource.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/download/support/UrlSource.java @@ -7,7 +7,7 @@ public class UrlSource { - public HashMap> SourceMap; + public HashMap> SourceMap; public final static String TYPE_VERSION_MANIFEST = "version_manifest_json"; public final static String TYPE_VERSION_JSON = "version_json"; @@ -20,71 +20,72 @@ public class UrlSource { public final static String TYPE_LITELOADER_VERSION_JSON = "liteloader_version_json"; public final static String TYPE_AUTHLIB_INJECTOR_JAR = "authlib_injector_jar"; - public UrlSource(){ - initSourceMap(new String[][] { + public UrlSource() { + initSourceMap(new String[][]{ //官方下载源 - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_VERSION_MANIFEST,"https://launchermeta.mojang.com/mc/game/version_manifest.json"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_VERSION_JSON,"https://launchermeta.mojang.com"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_VERSION_JAR,"https://launcher.mojang.com"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_ASSETS_INDEX_JSON,"https://launchermeta.mojang.com"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_ASSETS_OBJS,"http://resources.download.minecraft.net"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_LIBRARIES,"https://libraries.minecraft.net"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_FORGE_LIBRARIES,"https://files.minecraftforge.net/maven"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_LITELOADER_VERSION_JSON,"http://dl.liteloader.com/versions/versions.json"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_AUTHLIB_INJECTOR_JAR,"https://authlib-injector.yushi.moe/artifact/latest.json"}, - {SettingJson.DOWNLOAD_SOURCE_OFFICIAL,TYPE_FABRIC_LIBRARIES,"https://maven.fabricmc.net"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_VERSION_MANIFEST, "https://launchermeta.mojang.com/mc/game/version_manifest.json"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_VERSION_JSON, "https://launchermeta.mojang.com"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_VERSION_JAR, "https://launcher.mojang.com"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_ASSETS_INDEX_JSON, "https://launchermeta.mojang.com"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_ASSETS_OBJS, "http://resources.download.minecraft.net"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_LIBRARIES, "https://libraries.minecraft.net"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_FORGE_LIBRARIES, "https://files.minecraftforge.net/maven"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_LITELOADER_VERSION_JSON, "http://dl.liteloader.com/versions/versions.json"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_AUTHLIB_INJECTOR_JAR, "https://authlib-injector.yushi.moe/artifact/latest.json"}, + {SettingJson.DOWNLOAD_SOURCE_OFFICIAL, TYPE_FABRIC_LIBRARIES, "https://maven.fabricmc.net"}, //BMCLAPI下载源 - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_VERSION_MANIFEST,"https://bmclapi2.bangbang93.com/mc/game/version_manifest.json"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_VERSION_JSON,"https://bmclapi2.bangbang93.com"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_VERSION_JAR,"https://bmclapi2.bangbang93.com"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_ASSETS_INDEX_JSON,"https://bmclapi2.bangbang93.com"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_ASSETS_OBJS,"https://bmclapi2.bangbang93.com/assets"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_LIBRARIES,"https://bmclapi2.bangbang93.com/maven"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_FORGE_LIBRARIES,"https://bmclapi2.bangbang93.com/maven"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_LITELOADER_VERSION_JSON,"https://bmclapi.bangbang93.com/maven/com/mumfrey/liteloader/versions.json"}, - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_AUTHLIB_INJECTOR_JAR,"https://bmclapi2.bangbang93.com/mirrors/authlib-injector/artifact/latest.json"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_VERSION_MANIFEST, "https://bmclapi2.bangbang93.com/mc/game/version_manifest.json"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_VERSION_JSON, "https://bmclapi2.bangbang93.com"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_VERSION_JAR, "https://bmclapi2.bangbang93.com"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_ASSETS_INDEX_JSON, "https://bmclapi2.bangbang93.com"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_ASSETS_OBJS, "https://bmclapi2.bangbang93.com/assets"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_LIBRARIES, "https://bmclapi2.bangbang93.com/maven"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_FORGE_LIBRARIES, "https://bmclapi2.bangbang93.com/maven"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_LITELOADER_VERSION_JSON, "https://bmclapi.bangbang93.com/maven/com/mumfrey/liteloader/versions.json"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_AUTHLIB_INJECTOR_JAR, "https://bmclapi2.bangbang93.com/mirrors/authlib-injector/artifact/latest.json"}, //TODO: BMCLAPI 截至目前,没有提供Fabric的镜像 - {SettingJson.DOWNLOAD_SOURCE_BMCLAPI,TYPE_AUTHLIB_INJECTOR_JAR,"https://authlib-injector.yushi.moe/artifact/latest.json"}, + {SettingJson.DOWNLOAD_SOURCE_BMCLAPI, TYPE_AUTHLIB_INJECTOR_JAR, "https://authlib-injector.yushi.moe/artifact/latest.json"}, //MCBBS下载源 - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_VERSION_MANIFEST,"https://download.mcbbs.net/mc/game/version_manifest.json"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_VERSION_JSON,"https://download.mcbbs.net"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_VERSION_JAR,"https://download.mcbbs.net"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_ASSETS_INDEX_JSON,"https://download.mcbbs.net"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_ASSETS_OBJS,"https://download.mcbbs.net/assets"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_LIBRARIES,"https://download.mcbbs.net/maven"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_FORGE_LIBRARIES,"https://download.mcbbs.net/maven"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_LITELOADER_VERSION_JSON,"https://download.mcbbs.net/maven/com/mumfrey/liteloader/versions.json"}, - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_AUTHLIB_INJECTOR_JAR,"https://download.mcbbs.net/mirrors/authlib-injector/artifact/latest.json"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_VERSION_MANIFEST, "https://download.mcbbs.net/mc/game/version_manifest.json"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_VERSION_JSON, "https://download.mcbbs.net"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_VERSION_JAR, "https://download.mcbbs.net"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_ASSETS_INDEX_JSON, "https://download.mcbbs.net"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_ASSETS_OBJS, "https://download.mcbbs.net/assets"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_LIBRARIES, "https://download.mcbbs.net/maven"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_FORGE_LIBRARIES, "https://download.mcbbs.net/maven"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_LITELOADER_VERSION_JSON, "https://download.mcbbs.net/maven/com/mumfrey/liteloader/versions.json"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_AUTHLIB_INJECTOR_JAR, "https://download.mcbbs.net/mirrors/authlib-injector/artifact/latest.json"}, //TODO: MCBBS 截至目前,没有提供Fabric的镜像 - {SettingJson.DOWNLOAD_SOURCE_MCBBS,TYPE_AUTHLIB_INJECTOR_JAR,"https://authlib-injector.yushi.moe/artifact/latest.json"}, + {SettingJson.DOWNLOAD_SOURCE_MCBBS, TYPE_AUTHLIB_INJECTOR_JAR, "https://authlib-injector.yushi.moe/artifact/latest.json"}, }); } //String ... {{sourceName,Type,Url}, ...} - private void initSourceMap(String[][] originMap){ + private void initSourceMap(String[][] originMap) { SourceMap = new HashMap<>(); - for(String[] couple : originMap){ - if(SourceMap.containsKey(couple[0])){ - Objects.requireNonNull(SourceMap.get(couple[0])).put(couple[1],couple[2]); - }else{ - HashMap tmp = new HashMap<>(); - tmp.put(couple[1],couple[2]); - SourceMap.put(couple[0],tmp); + for (String[] couple : originMap) { + if (SourceMap.containsKey(couple[0])) { + Objects.requireNonNull(SourceMap.get(couple[0])).put(couple[1], couple[2]); + } else { + HashMap tmp = new HashMap<>(); + tmp.put(couple[1], couple[2]); + SourceMap.put(couple[0], tmp); } } } - public String getSourceUrl(String sourceName,String type){ + public String getSourceUrl(String sourceName, String type) { return Objects.requireNonNull(SourceMap.get(sourceName)).get(type); } - public String getFileUrl(String originUrl,String sourceName, String type){ + + public String getFileUrl(String originUrl, String sourceName, String type) { String convertedUrl; StringBuilder Str1 = new StringBuilder(); - String Str2 = getSourceUrl(SettingJson.DOWNLOAD_SOURCE_OFFICIAL,type); - for(int i = Str2.length(); i < originUrl.length() ; i++){ + String Str2 = getSourceUrl(SettingJson.DOWNLOAD_SOURCE_OFFICIAL, type); + for (int i = Str2.length(); i < originUrl.length(); i++) { Str1.append(originUrl.charAt(i)); } - convertedUrl = getSourceUrl(sourceName,type) + Str1; + convertedUrl = getSourceUrl(sourceName, type) + Str1; return convertedUrl; } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/lang/LangManager.java b/app/src/main/java/com/aof/mcinabox/launcher/lang/LangManager.java index 51fe80dd..776a482a 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/lang/LangManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/lang/LangManager.java @@ -18,44 +18,44 @@ public class LangManager { private final Context mContext; - public LangManager(Context context){ + public LangManager(Context context) { super(); this.mContext = context; } - public boolean fitSystemLang(){ - if(hasFitted){ + public boolean fitSystemLang() { + if (hasFitted) { hasFitted = false; return true; } - SharedPreferences sp = mContext.getSharedPreferences(spFileName,spMode); + SharedPreferences sp = mContext.getSharedPreferences(spFileName, spMode); String langData = sp.getString(sp_lang_tag, LanguageUtils.TAG_SYSTEM); - LanguageUtils.switchLang( mContext,LanguageUtils.getLocaleFromConfig(langData)); + LanguageUtils.switchLang(mContext, LanguageUtils.getLocaleFromConfig(langData)); hasFitted = true; Log.e(TAG, "fitted"); restartActivity(); return false; } - public void switchLang(@NonNull String tag){ + public void switchLang(@NonNull String tag) { boolean included = false; - for(String str : LanguageUtils.LANG_TAGS){ + for (String str : LanguageUtils.LANG_TAGS) { if (str.equals(tag)) { included = true; break; } } - if(!included){ + if (!included) { return; } - LanguageUtils.switchLang(mContext,LanguageUtils.getLocaleFromConfig(tag)); - SharedPreferences.Editor editor = mContext.getSharedPreferences(spFileName,spMode).edit(); - editor.putString(sp_lang_tag,tag); + LanguageUtils.switchLang(mContext, LanguageUtils.getLocaleFromConfig(tag)); + SharedPreferences.Editor editor = mContext.getSharedPreferences(spFileName, spMode).edit(); + editor.putString(sp_lang_tag, tag); editor.apply(); restartActivity(); } - private void restartActivity(){ + private void restartActivity() { OldMainActivity.CURRENT_ACTIVITY.get().restarter(); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/lang/LanguageDialog.java b/app/src/main/java/com/aof/mcinabox/launcher/lang/LanguageDialog.java index 21615ec6..f136f72d 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/lang/LanguageDialog.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/lang/LanguageDialog.java @@ -14,10 +14,10 @@ public class LanguageDialog extends Dialog { private ListView listLanguages; - private Context mContext; - private LangManager mManager; + private final Context mContext; + private final LangManager mManager; - public LanguageDialog(Context context){ + public LanguageDialog(Context context) { super(context); this.mContext = context; this.mManager = new LangManager(mContext); @@ -25,7 +25,7 @@ public LanguageDialog(Context context){ initUI(); } - private void initUI(){ + private void initUI() { listLanguages = findViewById(R.id.dialog_listview_languages); listLanguages.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, Arrays.asList(LanguageUtils.LANG_TAGS))); listLanguages.setOnItemClickListener((adapterView, view, pos, l) -> { @@ -34,7 +34,7 @@ private void initUI(){ }); } - private void ChangeLauncherLanguage(String language){ + private void ChangeLauncherLanguage(String language) { mManager.switchLang(language); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/lang/support/LanguageUtils.java b/app/src/main/java/com/aof/mcinabox/launcher/lang/support/LanguageUtils.java index 6091f146..614e742a 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/lang/support/LanguageUtils.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/lang/support/LanguageUtils.java @@ -27,9 +27,9 @@ public class LanguageUtils { public final static String[] LANG_TAGS = new String[]{TAG_SYSTEM, TAG_ENGLISH_EN, TAG_JAPANESE_JA, TAG_CHINESE_ZH_CN, TAG_CHINESE_ZH_TW, TAG_SPANISH_ES, TAG_PORTUGUESE_RU, TAG_BRAZILIAN_PT_BR, TAG_KOREAN_KO_KR}; - public static Locale getLocaleFromConfig(String config){ + public static Locale getLocaleFromConfig(String config) { Locale mLocale; - switch (config){ + switch (config) { case TAG_SYSTEM: mLocale = Locale.getDefault(); break; @@ -64,8 +64,8 @@ public static Locale getLocaleFromConfig(String config){ return mLocale; } - public static void switchLang(Context context, Locale locale){ - if(locale == null){ + public static void switchLang(Context context, Locale locale) { + if (locale == null) { return; } Resources resources = context.getResources(); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/launch/Activity/BoatStartupActivity.java b/app/src/main/java/com/aof/mcinabox/launcher/launch/Activity/BoatStartupActivity.java index 95cfd1bf..fcaca60f 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/launch/Activity/BoatStartupActivity.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/launch/Activity/BoatStartupActivity.java @@ -15,13 +15,12 @@ import com.aof.mcinabox.utils.DisplayUtils; import java.util.Timer; -import java.util.TimerTask; import cosine.boat.BoatActivity; public class BoatStartupActivity extends BoatActivity implements Client { - private int[] grabbedPointer = new int[]{0, 0}; + private final int[] grabbedPointer = new int[]{0, 0}; private boolean grabbed = false; private ImageView cursorIcon; private final static int CURSOR_SIZE = 16; //dp @@ -46,18 +45,18 @@ public void run() { @Override public void setKey(int keyCode, boolean pressed) { - this.setKey(keyCode,0,pressed); + this.setKey(keyCode, 0, pressed); } @Override public void setPointerInc(int xInc, int yInc) { - if(!grabbed){ + if (!grabbed) { int x, y; x = grabbedPointer[0] + xInc; y = grabbedPointer[1] + yInc; - if(x >= 0 && x <= screenWidth) + if (x >= 0 && x <= screenWidth) grabbedPointer[0] += xInc; - if(y >= 0 && y <= screenHeight) + if (y >= 0 && y <= screenHeight) grabbedPointer[1] += yInc; setPointer(grabbedPointer[0], grabbedPointer[1]); this.cursorIcon.post(new Runnable() { @@ -67,15 +66,15 @@ public void run() { cursorIcon.setY(grabbedPointer[1]); } }); - }else{ + } else { setPointer(getPointer()[0] + xInc, getPointer()[1] + yInc); } } @Override - public void setPointer(int x, int y){ + public void setPointer(int x, int y) { super.setPointer(x, y); - if(!grabbed){ + if (!grabbed) { this.cursorIcon.post(new Runnable() { @Override public void run() { @@ -100,10 +99,10 @@ public void addView(View v) { @Override public void typeWords(String str) { - if(str == null) return; - for(int i = 0; i < str.length(); i++){ - setKey(0, str.charAt(i),true); - setKey(0, str.charAt(i),false); + if (str == null) return; + for (int i = 0; i < str.length(); i++) { + setKey(0, str.charAt(i), true); + setKey(0, str.charAt(i), false); } } @@ -119,12 +118,12 @@ public int[] getLoosenPointer() { @Override public ViewGroup getViewsParent() { - return (binding != null)?binding.getRoot():null; + return (binding != null) ? binding.getRoot() : null; } @Override public View getSurfaceLayerView() { - return (binding != null)?binding.getRoot().findViewById(R.id.surface_view):null; + return (binding != null) ? binding.getRoot().findViewById(R.id.surface_view) : null; } @Override @@ -133,10 +132,10 @@ public boolean isGrabbed() { } @Override - public void setGrabCursor(boolean isGrabbed){ + public void setGrabCursor(boolean isGrabbed) { super.setGrabCursor(isGrabbed); this.grabbed = isGrabbed; - if(!isGrabbed){ + if (!isGrabbed) { setPointer(grabbedPointer[0], grabbedPointer[1]); cursorIcon.post(new Runnable() { @Override @@ -144,7 +143,7 @@ public void run() { cursorIcon.setVisibility(View.VISIBLE); } }); - }else if(cursorIcon.getVisibility() == View.VISIBLE) { + } else if (cursorIcon.getVisibility() == View.VISIBLE) { cursorIcon.post(new Runnable() { @Override public void run() { @@ -203,5 +202,4 @@ public boolean dispatchGenericMotionEvent(MotionEvent event) { } - } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/launch/LaunchManager.java b/app/src/main/java/com/aof/mcinabox/launcher/launch/LaunchManager.java index 7af70cb5..e30a38d8 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/launch/LaunchManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/launch/LaunchManager.java @@ -2,23 +2,17 @@ import android.content.Context; import android.content.Intent; -import android.view.KeyEvent; -import android.view.MotionEvent; + import com.aof.mcinabox.R; -import com.aof.mcinabox.gamecontroller.client.Client; -import com.aof.mcinabox.gamecontroller.controller.HardwareController; -import com.aof.mcinabox.gamecontroller.controller.VirtualController; import com.aof.mcinabox.launcher.launch.Activity.BoatStartupActivity; import com.aof.mcinabox.launcher.launch.support.AsyncManager; import com.aof.mcinabox.launcher.launch.support.argsmaker.BoatArgsMaker; import com.aof.mcinabox.launcher.setting.support.SettingJson; import com.aof.mcinabox.utils.dialog.DialogUtils; import com.aof.mcinabox.utils.dialog.support.TaskDialog; -import java.util.Timer; -import java.util.TimerTask; -import cosine.boat.BoatActivity; + import cosine.boat.BoatArgs; -import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.KEYMAP_TO_X; + import static cosine.boat.BoatActivity.EXTRA_BOAT_ARGS; public class LaunchManager { @@ -70,7 +64,7 @@ public void launchMinecraft(SettingJson setting, int i) { BoatArgs args = (BoatArgs) maker.getStartArgs(); brige_exitWithSuccess(); BoatStartupActivity.attachControllerInterface(); - mContext.startActivity(new Intent(mContext, BoatStartupActivity.class).putExtra(EXTRA_BOAT_ARGS, (BoatArgs)maker.getStartArgs()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + mContext.startActivity(new Intent(mContext, BoatStartupActivity.class).putExtra(EXTRA_BOAT_ARGS, (BoatArgs) maker.getStartArgs()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); break; } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/ArgsMaker.java b/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/ArgsMaker.java index a079e463..b46a8b50 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/ArgsMaker.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/ArgsMaker.java @@ -2,5 +2,6 @@ public interface ArgsMaker { Object getStartArgs(); + void setup(String id); } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/BoatArgsMaker.java b/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/BoatArgsMaker.java index 8a11f0a5..c154dc4b 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/BoatArgsMaker.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/launch/support/argsmaker/BoatArgsMaker.java @@ -25,7 +25,6 @@ import cosine.boat.BoatArgs; -import static com.aof.mcinabox.gamecontroller.definitions.manifest.AppManifest.BOAT_CACHE_HOME; import static com.aof.mcinabox.gamecontroller.definitions.manifest.AppManifest.MCINABOX_VERSION_NAME; public class BoatArgsMaker implements ArgsMaker { @@ -136,7 +135,7 @@ private String[] getArgs() { String JVM_Xmx = "-Xmx" + mSetting.getConfigurations().getMaxMemory() + "m"; String JVM_Xms = "-Xms128m"; String JVM_minecraft_launcher_brand = "-Dminecraft.launcher.brand=" + mContext.getString(R.string.app_name); - String JVM_minecraft_launcher_version = "-Dminecraft.launcher.version=" +MCINABOX_VERSION_NAME; + String JVM_minecraft_launcher_version = "-Dminecraft.launcher.version=" + MCINABOX_VERSION_NAME; String JVM_java_io_tmpdir = "-Djava.io.tmpdir=" + mContext.getCacheDir().getAbsolutePath(); String JVM_java_library_path = this.getJava_library_path(); String JVM_org_lwjgl_util_debug = "-Dorg.lwjgl.util.Debug=true"; @@ -162,13 +161,13 @@ private String[] getArgs() { tmp.add(JVM_java_library_path); //tmp.add(JVM_org_lwjgl_util_debug); //s tmp.add(JVM_org_lwjgl_util_debugloader); - if(JVM_ExtraArgs != null && JVM_ExtraArgs.trim().length()!= 0) + if (JVM_ExtraArgs != null && JVM_ExtraArgs.trim().length() != 0) tmp.addAll(Arrays.asList(JVM_ExtraArgs.split(" "))); tmp.add(JVM_ClassPath); tmp.add(JVM_ClassPath_info); if (AuthlibInjectorArgs != null) tmp.addAll(Arrays.asList(AuthlibInjectorArgs.split(" "))); tmp.addAll(Arrays.asList(Minecraft_MainClass.split(" "))); - if(MinecraftExtraArgs != null && MinecraftExtraArgs.trim().length()!= 0) + if (MinecraftExtraArgs != null && MinecraftExtraArgs.trim().length() != 0) tmp.addAll(Arrays.asList(MinecraftExtraArgs.split(" "))); tmp.addAll(Arrays.asList(MinecraftWindowArgs.split(" "))); tmp.addAll(Arrays.asList(Minecraft_Args.split(" "))); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/runtime/RuntimeManager.java b/app/src/main/java/com/aof/mcinabox/launcher/runtime/RuntimeManager.java index b278fc9b..9eebcefb 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/runtime/RuntimeManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/runtime/RuntimeManager.java @@ -30,53 +30,26 @@ import java.util.Objects; public class RuntimeManager { - private final static String TAG = "RuntimeManager"; - private static String filename; /** * 【从路径安装运行库】 **/ public static void installRuntimeFromPath(final Context context, String globalPath) { - final TaskDialog mDialog = DialogUtils.createTaskDialog(context, "", "", false); mDialog.show(); - @SuppressLint("HandlerLeak") final Handler mHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case 3: - mDialog.setTotalTaskName(context.getString(R.string.tips_installing_runtime)); - break; - case 4: - Toast.makeText(OldMainActivity.CURRENT_ACTIVITY.get(), OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_notfound), Toast.LENGTH_SHORT).show(); - mDialog.dismiss(); - break; - case 6: - Toast.makeText(OldMainActivity.CURRENT_ACTIVITY.get(), OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_install_successed), Toast.LENGTH_SHORT).show(); - mDialog.dismiss(); - break; - case 7: - Toast.makeText(OldMainActivity.CURRENT_ACTIVITY.get(), OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_install_failed) + " " + OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_install_fail_exeable), Toast.LENGTH_SHORT).show(); - mDialog.dismiss(); - break; - case 8: - mDialog.setTotalTaskName(context.getString(R.string.tips_unzipping_runtime_pack)); - mDialog.setCurrentTaskName(filename); - break; - } - super.handleMessage(msg); - } - }; final String mpackagePath = globalPath; new Thread() { @Override public void run() { - sendMsg(3); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> mDialog.setTotalTaskName(context.getString(R.string.tips_installing_runtime))); File packageFile = new File(mpackagePath); if (!packageFile.exists()) { - sendMsg(4); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> { + Toast.makeText(OldMainActivity.CURRENT_ACTIVITY.get(), OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_notfound), Toast.LENGTH_SHORT).show(); + mDialog.dismiss(); + }); return; } else { if (packageFile.isDirectory()) { @@ -88,29 +61,26 @@ public void run() { if (!dir.exists()) { FileTool.makeFolder(dir.getAbsolutePath()); } - BoatUtils.extractTarXZ(mpackagePath, AppManifest.BOAT_RUNTIME_HOME, new BoatUtils.CompressCallback() { - @Override - public void onFileCompressing(File file) { - if(file != null){ - Message msg = new Message(); - msg.what = 8; - filename = file.getName(); - mHandler.sendMessage(msg); - } + BoatUtils.extractTarXZ(mpackagePath, AppManifest.BOAT_RUNTIME_HOME, file -> { + if (file != null) { + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> { + mDialog.setTotalTaskName(context.getString(R.string.tips_unzipping_runtime_pack)); + mDialog.setCurrentTaskName(file.getName()); + }); } }); if (BoatUtils.setExecutable(AppManifest.BOAT_RUNTIME_HOME)) { - sendMsg(6); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> { + Toast.makeText(OldMainActivity.CURRENT_ACTIVITY.get(), OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_install_successed), Toast.LENGTH_SHORT).show(); + mDialog.dismiss(); + }); } else { - sendMsg(7); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> { + Toast.makeText(OldMainActivity.CURRENT_ACTIVITY.get(), OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_install_failed) + " " + OldMainActivity.CURRENT_ACTIVITY.get().getString(R.string.tips_runtime_install_fail_exeable), Toast.LENGTH_SHORT).show(); + mDialog.dismiss(); + }); } } - - public void sendMsg(int what) { - Message msg = new Message(); - msg.what = what; - mHandler.sendMessage(msg); - } }.start(); } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/ConditionResolve.java b/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/ConditionResolve.java index f449a916..5def56de 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/ConditionResolve.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/ConditionResolve.java @@ -4,51 +4,51 @@ public class ConditionResolve { - public static boolean handleConditionWithLauncherVersion(int launcherversion, String condition){ + public static boolean handleConditionWithLauncherVersion(int launcherversion, String condition) { //>0 <1|>2 <3 String[] conditions = condition.split(Definitions.RUNTIME_CONDITION_SPILT); - for(String str : conditions){ - if(checkConditionWithLauncherVersion(launcherversion,str)){ + for (String str : conditions) { + if (checkConditionWithLauncherVersion(launcherversion, str)) { return true; } } return false; } - private static boolean checkConditionWithLauncherVersion(int launcherversion, String handledcondition){ + private static boolean checkConditionWithLauncherVersion(int launcherversion, String handledcondition) { boolean result = true; - for(int a = 0; a < handledcondition.length(); a++){ - if(handledcondition.charAt(a) == '<'){ + for (int a = 0; a < handledcondition.length(); a++) { + if (handledcondition.charAt(a) == '<') { ArrayList nums = new ArrayList<>(); - for(int b = a + 1; b < handledcondition.length(); b++){ - if(handledcondition.charAt(b) != ' '){ + for (int b = a + 1; b < handledcondition.length(); b++) { + if (handledcondition.charAt(b) != ' ') { nums.add(String.valueOf(handledcondition.charAt(b))); } } StringBuilder numstr = new StringBuilder(); - for(String str : nums){ + for (String str : nums) { numstr.append(str); } int num = Integer.parseInt(numstr.toString()); - if(launcherversion >= num){ + if (launcherversion >= num) { result = false; } } - if(handledcondition.charAt(a) == '>'){ + if (handledcondition.charAt(a) == '>') { ArrayList nums = new ArrayList<>(); - for(int b = a + 1; b < handledcondition.length(); b++){ - if(handledcondition.charAt(b) != ' '){ + for (int b = a + 1; b < handledcondition.length(); b++) { + if (handledcondition.charAt(b) != ' ') { nums.add(String.valueOf(handledcondition.charAt(b))); } } StringBuilder numstr = new StringBuilder(); - for(String str : nums){ + for (String str : nums) { numstr.append(str); } int num = Integer.parseInt(numstr.toString()); - if(launcherversion <= num){ + if (launcherversion <= num) { result = false; } } @@ -56,10 +56,10 @@ private static boolean checkConditionWithLauncherVersion(int launcherversion, St return result; } - public static boolean handleConditionWithMinecraftVersion(String versionId, String condition){ + public static boolean handleConditionWithMinecraftVersion(String versionId, String condition) { String[] conditions = condition.split(Definitions.RUNTIME_CONDITION_SPILT); - for(String str : conditions){ - if(str.equals(versionId)){ + for (String str : conditions) { + if (str.equals(versionId)) { return true; } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/RuntimePackInfo.java b/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/RuntimePackInfo.java index 540c48d8..ff6d3067 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/RuntimePackInfo.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/runtime/support/RuntimePackInfo.java @@ -82,12 +82,12 @@ public Manifest setSo(String so) { return this; } - public Manifest setConditionInfo(String info){ + public Manifest setConditionInfo(String info) { this.condition_info = info; return this; } - public Manifest setSystemEnv(Map env){ + public Manifest setSystemEnv(Map env) { this.systemEnv = env; return this; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/setting/SettingManager.java b/app/src/main/java/com/aof/mcinabox/launcher/setting/SettingManager.java index 2b0b2167..3b81719e 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/setting/SettingManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/setting/SettingManager.java @@ -23,19 +23,21 @@ public class SettingManager { - private Context mContext; - private File settingFile; + private final Context mContext; + private final File settingFile; private Timer mTimer; private final static String TAG = "SettingManager"; - public SettingManager(Context context){ + public SettingManager(Context context) { this.mContext = context; settingFile = new File(Objects.requireNonNull(mContext.getExternalFilesDir("mcinabox")).getAbsolutePath() + "/mcinabox.json"); } - /**【读入mcinabox.json】**/ - public SettingJson getSettingFromFile(){ + /** + * 【读入mcinabox.json】 + **/ + public SettingJson getSettingFromFile() { SettingJson settingModel; if (!settingFile.exists()) { @@ -53,15 +55,17 @@ public SettingJson getSettingFromFile(){ } } - if(settingModel == null){ + if (settingModel == null) { settingModel = new SettingJson(); } return settingModel; } - /**【保存mcinabox.json文件】**/ - public void saveSettingToFile(){ + /** + * 【保存mcinabox.json文件】 + **/ + public void saveSettingToFile() { Gson gson = new Gson(); String jsonString = gson.toJson(OldMainActivity.Setting); try { @@ -71,17 +75,17 @@ public void saveSettingToFile(){ out.close(); } catch (IOException e) { e.printStackTrace(); - Log.e(TAG,"save failed."); + Log.e(TAG, "save failed."); } } - public void startChecking(){ - if(mTimer == null){ + public void startChecking() { + if (mTimer == null) { mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { - SettingChecker sc = new SettingChecker(mContext,null,null); + SettingChecker sc = new SettingChecker(mContext, null, null); sc.checkIfChoseUser(); sc.checkIfInstallGame(); sc.checkIfInstallRuntime(); @@ -89,12 +93,12 @@ public void run() { sc.checkIfDisableFileCheck(); sc.checkAuthlibInjector(); } - },0,500); + }, 0, 500); } } - public void stopChecking(){ - if(mTimer != null){ + public void stopChecking() { + if (mTimer != null) { mTimer.cancel(); mTimer = null; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/setting/support/SettingJson.java b/app/src/main/java/com/aof/mcinabox/launcher/setting/support/SettingJson.java index 23cb0b92..462e66be 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/setting/support/SettingJson.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/setting/support/SettingJson.java @@ -55,7 +55,7 @@ public class Configurations { private boolean enableDebug; //启用调试 private boolean enableAutoMemory; //启用自动内存设定 - public Configurations(){ + public Configurations() { super(); } @@ -69,11 +69,11 @@ public Configurations setJavaArgs(String javaArgs) { return this; } - public boolean isEnableDebug(){ + public boolean isEnableDebug() { return enableDebug; } - public Configurations setDebug(boolean b){ + public Configurations setDebug(boolean b) { this.enableDebug = b; return this; } @@ -114,48 +114,48 @@ public Configurations setNotCheckPlatform(boolean b) { return this; } - public boolean isNotCheckTipper(){ + public boolean isNotCheckTipper() { return notCheckTipper; } - public Configurations setNotCheckTipper(boolean b){ + public Configurations setNotCheckTipper(boolean b) { this.notCheckTipper = b; return this; } - public Configurations setAlwaysChoiceRuntimeMainfest(boolean b){ + public Configurations setAlwaysChoiceRuntimeMainfest(boolean b) { this.alwaysChoiceRuntimeManifest = b; return this; } - public boolean isAlwaysChoiceRuntimeManifest(){ + public boolean isAlwaysChoiceRuntimeManifest() { return this.alwaysChoiceRuntimeManifest; } - public Configurations setNotCheckForge(boolean b){ + public Configurations setNotCheckForge(boolean b) { this.notCheckForge = b; return this; } - public boolean isNotCheckForge(){ + public boolean isNotCheckForge() { return this.notCheckForge; } - public Configurations setAutoMemory(boolean b){ + public Configurations setAutoMemory(boolean b) { this.enableAutoMemory = b; return this; } - public boolean isEnableAutoMemory(){ + public boolean isEnableAutoMemory() { return this.enableAutoMemory; } - public Configurations setNotCheckOptions(boolean b){ + public Configurations setNotCheckOptions(boolean b) { this.notCheckOptions = b; return this; } - public boolean isNotCheckOptions(){ + public boolean isNotCheckOptions() { return this.notCheckOptions; } @@ -174,7 +174,7 @@ public class Account { String serverName; boolean selected; //是否被选中 - public Account(){ + public Account() { super(); } @@ -307,20 +307,20 @@ public SettingJson setGameDir(String dir) { return this; } - public boolean isBackgroundAutoSwitch(){ + public boolean isBackgroundAutoSwitch() { return this.backgroundAutoSwitch; } - public SettingJson setBackgroundAutoSwitch(boolean b){ + public SettingJson setBackgroundAutoSwitch(boolean b) { this.backgroundAutoSwitch = b; return this; } - public boolean isFullscreen(){ + public boolean isFullscreen() { return this.fullscreen; } - public SettingJson setFullscreen(boolean b){ + public SettingJson setFullscreen(boolean b) { this.fullscreen = b; return this; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/tipper/Tipper.java b/app/src/main/java/com/aof/mcinabox/launcher/tipper/Tipper.java index 2c729cef..df2c87c0 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/tipper/Tipper.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/tipper/Tipper.java @@ -18,7 +18,7 @@ public class Tipper { - private Context mContext; + private final Context mContext; private ListView listTipper; private BubbleLayout bubbleTipper; private PopupWindow popupWindow; @@ -39,7 +39,7 @@ private void init() { * 【在View下方显示Tipper】 **/ public void showTipper(View v, List list) { - if(list == null || list.size() == 0){ + if (list == null || list.size() == 0) { return; } TipperListAdapter tipperListAdapter = new TipperListAdapter(mContext, list); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/tipper/TipperManager.java b/app/src/main/java/com/aof/mcinabox/launcher/tipper/TipperManager.java index 3378bc22..c9ea62f5 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/tipper/TipperManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/tipper/TipperManager.java @@ -16,15 +16,15 @@ public class TipperManager { private final static String TAG = "TipperManager"; - private Tipper mTipper; + private final Tipper mTipper; private ArrayList tipperList; - public TipperManager(Context context){ + public TipperManager(Context context) { mTipper = new Tipper(context); tipperList = new ArrayList<>(); } - public static TipperListBean createTipBean(Context context, int level, String des /*描述*/, TipperRunable runable, int id){ + public static TipperListBean createTipBean(Context context, int level, String des /*描述*/, TipperRunable runable, int id) { return new TipperListBean() .setContext(context) .setTipper_level(level) @@ -33,47 +33,47 @@ public static TipperListBean createTipBean(Context context, int level, String de .setTipper_id(id); } - public void addTip(TipperListBean tipbean){ - for(TipperListBean bean : tipperList){ - if(bean.getTipper_id() == tipbean.getTipper_id()){ + public void addTip(TipperListBean tipbean) { + for (TipperListBean bean : tipperList) { + if (bean.getTipper_id() == tipbean.getTipper_id()) { return; } } tipperList.add(tipbean); } - public void removeTip(int id){ - for(TipperListBean bean : tipperList){ - if(bean.getTipper_id() == id){ + public void removeTip(int id) { + for (TipperListBean bean : tipperList) { + if (bean.getTipper_id() == id) { tipperList.remove(bean); break; } } ArrayList tmp = new ArrayList<>(); - for(TipperListBean bean : tipperList){ - if(bean != null){ + for (TipperListBean bean : tipperList) { + if (bean != null) { tmp.add(bean); } } this.tipperList = tmp; } - public void showTipper(View underView){ + public void showTipper(View underView) { mTipper.showTipper(underView, this.tipperList); } - public void clearTipper(){ + public void clearTipper() { this.tipperList = new ArrayList<>(); } - public int getTipCounts(){ + public int getTipCounts() { return this.tipperList.size(); } - public int getTipCounts(int level){ + public int getTipCounts(int level) { int a = 0; - for(int b = 0; b < tipperList.size(); b++){ - if (tipperList.get(b).getTipper_level() == level){ + for (int b = 0; b < tipperList.size(); b++) { + if (tipperList.get(b).getTipper_level() == level) { a++; } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListAdapter.java b/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListAdapter.java index 418187db..e8b5ed7d 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListAdapter.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListAdapter.java @@ -16,22 +16,25 @@ public class TipperListAdapter extends BaseAdapter { - private List tipperList; + private final List tipperList; private LayoutInflater mLayoutInflater; - public TipperListAdapter(List list){ + + public TipperListAdapter(List list) { tipperList = list; } @Override - public int getCount(){ + public int getCount() { return tipperList.size(); } + @Override - public Object getItem(int position){ + public Object getItem(int position) { return tipperList.get(position); } + @Override - public long getItemId(int position){ + public long getItemId(int position) { return position; } @@ -44,14 +47,14 @@ public TipperListAdapter(Context context, List list) { @Override public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; - if(convertView == null){ + if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.listview_tipper, null); viewHolder = new ViewHolder(); viewHolder.tip = convertView.findViewById(R.id.tipper_info); viewHolder.help = convertView.findViewById(R.id.tipper_help); viewHolder.level = convertView.findViewById(R.id.tipper_level); - switch (tipperList.get(position).getTipper_level()){ + switch (tipperList.get(position).getTipper_level()) { case TipperManager.TIPPER_LEVEL_NOTE: viewHolder.level.setText("N"); viewHolder.level.setTextColor(Color.BLUE); @@ -67,14 +70,14 @@ public View getView(final int position, View convertView, ViewGroup parent) { } convertView.setTag(viewHolder); - }else{ - viewHolder = (ViewHolder)convertView.getTag(); + } else { + viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.context = tipperList.get(position).getContext(); viewHolder.tip.setText(tipperList.get(position).getTipper_info()); viewHolder.help.setOnClickListener(v -> { - if(tipperList.get(position).getTipper_runable() != null){ + if (tipperList.get(position).getTipper_runable() != null) { tipperList.get(position).getTipper_runable().run(); } }); @@ -82,7 +85,7 @@ public View getView(final int position, View convertView, ViewGroup parent) { } - class ViewHolder{ + class ViewHolder { public TextView tip; public TextView level; public ImageButton help; diff --git a/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListBean.java b/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListBean.java index 2f22f7e9..19566078 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListBean.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/tipper/support/TipperListBean.java @@ -27,29 +27,29 @@ public TipperListBean setContext(Context context) { return this; } - public int getTipper_level(){ + public int getTipper_level() { return this.tipper_level; } - public TipperListBean setTipper_level(int level){ + public TipperListBean setTipper_level(int level) { this.tipper_level = level; return this; } - public TipperRunable getTipper_runable(){ - return this.tipper_runable; + public TipperRunable getTipper_runable() { + return this.tipper_runable; } - public TipperListBean setTipper_runable(TipperRunable runable){ + public TipperListBean setTipper_runable(TipperRunable runable) { this.tipper_runable = runable; return this; } - public int getTipper_id(){ + public int getTipper_id() { return this.tipper_id; } - public TipperListBean setTipper_id(int id){ + public TipperListBean setTipper_id(int id) { this.tipper_id = id; return this; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/BaseUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/BaseUI.java index 0845b76a..04c50fff 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/BaseUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/BaseUI.java @@ -7,7 +7,7 @@ public abstract class BaseUI implements UILifecycleCallbacks { public Context mContext; //Method instruction - public BaseUI(Context context){ + public BaseUI(Context context) { super(); setUIContext(context); } @@ -25,28 +25,35 @@ public BaseUI(Context context){ public abstract int getUIVisibility(); //Set Android Context - public void setUIContext(Context context){ + public void setUIContext(Context context) { this.mContext = context; } @Override - public void onCreate(){ } + public void onCreate() { + } @Override - public void onStart(){ } + public void onStart() { + } @Override - public void onResume(){ } + public void onResume() { + } @Override - public void onPause(){ } + public void onPause() { + } @Override - public void onStop(){ } + public void onStop() { + } @Override - public void onDestory(){} + public void onDestory() { + } @Override - public void onRestart(){} + public void onRestart() { + } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/FunctionbarUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/FunctionbarUI.java index 26137c7f..3834402d 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/FunctionbarUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/FunctionbarUI.java @@ -43,10 +43,10 @@ public void onClick(View v) { if (v == buttonGamelist) { OldMainActivity.CURRENT_ACTIVITY.get().switchUIs(OldMainActivity.CURRENT_ACTIVITY.get().mUiManager.uiGamelist, mContext.getString(R.string.title_game_list)); } - if(v == buttonGamedir){ + if (v == buttonGamedir) { OldMainActivity.CURRENT_ACTIVITY.get().switchUIs(OldMainActivity.CURRENT_ACTIVITY.get().mUiManager.uiGamedir, mContext.getString(R.string.title_game_dir)); } - if(v == buttonSetting){ + if (v == buttonSetting) { OldMainActivity.CURRENT_ACTIVITY.get().switchUIs(OldMainActivity.CURRENT_ACTIVITY.get().mUiManager.uiLauncherSetting, mContext.getString(R.string.title_launcher_setting)); } if (v == buttonKeyboard) { @@ -114,7 +114,7 @@ private void refreshUserInfo() { selected = true; textUserName.setText(a.getUsername()); String type; - switch(a.getType()){ + switch (a.getType()) { case SettingJson.USER_TYPE_OFFLINE: type = mContext.getString(R.string.title_offline); break; @@ -133,7 +133,7 @@ private void refreshUserInfo() { } } } - if(!selected){ + if (!selected) { textUserName.setText(mContext.getString(R.string.title_user)); textUserType.setText(""); } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/GamelistUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/GamelistUI.java index bcce0d5d..7c5d72ec 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/GamelistUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/GamelistUI.java @@ -19,7 +19,7 @@ public class GamelistUI extends BaseUI { - public GamelistUI(Context context){ + public GamelistUI(Context context) { super(context); } @@ -60,7 +60,7 @@ public void saveUIConfig() { @Override public void setUIVisibility(int visibility) { - if(visibility == View.VISIBLE){ + if (visibility == View.VISIBLE) { layout_gamelist.startAnimation(showAnim); } layout_gamelist.setVisibility(visibility); @@ -98,10 +98,10 @@ public void refreshLocalVersionList() { beans = new ArrayList<>(); beans.addAll(VersionManager.getVersionBeansList()); listLocalVersions.setAdapter(new LocalVersionListAdapter(mContext, beans)); - }else{ + } else { beans.clear(); beans.addAll(VersionManager.getVersionBeansList()); - ((BaseAdapter)listLocalVersions.getAdapter()).notifyDataSetChanged(); + ((BaseAdapter) listLocalVersions.getAdapter()).notifyDataSetChanged(); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/InstallVersionUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/InstallVersionUI.java index cebb7698..2df6f9f9 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/InstallVersionUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/InstallVersionUI.java @@ -76,7 +76,7 @@ public void saveUIConfig() { @Override public void setUIVisibility(int visibility) { - if(visibility == View.VISIBLE){ + if (visibility == View.VISIBLE) { buttonRefresh.performClick(); } layout_installversion.setVisibility(visibility); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/LogUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/LogUI.java index fb46a257..8cb6b038 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/LogUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/LogUI.java @@ -2,7 +2,6 @@ import android.content.Context; import android.graphics.Color; -import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; @@ -52,7 +51,7 @@ public void onCreate() { this.scrollView.addView(logView); this.buttonRefreshFromFile = layout_log.findViewById(R.id.log_button_refresh_from_file); this.buttonRefreshFromThread = layout_log.findViewById(R.id.log_button_refresh_from_this); - for(View view : new View[]{buttonRefreshFromFile, buttonRefreshFromThread}){ + for (View view : new View[]{buttonRefreshFromFile, buttonRefreshFromThread}) { view.setOnClickListener(this); } showAnim = AnimationUtils.loadAnimation(mContext, R.anim.layout_show); @@ -82,13 +81,13 @@ public int getUIVisibility() { return layout_log.getVisibility(); } - private void showLog(TextView view){ + private void showLog(TextView view) { if (LoadMe.mReceiver != null && LoadMe.mReceiver.get() != null && !LoadMe.mReceiver.get().getLogs().equals("")) { view.setText(LoadMe.mReceiver.get().getLogs()); } else { try { view.setText(FileTool.readToString(AppManifest.BOAT_LOG_FILE)); - } catch (IOException e){ + } catch (IOException e) { e.printStackTrace(); view.setText(e.toString()); } @@ -97,7 +96,7 @@ private void showLog(TextView view){ @Override public void onClick(View v) { - if(v == buttonRefreshFromFile){ + if (v == buttonRefreshFromFile) { try { logView.setText(FileTool.readToString(AppManifest.BOAT_LOG_FILE)); } catch (IOException e) { @@ -106,10 +105,10 @@ public void onClick(View v) { } } - if(v == buttonRefreshFromThread){ - if (LoadMe.mReceiver != null && LoadMe.mReceiver.get() != null){ + if (v == buttonRefreshFromThread) { + if (LoadMe.mReceiver != null && LoadMe.mReceiver.get() != null) { logView.setText(LoadMe.mReceiver.get().getLogs()); - }else{ + } else { DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_error), mContext.getString(R.string.tips_process_is_not_running), mContext.getString(R.string.title_ok), null); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/PluginUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/PluginUI.java index 2ee87958..ba3c4141 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/PluginUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/PluginUI.java @@ -47,7 +47,7 @@ public void saveUIConfig() { @Override public void setUIVisibility(int visibility) { - if(visibility == View.VISIBLE){ + if (visibility == View.VISIBLE) { lagout_plugin.startAnimation(showAnim); } lagout_plugin.setVisibility(visibility); diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/StartGameUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/StartGameUI.java index 3c1c5f04..73a83f9e 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/StartGameUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/StartGameUI.java @@ -68,7 +68,7 @@ public void onCreate() { //设定属性 refreshLocalVersionList(); - if(setting.getLastVersion() != null && !setting.getLastVersion().equals("")){ + if (setting.getLastVersion() != null && !setting.getLastVersion().equals("")) { setConfigureToVersionlist(setting.getLastVersion(), listVersions); } @@ -85,15 +85,16 @@ public void onCreate() { * 【刷新本地游戏列表】 **/ private ArrayList versionIdList; + private void refreshLocalVersionList() { - if(listVersions.getAdapter() == null){ + if (listVersions.getAdapter() == null) { versionIdList = new ArrayList<>(); versionIdList.addAll(Arrays.asList(VersionManager.getVersionsList())); listVersions.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, this.versionIdList)); - }else{ + } else { versionIdList.clear(); versionIdList.addAll(Arrays.asList(VersionManager.getVersionsList())); - ((BaseAdapter)listVersions.getAdapter()).notifyDataSetChanged(); + ((BaseAdapter) listVersions.getAdapter()).notifyDataSetChanged(); } } @@ -101,7 +102,7 @@ private void refreshLocalVersionList() { * 【启动Minecraft】 **/ private void startMinecraft() { - new LaunchManager(mContext).launchMinecraft(OldMainActivity.Setting ,LaunchManager.LAUNCH_PRECHECK); + new LaunchManager(mContext).launchMinecraft(OldMainActivity.Setting, LaunchManager.LAUNCH_PRECHECK); } /** @@ -116,14 +117,14 @@ private void setConfigureToVersionlist(String id, Spinner list) { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if(parent == listVersions){ + if (parent == listVersions) { setting.setLastVersion((String) listVersions.getItemAtPosition(position)); } } @Override public void onNothingSelected(AdapterView parent) { - if(parent == listVersions){ + if (parent == listVersions) { setting.setLastVersion(""); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/UserUI.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/UserUI.java index 3f249175..572746e5 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/UserUI.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/UserUI.java @@ -53,7 +53,7 @@ public void saveUIConfig() { @Override public void setUIVisibility(int visibility) { - if(visibility == View.VISIBLE){ + if (visibility == View.VISIBLE) { layout_user.startAnimation(showAnim); } layout_user.setVisibility(visibility); @@ -92,27 +92,28 @@ public void reloadListView() { } private ArrayList usersList; - public void refreshList(){ - if(usersList == null){ + + public void refreshList() { + if (usersList == null) { usersList = new ArrayList<>(); - listUsers.setAdapter(new UserListAdapter(mContext,usersList)); - }else{ + listUsers.setAdapter(new UserListAdapter(mContext, usersList)); + } else { usersList.clear(); } - for(SettingJson.Account account : OldMainActivity.Setting.getAccounts()){ - if(account != null){ + for (SettingJson.Account account : OldMainActivity.Setting.getAccounts()) { + if (account != null) { usersList.add(account); } } - ((BaseAdapter)listUsers.getAdapter()).notifyDataSetChanged(); + ((BaseAdapter) listUsers.getAdapter()).notifyDataSetChanged(); } - public boolean addFormatedUser(SettingJson.Account account){ - if(account == null){ + public boolean addFormatedUser(SettingJson.Account account) { + if (account == null) { return false; - }else{ - for(SettingJson.Account bean : usersList){ - if(bean.equals(account)){ + } else { + for (SettingJson.Account bean : usersList) { + if (bean.equals(account)) { return false; } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/uis/achieve/UiManager.java b/app/src/main/java/com/aof/mcinabox/launcher/uis/achieve/UiManager.java index 3fd9d653..203be582 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/uis/achieve/UiManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/uis/achieve/UiManager.java @@ -37,7 +37,7 @@ public class UiManager { private final Context mContext; - public UiManager(Context context, SettingJson setting){ + public UiManager(Context context, SettingJson setting) { this.mContext = context; uiInstallVersion = new InstallVersionUI(context); uiPlugin = new PluginUI(context); @@ -98,41 +98,41 @@ public void hideAllUIs() { } } - public void refreshUis(){ - for(BaseUI ui : Uis){ - if (ui != null){ + public void refreshUis() { + for (BaseUI ui : Uis) { + if (ui != null) { ui.refreshUI(); } } } - public void onStop(){ - for (BaseUI ui : Uis){ - if(ui != null){ + public void onStop() { + for (BaseUI ui : Uis) { + if (ui != null) { ui.onStop(); } } } - public void onCreate(){ - for (BaseUI ui : Uis){ - if(ui != null){ + public void onCreate() { + for (BaseUI ui : Uis) { + if (ui != null) { ui.onCreate(); } } } - public void onRestart(){ - for (BaseUI ui : Uis){ - if(ui != null){ + public void onRestart() { + for (BaseUI ui : Uis) { + if (ui != null) { ui.onRestart(); } } } - public void saveConfigToSetting(){ - for (BaseUI ui : Uis){ - if(ui != null){ + public void saveConfigToSetting() { + for (BaseUI ui : Uis) { + if (ui != null) { ui.saveUIConfig(); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/user/CreateUserDialog.java b/app/src/main/java/com/aof/mcinabox/launcher/user/CreateUserDialog.java index 4cc00761..35e18989 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/user/CreateUserDialog.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/user/CreateUserDialog.java @@ -44,7 +44,8 @@ public CreateUserDialog(Context context) { private String pre_username; private String pre_url; private boolean useCustom = false; - public CreateUserDialog(Context context, String username, String url){ + + public CreateUserDialog(Context context, String username, String url) { super(context); this.mContext = context; this.pre_username = username; @@ -69,7 +70,7 @@ protected void onCreate(Bundle savedInstanceState) { v.setOnClickListener(this); } - if(useCustom){ + if (useCustom) { checkboxUsermodel.setChecked(true); checkboxUsermodel.setClickable(false); editUsername.setText(pre_username); @@ -81,24 +82,24 @@ protected void onCreate(Bundle savedInstanceState) { @Override public void onClick(View v) { - if(v == buttonOK){ - if(addUser()){ + if (v == buttonOK) { + if (addUser()) { dismiss(); } } - if(v == buttonCancel){ + if (v == buttonCancel) { this.cancel(); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if(buttonView == checkboxUsermodel){ - if(isChecked){ + if (buttonView == checkboxUsermodel) { + if (isChecked) { layoutPassword.setVisibility(View.VISIBLE); layoutServer.setVisibility(View.VISIBLE); enableLegal = true; - }else{ + } else { layoutPassword.setVisibility(View.GONE); layoutServer.setVisibility(View.GONE); enableLegal = false; @@ -106,32 +107,33 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } } - private boolean addUser(){ + private boolean addUser() { String password = editPassword.getText().toString(); String username = editUsername.getText().toString(); String server = editServer.getText().toString(); //检查用户名 - for(String str : UserManager.getUsersName(OldMainActivity.Setting)){ - if (str.equals(username)){ + for (String str : UserManager.getUsersName(OldMainActivity.Setting)) { + if (str.equals(username)) { Toast.makeText(mContext, mContext.getString(R.string.tips_the_user_has_been_created), Toast.LENGTH_SHORT).show(); return false; } } - if(username.equals("")){ + if (username.equals("")) { Toast.makeText(mContext, mContext.getString(R.string.tips_user_name_can_not_be_void), Toast.LENGTH_SHORT).show(); return false; } //检查密码是否为空 - if(enableLegal){ - if(password.equals("")){ + if (enableLegal) { + if (password.equals("")) { Toast.makeText(mContext, mContext.getString(R.string.tips_password_can_not_be_void), Toast.LENGTH_SHORT).show(); return false; } } //创建用户 - if(enableLegal){ + if (enableLegal) { new LoginServer(server).setCallback(new LoginServer.Callback() { - final TaskDialog mDialog = DialogUtils.createTaskDialog(mContext,mContext.getString(R.string.tips_logging),"",false); + final TaskDialog mDialog = DialogUtils.createTaskDialog(mContext, mContext.getString(R.string.tips_logging), "", false); + @Override public void onStart() { mDialog.show(); @@ -139,21 +141,21 @@ public void onStart() { @Override public void onFailed(Exception e) { - DialogUtils.createSingleChoiceDialog(mContext,mContext.getString(R.string.title_error),String.format(mContext.getString(R.string.tips_error),e.getMessage()),mContext.getString(R.string.title_ok),null); + DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_error), String.format(mContext.getString(R.string.tips_error), e.getMessage()), mContext.getString(R.string.title_ok), null); } @Override - public void onLoginSuccess(final SettingJson.Account account,final AuthenticateResponse response) { - if(response.availableProfiles == null || response.availableProfiles.length == 0){ - DialogUtils.createSingleChoiceDialog(mContext,mContext.getString(R.string.title_error),mContext.getString(R.string.tips_no_roles_in_current_account),mContext.getString(R.string.title_ok),null); + public void onLoginSuccess(final SettingJson.Account account, final AuthenticateResponse response) { + if (response.availableProfiles == null || response.availableProfiles.length == 0) { + DialogUtils.createSingleChoiceDialog(mContext, mContext.getString(R.string.title_error), mContext.getString(R.string.tips_no_roles_in_current_account), mContext.getString(R.string.title_ok), null); return; } - if(response.availableProfiles.length != 1){ + if (response.availableProfiles.length != 1) { String[] names = new String[response.availableProfiles.length]; - for(int a = 0; a < response.availableProfiles.length; a++){ + for (int a = 0; a < response.availableProfiles.length; a++) { names[a] = response.availableProfiles[a].name; } - DialogUtils.createItemsChoiceDialog(mContext,mContext.getString(R.string.title_choice),null,null,mContext.getString(R.string.title_cancel),false,names,new DialogSupports(){ + DialogUtils.createItemsChoiceDialog(mContext, mContext.getString(R.string.title_choice), null, null, mContext.getString(R.string.title_cancel), false, names, new DialogSupports() { @Override public void runWhenItemsSelected(int pos) { super.runWhenItemsSelected(pos); @@ -164,7 +166,7 @@ public void runWhenItemsSelected(int pos) { UserManager.addAccount(OldMainActivity.Setting, account); } }); - }else{ + } else { account.setAccessToken(response.accessToken); account.setUuid(response.selectedProfile.id); account.setUsername(response.selectedProfile.name); @@ -174,13 +176,16 @@ public void runWhenItemsSelected(int pos) { } @Override - public void onValidateSuccess(SettingJson.Account account) {} + public void onValidateSuccess(SettingJson.Account account) { + } @Override - public void onValidateFailed(SettingJson.Account account) {} + public void onValidateFailed(SettingJson.Account account) { + } @Override - public void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response) {} + public void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response) { + } @Override public void onFinish() { @@ -189,8 +194,8 @@ public void onFinish() { }).login(username, password); return true; - }else{ - UserManager.addAccount(OldMainActivity.Setting,UserManager.getOfflineAccount(username)); + } else { + UserManager.addAccount(OldMainActivity.Setting, UserManager.getOfflineAccount(username)); } return true; } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/user/UserManager.java b/app/src/main/java/com/aof/mcinabox/launcher/user/UserManager.java index dab7659c..a7b763ab 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/user/UserManager.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/user/UserManager.java @@ -30,30 +30,30 @@ public static SettingJson.Account getOfflineAccount(String username) { return user; } - public static UUID createUUID(String str){ + public static UUID createUUID(String str) { return UUID.nameUUIDFromBytes((str).getBytes()); } - public static boolean addAccount(SettingJson setting, SettingJson.Account account){ - if (setting.getAccounts() == null){ + public static boolean addAccount(SettingJson setting, SettingJson.Account account) { + if (setting.getAccounts() == null) { return false; } //先检查是否由相同用户名的用户,如果存在的话直接删除 - for(SettingJson.Account a : setting.getAccounts()){ - if(a.getUsername().equals(account.getUsername())){ + for (SettingJson.Account a : setting.getAccounts()) { + if (a.getUsername().equals(account.getUsername())) { account.setSelected(a.isSelected()); - UserManager.removeAccount(setting,account.getUsername()); + UserManager.removeAccount(setting, account.getUsername()); break; } } - SettingJson.Account[] accounts = new SettingJson.Account[setting.getAccounts().length +1]; + SettingJson.Account[] accounts = new SettingJson.Account[setting.getAccounts().length + 1]; SettingJson.Account[] lastAccounts = setting.getAccounts(); int a = 0; - for(; a < lastAccounts.length ; a++){ - if(lastAccounts[a] != null){ + for (; a < lastAccounts.length; a++) { + if (lastAccounts[a] != null) { accounts[a] = lastAccounts[a]; } } @@ -64,47 +64,47 @@ public static boolean addAccount(SettingJson setting, SettingJson.Account accoun return true; } - public static String[] getUsersName(SettingJson setting){ + public static String[] getUsersName(SettingJson setting) { String[] strs = new String[setting.getAccounts().length]; - for(int i = 0; i < strs.length ; i ++){ + for (int i = 0; i < strs.length; i++) { strs[i] = setting.getAccounts()[i].getUsername(); } return strs; } - public static SettingJson.Account getSelectedAccount(SettingJson setting){ - for(SettingJson.Account account : setting.getAccounts()){ - if(account.isSelected()){ + public static SettingJson.Account getSelectedAccount(SettingJson setting) { + for (SettingJson.Account account : setting.getAccounts()) { + if (account.isSelected()) { return account; } } return null; } - public static SettingJson.Account getAccountByUsername(SettingJson setting, String username){ - for(SettingJson.Account account : setting.getAccounts()){ - if(account.getUsername().equals(username)){ + public static SettingJson.Account getAccountByUsername(SettingJson setting, String username) { + for (SettingJson.Account account : setting.getAccounts()) { + if (account.getUsername().equals(username)) { return account; } } return null; } - public static boolean removeAccount(SettingJson setting, String username){ + public static boolean removeAccount(SettingJson setting, String username) { SettingJson.Account[] accounts = setting.getAccounts(); SettingJson.Account target = null; - for(SettingJson.Account account : accounts){ - if(account.getUsername().equals(username)){ + for (SettingJson.Account account : accounts) { + if (account.getUsername().equals(username)) { target = account; } } - if(target == null){ + if (target == null) { return false; - }else{ + } else { SettingJson.Account[] tmp = new SettingJson.Account[setting.getAccounts().length - 1]; int a = 0; - for(SettingJson.Account account : accounts){ - if(target != account){ + for (SettingJson.Account account : accounts) { + if (target != account) { tmp[a] = account; a++; } @@ -114,40 +114,40 @@ public static boolean removeAccount(SettingJson setting, String username){ } } - public static boolean cantainAccount(SettingJson setting, String username){ - for(SettingJson.Account account : setting.getAccounts()){ - if(account.getUsername().equals(username)){ + public static boolean cantainAccount(SettingJson setting, String username) { + for (SettingJson.Account account : setting.getAccounts()) { + if (account.getUsername().equals(username)) { return true; } } return false; } - public static boolean cantainAccount(SettingJson setting, SettingJson.Account account){ + public static boolean cantainAccount(SettingJson setting, SettingJson.Account account) { return cantainAccount(setting, account.getUsername()); } - public static boolean replaceAccount(SettingJson setting, SettingJson.Account originalAccount , SettingJson.Account account){ - if(cantainAccount(setting,originalAccount)){ + public static boolean replaceAccount(SettingJson setting, SettingJson.Account originalAccount, SettingJson.Account account) { + if (cantainAccount(setting, originalAccount)) { removeAccount(setting, originalAccount.getUsername()); addAccount(setting, account); return true; - }else{ + } else { return false; } } - public static boolean replaceAccount(SettingJson setting, String originalUsername , SettingJson.Account account){ + public static boolean replaceAccount(SettingJson setting, String originalUsername, SettingJson.Account account) { return replaceAccount(setting, getAccountByUsername(setting, originalUsername), account); } - public static void clearLegalData(Context context){ + public static void clearLegalData(Context context) { FileTool.deleteFile(new File(context.getExternalFilesDir(null) + "/shared_prefs/" + launcher_prefs_file + ".xml")); } - public static void setAccountSelected(String username){ - SettingJson.Account a = getAccountByUsername(OldMainActivity.Setting,username); - for(SettingJson.Account account : OldMainActivity.Setting.getAccounts()){ + public static void setAccountSelected(String username) { + SettingJson.Account a = getAccountByUsername(OldMainActivity.Setting, username); + for (SettingJson.Account account : OldMainActivity.Setting.getAccounts()) { account.setSelected(account == a); } } diff --git a/app/src/main/java/com/aof/mcinabox/launcher/user/support/AuthlibResponse.java b/app/src/main/java/com/aof/mcinabox/launcher/user/support/AuthlibResponse.java index 351099eb..494c1753 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/user/support/AuthlibResponse.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/user/support/AuthlibResponse.java @@ -6,7 +6,7 @@ public class AuthlibResponse { public String[] skinDomains; public String signaturePublickey; public ServerMeta meta; - + public class ServerMeta { public String implementationName; public String implementationVersion; diff --git a/app/src/main/java/com/aof/mcinabox/launcher/user/support/LoginServer.java b/app/src/main/java/com/aof/mcinabox/launcher/user/support/LoginServer.java index 117e4d5e..f9f54f15 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/user/support/LoginServer.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/user/support/LoginServer.java @@ -1,10 +1,6 @@ package com.aof.mcinabox.launcher.user.support; -import android.annotation.SuppressLint; import android.content.Context; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; import android.util.Base64; import com.aof.mcinabox.R; @@ -54,66 +50,41 @@ public LoginServer setCallback(Callback call) { return this; } - @SuppressLint("HandlerLeak") - private final Handler handler = new Handler() { - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - Bundle data = msg.getData(); - String type = data.getString(OUTPUT_TYPE); - String result = data.getString(OUTPUT_RESULT); - output(type, result); - } - }; private final okhttp3.Callback loginResponse = new okhttp3.Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { isLogining = false; - Message msg = new Message(); - Bundle data = new Bundle(); - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(e)); - msg.setData(data); - handler.sendMessage(msg); + output(TYPE_ERROR, gson.toJson(e)); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) { isLogining = false; - Message msg = new Message(); - Bundle data = new Bundle(); - try { String result = Objects.requireNonNull(response.body()).string(); if (response.code() == 200) { - data.putString(OUTPUT_TYPE, TYPE_LOGIN); - data.putString(OUTPUT_RESULT, result); + output(TYPE_LOGIN, result); } else { ErrorResponse error = gson.fromJson(result, ErrorResponse.class); - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(new Exception(error.errorMessage))); + output(TYPE_ERROR, gson.toJson(new Exception(error.errorMessage))); } } catch (Exception e) { - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(e)); + output(TYPE_ERROR, gson.toJson(e)); } - - msg.setData(data); - handler.sendMessage(msg); } }; - public LoginServer(SettingJson.Account account, Context context){ + public LoginServer(SettingJson.Account account, Context context) { this(account.getApiUrl(), account, context); } - public LoginServer(String url, Context context){ - this(url, new SettingJson().new Account(),context); + public LoginServer(String url, Context context) { + this(url, new SettingJson().new Account(), context); } public LoginServer(String url, SettingJson.Account account, Context context) { this.mContext = context; - if(url == null || url.equals("")) account.setApiUrl(MOJANG_URL); + if (url == null || url.equals("")) account.setApiUrl(MOJANG_URL); else if (!url.startsWith("http")) account.setApiUrl("https://".concat(url)); else account.setApiUrl(url); this.account = account; @@ -124,37 +95,37 @@ private void verifyServer() { Request request = new Request.Builder().url(account.getApiUrl()).build(); try { client.newCall(request).enqueue(verifyServerResponse); - }catch (Exception e) { + } catch (Exception e) { output(TYPE_ERROR, e.getMessage()); } } public void login(String username, String password) { - if(callable){ + if (callable) { mCallback.onStart(); } this.username = username; this.password = password; account.setUserUuid(UserManager.createUUID(username).toString()); isLogining = true; - if(account.getApiUrl().equals(MOJANG_URL)) { + if (account.getApiUrl().equals(MOJANG_URL)) { account.setType(SettingJson.USER_TYPE_ONLINE); login(); - }else { + } else { account.setType(SettingJson.USER_TYPE_EXTERNAL); verifyServer(); } } public void verifyToken() { - if(callable){ + if (callable) { mCallback.onStart(); } httpPost("/validate", new ValidateRequest(account.getAccessToken()), verifyTokenResponse); } public void refreshToken() { - if(callable){ + if (callable) { mCallback.onStart(); } httpPost("/refresh", new RefreshRequest(account.getAccessToken(), UUID.fromString(account.getUserUUID())), loginResponse); @@ -166,10 +137,10 @@ private void login() { private void httpPost(String api, T data, okhttp3.Callback response) { RequestBody body = RequestBody.create(JSON, gson.toJson(data)); - Request request = new Request.Builder().url(account.getApiUrl() + (account.getApiUrl().equals(MOJANG_URL)?api:"/authserver".concat(api))).post(body).build(); + Request request = new Request.Builder().url(account.getApiUrl() + (account.getApiUrl().equals(MOJANG_URL) ? api : "/authserver".concat(api))).post(body).build(); try { client.newCall(request).enqueue(response); - }catch (Exception e) { + } catch (Exception e) { output(TYPE_ERROR, e.getMessage()); } } @@ -177,66 +148,40 @@ private void httpPost(String api, T data, okhttp3.Callback response) { private final okhttp3.Callback verifyServerResponse = new okhttp3.Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { - Message msg = new Message(); - Bundle data = new Bundle(); - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(e)); - msg.setData(data); - handler.sendMessage(msg); + output(TYPE_ERROR, gson.toJson(e)); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) { - Message msg = new Message(); - Bundle data = new Bundle(); - try { - if(response.toString().contains("x-authlib-injector-api-location")) { + if (response.toString().contains("x-authlib-injector-api-location")) { account.setApiUrl(response.request().url().toString()); verifyServer(); - data.putString(OUTPUT_TYPE, TYPE_VERIFY_SERVER); - data.putString(OUTPUT_RESULT, OldMainActivity.CURRENT_ACTIVITY.get().getResources().getString(R.string.tips_redirecting)); - }else { - if(response.code() == 200) data.putString(OUTPUT_TYPE, TYPE_VERIFY_SERVER); - else data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, Objects.requireNonNull(response.body()).string()); + output(TYPE_VERIFY_SERVER, OldMainActivity.CURRENT_ACTIVITY.get().getResources().getString(R.string.tips_redirecting)); + } else { + if (response.code() == 200) + output(TYPE_VERIFY_SERVER, Objects.requireNonNull(response.body()).string()); + else output(TYPE_ERROR, Objects.requireNonNull(response.body()).string()); } } catch (Exception e) { - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(e)); + output(TYPE_ERROR, gson.toJson(e)); } - - msg.setData(data); - handler.sendMessage(msg); } }; private final okhttp3.Callback verifyTokenResponse = new okhttp3.Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { - Message msg = new Message(); - Bundle data = new Bundle(); - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(e)); - msg.setData(data); - handler.sendMessage(msg); + output(TYPE_ERROR, gson.toJson(e)); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) { isLogining = false; - Message msg = new Message(); - Bundle data = new Bundle(); - try { - String result = Objects.requireNonNull(response.body()).string(); - data.putString(OUTPUT_TYPE, TYPE_VALIDATE); - data.putString(OUTPUT_RESULT, gson.toJson(response.code())); + output(TYPE_VALIDATE, gson.toJson(response.code())); } catch (Exception e) { - data.putString(OUTPUT_TYPE, TYPE_ERROR); - data.putString(OUTPUT_RESULT, gson.toJson(e)); + output(TYPE_ERROR, gson.toJson(e)); } - msg.setData(data); - handler.sendMessage(msg); } }; @@ -249,53 +194,61 @@ public LoginServer(SettingJson.Account account) { } private void output(String type, String result) { - if (result != null) - switch (type) { - case TYPE_VERIFY_SERVER: - AuthlibResponse authlibResponse = gson.fromJson(result, AuthlibResponse.class); - account.setServerName(authlibResponse.meta.serverName); - account.setApiMeta(Base64.encodeToString(result.getBytes(), Base64.DEFAULT)); - if (isLogining) login(); - break; - case TYPE_LOGIN: - if(callable){ - mCallback.onLoginSuccess(account,gson.fromJson(result, AuthenticateResponse.class)); - } - break; - case TYPE_ERROR: - Exception e = gson.fromJson(result,Exception.class); - if(callable){ - mCallback.onFailed(e); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> { + if (result != null) + switch (type) { + case TYPE_VERIFY_SERVER: + AuthlibResponse authlibResponse = gson.fromJson(result, AuthlibResponse.class); + account.setServerName(authlibResponse.meta.serverName); + account.setApiMeta(Base64.encodeToString(result.getBytes(), Base64.DEFAULT)); + if (isLogining) login(); + break; + case TYPE_LOGIN: + if (callable) { + mCallback.onLoginSuccess(account, gson.fromJson(result, AuthenticateResponse.class)); + } + break; + case TYPE_ERROR: + Exception e = gson.fromJson(result, Exception.class); + if (callable) { + mCallback.onFailed(e); + } + break; + case TYPE_VALIDATE: + Integer code = gson.fromJson(result, Integer.class); + if (callable) { + switch (code) { + case 204: + mCallback.onValidateSuccess(account); + break; + case 403: + mCallback.onValidateFailed(account); + break; + default: + mCallback.onFailed(new Exception(String.format("Unknown status code : %s", code))); + } + } + break; } - break; - case TYPE_VALIDATE: - Integer code = gson.fromJson(result,Integer.class); - if(callable){ - switch (code){ - case 204: - mCallback.onValidateSuccess(account); - break; - case 403: - mCallback.onValidateFailed(account); - break; - default: - mCallback.onFailed(new Exception(String.format("Unknown status code : %s",code))); - } - } - break; - } - if(callable){ - mCallback.onFinish(); - } + if (callable) { + mCallback.onFinish(); + } + }); } - public interface Callback{ + public interface Callback { void onStart(); + void onFailed(Exception e); + void onLoginSuccess(SettingJson.Account account, AuthenticateResponse response); + void onValidateSuccess(SettingJson.Account account); + void onValidateFailed(SettingJson.Account account); + void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response); + void onFinish(); } } \ No newline at end of file diff --git a/app/src/main/java/com/aof/mcinabox/launcher/user/support/UserListAdapter.java b/app/src/main/java/com/aof/mcinabox/launcher/user/support/UserListAdapter.java index e75a4559..b100f2c3 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/user/support/UserListAdapter.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/user/support/UserListAdapter.java @@ -104,6 +104,7 @@ public void onClick(View v) { public void runWhenPositive() { new LoginServer(userlist.get(position)).setCallback(new LoginServer.Callback() { final TaskDialog mDialog = DialogUtils.createTaskDialog(context, context.getString(R.string.tips_verifying_account), "", false); + @Override public void onStart() { mDialog.show(); @@ -111,25 +112,27 @@ public void onStart() { @Override public void onFailed(Exception e) { - DialogUtils.createSingleChoiceDialog(context,context.getString(R.string.title_error),String.format(context.getString(R.string.tips_error),e.getMessage()),context.getString(R.string.title_ok),null); + DialogUtils.createSingleChoiceDialog(context, context.getString(R.string.title_error), String.format(context.getString(R.string.tips_error), e.getMessage()), context.getString(R.string.title_ok), null); } @Override - public void onLoginSuccess(SettingJson.Account account, AuthenticateResponse response) {} + public void onLoginSuccess(SettingJson.Account account, AuthenticateResponse response) { + } @Override public void onValidateSuccess(SettingJson.Account account) { - DialogUtils.createSingleChoiceDialog(context,context.getString(R.string.title_note),context.getString(R.string.tips_account_is_valid),context.getString(R.string.title_ok),null); + DialogUtils.createSingleChoiceDialog(context, context.getString(R.string.title_note), context.getString(R.string.tips_account_is_valid), context.getString(R.string.title_ok), null); } @Override public void onValidateFailed(final SettingJson.Account account) { - DialogUtils.createBothChoicesDialog(context,context.getString(R.string.title_note),context.getString(R.string.tips_account_is_invalid),context.getString(R.string.title_ok),context.getString(R.string.title_cancel),new DialogSupports(){ + DialogUtils.createBothChoicesDialog(context, context.getString(R.string.title_note), context.getString(R.string.tips_account_is_invalid), context.getString(R.string.title_ok), context.getString(R.string.title_cancel), new DialogSupports() { @Override public void runWhenPositive() { super.runWhenPositive(); new LoginServer(account, context).setCallback(new LoginServer.Callback() { final TaskDialog mDialog = DialogUtils.createTaskDialog(context, context.getString(R.string.tips_refreshing_account), "", false); + @Override public void onStart() { mDialog.show(); @@ -137,25 +140,28 @@ public void onStart() { @Override public void onFailed(Exception e) { - DialogUtils.createSingleChoiceDialog(context,context.getString(R.string.title_error),String.format(context.getString(R.string.tips_error),e.getMessage()),context.getString(R.string.title_ok),null); + DialogUtils.createSingleChoiceDialog(context, context.getString(R.string.title_error), String.format(context.getString(R.string.tips_error), e.getMessage()), context.getString(R.string.title_ok), null); } @Override public void onLoginSuccess(SettingJson.Account account, AuthenticateResponse response) { - account.setAccessToken(response.accessToken); - account.setUuid(response.selectedProfile.id); - account.setUsername(response.selectedProfile.name); - account.setSelected(false); + account.setAccessToken(response.accessToken); + account.setUuid(response.selectedProfile.id); + account.setUsername(response.selectedProfile.name); + account.setSelected(false); } @Override - public void onValidateSuccess(SettingJson.Account account) {} + public void onValidateSuccess(SettingJson.Account account) { + } @Override - public void onValidateFailed(SettingJson.Account account) {} + public void onValidateFailed(SettingJson.Account account) { + } @Override - public void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response) {} + public void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response) { + } @Override public void onFinish() { @@ -167,7 +173,8 @@ public void onFinish() { } @Override - public void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response) {} + public void onRefreshSuccess(SettingJson.Account account, AuthenticateResponse response) { + } @Override public void onFinish() { diff --git a/app/src/main/java/com/aof/mcinabox/launcher/version/support/LocalVersionListAdapter.java b/app/src/main/java/com/aof/mcinabox/launcher/version/support/LocalVersionListAdapter.java index 3ebea8fe..92cec1c9 100644 --- a/app/src/main/java/com/aof/mcinabox/launcher/version/support/LocalVersionListAdapter.java +++ b/app/src/main/java/com/aof/mcinabox/launcher/version/support/LocalVersionListAdapter.java @@ -19,19 +19,21 @@ public class LocalVersionListAdapter extends BaseAdapter { - private ArrayList versionlist; - private Context mContext; + private final ArrayList versionlist; + private final Context mContext; @Override - public int getCount(){ + public int getCount() { return versionlist.size(); } + @Override - public Object getItem(int position){ + public Object getItem(int position) { return versionlist.get(position); } + @Override - public long getItemId(int position){ + public long getItemId(int position) { return position; } @@ -44,28 +46,28 @@ public LocalVersionListAdapter(Context context, ArrayList @Override public View getView(final int position, View convertView, ViewGroup parent) { LocalVersionListAdapter.ViewHolder viewHolder; - if(convertView == null){ + if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_version, null); viewHolder = new LocalVersionListAdapter.ViewHolder(); viewHolder.versionimage = convertView.findViewById(R.id.version_image); viewHolder.versionId = convertView.findViewById(R.id.versionlist_text_versionId); viewHolder.removeversion = convertView.findViewById(R.id.gamelist_button_removeversion); convertView.setTag(viewHolder); - }else{ - viewHolder = (LocalVersionListAdapter.ViewHolder)convertView.getTag(); + } else { + viewHolder = (LocalVersionListAdapter.ViewHolder) convertView.getTag(); } viewHolder.versionId.setText(versionlist.get(position).getVersion_Id()); - viewHolder.removeversion.setOnClickListener(v -> DialogUtils.createBothChoicesDialog(mContext,mContext.getString(R.string.title_warn),String.format(mContext.getString(R.string.tips_are_you_sure_to_delete_version),versionlist.get(position).getVersion_Id()),mContext.getString(R.string.title_ok),mContext.getString(R.string.title_cancel),new DialogSupports(){ + viewHolder.removeversion.setOnClickListener(v -> DialogUtils.createBothChoicesDialog(mContext, mContext.getString(R.string.title_warn), String.format(mContext.getString(R.string.tips_are_you_sure_to_delete_version), versionlist.get(position).getVersion_Id()), mContext.getString(R.string.title_ok), mContext.getString(R.string.title_cancel), new DialogSupports() { @Override - public void runWhenPositive(){ - VersionManager.removeVersion(versionlist.get(position).getVersion_Id(),VersionManager.REMOVE_VERSION_ONLY); + public void runWhenPositive() { + VersionManager.removeVersion(versionlist.get(position).getVersion_Id(), VersionManager.REMOVE_VERSION_ONLY); } })); return convertView; } - class ViewHolder{ + class ViewHolder { public ImageView versionimage; public TextView versionId; Button removeversion; diff --git a/app/src/main/java/com/aof/mcinabox/minecraft/json/AssetsJson.java b/app/src/main/java/com/aof/mcinabox/minecraft/json/AssetsJson.java index bbe6ada4..b01ea850 100644 --- a/app/src/main/java/com/aof/mcinabox/minecraft/json/AssetsJson.java +++ b/app/src/main/java/com/aof/mcinabox/minecraft/json/AssetsJson.java @@ -4,17 +4,36 @@ public class AssetsJson { - public HashMap objects; - public class MinecraftAssetInfo{ + public HashMap objects; + + public class MinecraftAssetInfo { public String hash; public int size; - public String getHash() { return hash; } - public void setHash(String hash) { this.hash = hash; } - public int getSize() { return size; } - public void setSize(int size) { this.size = size; } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + } + + public HashMap getObjects() { + return objects; + } + + public void setObjects(HashMap objects) { + this.objects = objects; } - public HashMap getObjects() { return objects; } - public void setObjects(HashMap objects) { this.objects = objects; } } diff --git a/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionJson.java b/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionJson.java index 003c71c0..1525c23c 100644 --- a/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionJson.java +++ b/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionJson.java @@ -2,7 +2,7 @@ public class VersionJson { - //通用参数 + //通用参数 private String id; private String mainClass; private int minimumLauncherVersion; @@ -14,116 +14,312 @@ public class VersionJson { private Download downloads; private AssetIndex assetIndex; - //minimumLauncherVersion < 21 + //minimumLauncherVersion < 21 private String minecraftArguments; - //minimumLauncherVersion >= 21 + //minimumLauncherVersion >= 21 private Arguments arguments; - //forge + //forge private String inheritsFrom; - public class DependentLibrary{ + public class DependentLibrary { private String name; private Download downloads; private String url; - public class Download{ + + public class Download { private Artifact artifact; - public class Artifact{ + + public class Artifact { private String path; private String url; private String sha1; private int size; - public String getPath() { return path; } - public void setPath(String path) { this.path = path; } - public String getUrl() { return url; } - public void setUrl(String url) { this.url = url; } - public String getSha1() { return sha1; } - public void setSha1(String sha1) { this.sha1 = sha1; } - public int getSize() { return size; } - public void setSize(int size) { this.size = size; } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getSha1() { + return sha1; + } + + public void setSha1(String sha1) { + this.sha1 = sha1; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + } + + public Artifact getArtifact() { + return artifact; } - public Artifact getArtifact() { return artifact; } - public void setArtifact(Artifact artifact) { this.artifact = artifact; } + + public void setArtifact(Artifact artifact) { + this.artifact = artifact; + } + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Download getDownloads() { + return downloads; + } + + public void setDownloads(Download downloads) { + this.downloads = downloads; } - public String getUrl() {return url;} - public void setUrl(String url){this.url = url;} - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public Download getDownloads() { return downloads; } - public void setDownloads(Download downloads) { this.downloads = downloads; } } - public class Download{ + public class Download { private Client client; private Server server; - public class Client{ + + public class Client { private int size; private String sha1; private String url; - public int getSize() { return size; } - public void setSize(int size) { this.size = size; } - public String getSha1() { return sha1; } - public void setSha1(String sha1) { this.sha1 = sha1; } - public String getUrl() { return url; } - public void setUrl(String url) { this.url = url; } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public String getSha1() { + return sha1; + } + + public void setSha1(String sha1) { + this.sha1 = sha1; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } + + public class Server extends Client { + } + + public Client getClient() { + return client; + } + + public void setClient(Client client) { + this.client = client; + } + + public Server getServer() { + return server; + } + + public void setServer(Server server) { + this.server = server; } - public class Server extends Client{ } - public Client getClient() { return client; } - public void setClient(Client client) { this.client = client; } - public Server getServer() { return server; } - public void setServer(Server server) { this.server = server; } } - public class AssetIndex{ + public class AssetIndex { private String id; private String sha1; private String url; private int size; private int totalSize; - public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getSha1() { return sha1; } - public void setSha1(String sha1) { this.sha1 = sha1; } - public String getUrl() { return url; } - public void setUrl(String url) { this.url = url; } - public int getSize() { return size; } - public void setSize(int size) { this.size = size; } - public int getTotalSize() { return totalSize; } - public void setTotalSize(int totalSize) { this.totalSize = totalSize; } - } - - public class Arguments{ + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getSha1() { + return sha1; + } + + public void setSha1(String sha1) { + this.sha1 = sha1; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + } + + public class Arguments { private Object[] game; - public Object[] getGame() { return game; } - public void setGame(Object[] game) { this.game = game; } - } - - public Arguments getArguments() { return arguments; } - public void setArguments(Arguments arguments) { this.arguments = arguments; } - public String getInheritsFrom() { return inheritsFrom; } - public void setInheritsFrom(String inheritsFrom) { this.inheritsFrom = inheritsFrom; } - public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getMainClass() { return mainClass; } - public void setMainClass(String mainClass) { this.mainClass = mainClass; } - public String getMinecraftArguments() { return minecraftArguments; } - public void setMinecraftArguments(String minecraftArguments) { this.minecraftArguments = minecraftArguments; } - public int getMinimumLauncherVersion() { return minimumLauncherVersion; } - public void setMinimumLauncherVersion(int minimumLauncherVersion) { this.minimumLauncherVersion = minimumLauncherVersion; } - public String getReleaseTime() { return releaseTime; } - public void setReleaseTime(String releaseTime) { this.releaseTime = releaseTime; } - public String getTime() { return time; } - public void setTime(String time) { this.time = time; } - public String getType() { return type; } - public void setType(String type) { this.type = type; } - public String getAssets() { return assets; } - public void setAssets(String assets) { this.assets = assets; } - public DependentLibrary[] getLibraries() { return libraries; } - public void setLibraries(DependentLibrary[] libraries) { this.libraries = libraries; } - public Download getDownloads() { return downloads; } - public void setDownloads(Download downloads) { this.downloads = downloads; } - public AssetIndex getAssetIndex() { return assetIndex; } - public void setAssetIndex(AssetIndex assetIndex) { this.assetIndex = assetIndex; } + + public Object[] getGame() { + return game; + } + + public void setGame(Object[] game) { + this.game = game; + } + } + + public Arguments getArguments() { + return arguments; + } + + public void setArguments(Arguments arguments) { + this.arguments = arguments; + } + + public String getInheritsFrom() { + return inheritsFrom; + } + + public void setInheritsFrom(String inheritsFrom) { + this.inheritsFrom = inheritsFrom; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMainClass() { + return mainClass; + } + + public void setMainClass(String mainClass) { + this.mainClass = mainClass; + } + + public String getMinecraftArguments() { + return minecraftArguments; + } + + public void setMinecraftArguments(String minecraftArguments) { + this.minecraftArguments = minecraftArguments; + } + + public int getMinimumLauncherVersion() { + return minimumLauncherVersion; + } + + public void setMinimumLauncherVersion(int minimumLauncherVersion) { + this.minimumLauncherVersion = minimumLauncherVersion; + } + + public String getReleaseTime() { + return releaseTime; + } + + public void setReleaseTime(String releaseTime) { + this.releaseTime = releaseTime; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAssets() { + return assets; + } + + public void setAssets(String assets) { + this.assets = assets; + } + + public DependentLibrary[] getLibraries() { + return libraries; + } + + public void setLibraries(DependentLibrary[] libraries) { + this.libraries = libraries; + } + + public Download getDownloads() { + return downloads; + } + + public void setDownloads(Download downloads) { + this.downloads = downloads; + } + + public AssetIndex getAssetIndex() { + return assetIndex; + } + + public void setAssetIndex(AssetIndex assetIndex) { + this.assetIndex = assetIndex; + } } diff --git a/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionManifestJson.java b/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionManifestJson.java index 689758bc..fc8fc823 100644 --- a/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionManifestJson.java +++ b/app/src/main/java/com/aof/mcinabox/minecraft/json/VersionManifestJson.java @@ -14,10 +14,21 @@ public class VersionManifestJson { //其中“release”为最新的稳定版 “snapshot”为最新的快照版 private Map latest; - public Map getLatest() { return latest; } - public void setLatest(Map latest) { this.latest = latest; } - public Version[] getVersions() { return versions; } - public void setVersions(Version[] versions) { this.versions = versions; } + public Map getLatest() { + return latest; + } + + public void setLatest(Map latest) { + this.latest = latest; + } + + public Version[] getVersions() { + return versions; + } + + public void setVersions(Version[] versions) { + this.versions = versions; + } public class Version { private String id; @@ -27,15 +38,44 @@ public class Version { private String realeaseTime; //Getter and Setter - public void setId(String i) { id = i; } - public String getId() { return id; } - public void setType(String i) { type = i; } - public String getType() { return type; } - public void setUrl(String i) { url = i; } - public String getUrl() { return url; } - public void setTime(String i) { time = i; } - public String getTime() { return time; } - public void setRealeaseTime(String i) { realeaseTime = i; } - public String getReleaseTime() { return realeaseTime; } + public void setId(String i) { + id = i; + } + + public String getId() { + return id; + } + + public void setType(String i) { + type = i; + } + + public String getType() { + return type; + } + + public void setUrl(String i) { + url = i; + } + + public String getUrl() { + return url; + } + + public void setTime(String i) { + time = i; + } + + public String getTime() { + return time; + } + + public void setRealeaseTime(String i) { + realeaseTime = i; + } + + public String getReleaseTime() { + return realeaseTime; + } } } diff --git a/app/src/main/java/com/aof/mcinabox/model/CurrentLaunchFeatureMatcher.java b/app/src/main/java/com/aof/mcinabox/model/CurrentLaunchFeatureMatcher.java index 67d0c322..6e166f37 100644 --- a/app/src/main/java/com/aof/mcinabox/model/CurrentLaunchFeatureMatcher.java +++ b/app/src/main/java/com/aof/mcinabox/model/CurrentLaunchFeatureMatcher.java @@ -4,12 +4,12 @@ import com.google.common.base.Objects; public class CurrentLaunchFeatureMatcher implements CompatibilityRule.FeatureMatcher { - - public boolean hasFeature(String name, Object value) { - if (name.equals("is_demo_user")) - return Objects.equal(false, value); - if (name.equals("has_custom_resolution")) - return Objects.equal(true, value); - return false; - } + + public boolean hasFeature(String name, Object value) { + if (name.equals("is_demo_user")) + return Objects.equal(false, value); + if (name.equals("has_custom_resolution")) + return Objects.equal(true, value); + return false; + } } diff --git a/app/src/main/java/com/aof/mcinabox/network/model/assets/AssetIndex.java b/app/src/main/java/com/aof/mcinabox/network/model/assets/AssetIndex.java index 298fb41d..e2dd43c5 100644 --- a/app/src/main/java/com/aof/mcinabox/network/model/assets/AssetIndex.java +++ b/app/src/main/java/com/aof/mcinabox/network/model/assets/AssetIndex.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; if ((this.compressedHash != null) ? !this.compressedHash.equals(that.compressedHash) : (that.compressedHash != null)) return false; - return (this.hash != null) ? this.hash.equals(that.hash) : (that.hash == null); + return (this.hash != null) ? this.hash.equals(that.hash) : (that.hash == null); } public int hashCode() { diff --git a/app/src/main/java/com/aof/mcinabox/utils/BoatUtils.java b/app/src/main/java/com/aof/mcinabox/utils/BoatUtils.java index d8eee667..58f32f1a 100644 --- a/app/src/main/java/com/aof/mcinabox/utils/BoatUtils.java +++ b/app/src/main/java/com/aof/mcinabox/utils/BoatUtils.java @@ -101,14 +101,14 @@ public static boolean extractAsset(AssetManager am, String src, String target) { * Add a callback with filenames. */ - public static void extractTarXZ(File tarFile, File destDir, CompressCallback callback){ + public static void extractTarXZ(File tarFile, File destDir, CompressCallback callback) { try (FileInputStream fis = new FileInputStream(tarFile); XZCompressorInputStream xzcis = new XZCompressorInputStream(fis); TarArchiveInputStream tais = new TarArchiveInputStream(xzcis, 1024)) { TarArchiveEntry entry; while ((entry = tais.getNextTarEntry()) != null) { File target = new File(destDir, entry.getName()); - if(callback != null){ + if (callback != null) { callback.onFileCompressing(target); } if (entry.isDirectory()) { @@ -152,7 +152,7 @@ public static boolean setExecutable(String file) { return setExecutable(new File(file)); } - public interface CompressCallback{ + public interface CompressCallback { void onFileCompressing(File file); } } diff --git a/app/src/main/java/com/aof/mcinabox/utils/ColorUtils.java b/app/src/main/java/com/aof/mcinabox/utils/ColorUtils.java index bb329fcd..1678a057 100644 --- a/app/src/main/java/com/aof/mcinabox/utils/ColorUtils.java +++ b/app/src/main/java/com/aof/mcinabox/utils/ColorUtils.java @@ -9,28 +9,30 @@ public class ColorUtils { - /**Color的Int整型转Color的16进制颜色值【方案一】 + /** + * Color的Int整型转Color的16进制颜色值【方案一】 * colorInt - -12590395 * return Color的16进制颜色值——#3FE2C5 - * */ - public static String int2Hex(int colorInt){ + */ + public static String int2Hex(int colorInt) { String hexCode; hexCode = String.format("#%06X", 16777215 & colorInt); return hexCode; } - /**Color的Int整型转Color的16进制颜色值【方案二】 + /** + * Color的Int整型转Color的16进制颜色值【方案二】 * colorInt - -12590395 * return Color的16进制颜色值——#3FE2C5 - * */ - public static String int2Hex2(int colorInt){ + */ + public static String int2Hex2(int colorInt) { String hexCode; int[] rgb = int2Rgb(colorInt); hexCode = rgb2Hex(rgb); return hexCode; } - public static String int2Hex3(int colorInt){ + public static String int2Hex3(int colorInt) { return "#" + intToHex(Color.alpha(colorInt), 2) + intToHex(Color.red(colorInt), 2) + @@ -38,35 +40,37 @@ public static String int2Hex3(int colorInt){ intToHex(Color.blue(colorInt), 2); } - private static String intToHex(int n,int size) { + private static String intToHex(int n, int size) { StringBuffer s = new StringBuffer(); String a; - char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; - while(n != 0){ - s = s.append(b[n%16]); - n = n/16; + char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + while (n != 0) { + s = s.append(b[n % 16]); + n = n / 16; } a = s.reverse().toString(); - a = add_zore(a,size); + a = add_zore(a, size); return a; } - public static String add_zore(String str, int size){ - if (str.length() { - public void write(JsonWriter out, UUID value) throws IOException { - out.value(fromUUID(value)); - } - - public UUID read(JsonReader in) throws IOException { - return fromString(in.nextString()); - } - - public static String fromUUID(UUID value) { - return value.toString().replace("-", ""); - } - - public static UUID fromString(String input) { - return UUID.fromString(input.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); - } + public void write(JsonWriter out, UUID value) throws IOException { + out.value(fromUUID(value)); + } + + public UUID read(JsonReader in) throws IOException { + return fromString(in.nextString()); + } + + public static String fromUUID(UUID value) { + return value.toString().replace("-", ""); + } + + public static UUID fromString(String input) { + return UUID.fromString(input.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); + } } diff --git a/app/src/main/java/com/aof/mcinabox/utils/ZipUtils.java b/app/src/main/java/com/aof/mcinabox/utils/ZipUtils.java index 3b4b141e..523ed45e 100644 --- a/app/src/main/java/com/aof/mcinabox/utils/ZipUtils.java +++ b/app/src/main/java/com/aof/mcinabox/utils/ZipUtils.java @@ -1,48 +1,19 @@ package com.aof.mcinabox.utils; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; import android.util.Log; import androidx.annotation.NonNull; -import com.google.gson.Gson; +import com.aof.mcinabox.activity.OldMainActivity; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.util.Objects; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipUtils { - private final static String TAG = "ZipUtils"; - private final static String TYPE = "Type"; - private final static String RESULT = "Result"; - private final static String TYPE_ERROR = "Error"; - private final static String TYPE_SUCCESS = "Success"; - - private final Gson gson = new Gson(); - - private final Handler mHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - if (callable) { - switch (Objects.requireNonNull(msg.getData().getString(TYPE))) { - case TYPE_ERROR: - mCallback.onFailed(gson.fromJson(msg.getData().getString(RESULT), Exception.class)); - break; - case TYPE_SUCCESS: - mCallback.onSuccess(); - break; - } - mCallback.onFinish(); - } - } - }; private Callback mCallback; private boolean callable = false; @@ -60,9 +31,6 @@ public void UnZipFolder(final String zipFileString, final String outPathString) new Thread() { @Override public void run() { - super.run(); - Message msg = new Message(); - Bundle bundle = new Bundle(); try (ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString))) { ZipEntry zipEntry; String szName; @@ -93,15 +61,11 @@ public void run() { } } } - bundle.putString(TYPE, TYPE_SUCCESS); - bundle.putString(RESULT, null); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> mCallback.onSuccess()); } catch (Exception e) { e.printStackTrace(); - bundle.putString(TYPE, TYPE_ERROR); - bundle.putString(RESULT, gson.toJson(e)); + OldMainActivity.CURRENT_ACTIVITY.get().runOnUiThread(() -> mCallback.onFailed(e)); } - msg.setData(bundle); - mHandler.sendMessage(msg); } }.start(); } diff --git a/app/src/main/java/com/aof/mcinabox/utils/dialog/DialogUtils.java b/app/src/main/java/com/aof/mcinabox/utils/dialog/DialogUtils.java index 196871a4..9ba1e383 100644 --- a/app/src/main/java/com/aof/mcinabox/utils/dialog/DialogUtils.java +++ b/app/src/main/java/com/aof/mcinabox/utils/dialog/DialogUtils.java @@ -131,7 +131,7 @@ public static void createColorPickerDialog(Context context, String title, String picker.build().show(); } - public static void createFileSelectorDialog(@NonNull Context context, String title, @NonNull String startPath, String extension, @Nullable final DialogSupports support){ + public static void createFileSelectorDialog(@NonNull Context context, String title, @NonNull String startPath, String extension, @Nullable final DialogSupports support) { new FileChooserDialog.Builder(context, file -> { if (support != null) { support.runWhenItemsSelected(file.getAbsolutePath()); diff --git a/app/src/main/java/com/aof/mcinabox/utils/dialog/support/DialogSupports.java b/app/src/main/java/com/aof/mcinabox/utils/dialog/support/DialogSupports.java index 340b1bc6..af768581 100644 --- a/app/src/main/java/com/aof/mcinabox/utils/dialog/support/DialogSupports.java +++ b/app/src/main/java/com/aof/mcinabox/utils/dialog/support/DialogSupports.java @@ -2,11 +2,24 @@ public class DialogSupports { - public void runWhenPositive(){} - public void runWhenNegative(){} - public void runWhenNeutral(){} - public void runWhenItemsSelected(int pos){} - public void runWhenItemsSelected(Object obj){} - public void runWhenItemsSelected(){} - public void runWhenColorSelected(int[] colors){} + public void runWhenPositive() { + } + + public void runWhenNegative() { + } + + public void runWhenNeutral() { + } + + public void runWhenItemsSelected(int pos) { + } + + public void runWhenItemsSelected(Object obj) { + } + + public void runWhenItemsSelected() { + } + + public void runWhenColorSelected(int[] colors) { + } } diff --git a/app/src/main/java/com/aof/mcinabox/utils/dialog/support/TaskDialog.java b/app/src/main/java/com/aof/mcinabox/utils/dialog/support/TaskDialog.java index 8c7719b8..cf66779d 100644 --- a/app/src/main/java/com/aof/mcinabox/utils/dialog/support/TaskDialog.java +++ b/app/src/main/java/com/aof/mcinabox/utils/dialog/support/TaskDialog.java @@ -10,9 +10,9 @@ public class TaskDialog extends Dialog { - private TextView textTotalTaskName; - private TextView textCurrentTaskName; - private Context mContext; + private final TextView textTotalTaskName; + private final TextView textCurrentTaskName; + private final Context mContext; public TaskDialog(@NonNull Context context, boolean cancelable) { super(context); @@ -23,21 +23,21 @@ public TaskDialog(@NonNull Context context, boolean cancelable) { setCancelable(cancelable); } - public TaskDialog setTotalTaskName(String taskname){ + public TaskDialog setTotalTaskName(String taskname) { textTotalTaskName.setText(taskname); return this; } - public TaskDialog setCurrentTaskName(String taskname){ + public TaskDialog setCurrentTaskName(String taskname) { textCurrentTaskName.setText(taskname); return this; } - public TextView getTextTotalTaskName(){ + public TextView getTextTotalTaskName() { return textTotalTaskName; } - public TextView getTextCurrentTaskName(){ + public TextView getTextCurrentTaskName() { return textCurrentTaskName; } } diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml new file mode 100644 index 00000000..c1e7e083 --- /dev/null +++ b/app/src/main/res/layout/activity_login.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/xml/account_preferences.xml b/app/src/main/res/xml/account_preferences.xml new file mode 100644 index 00000000..e0a94b7f --- /dev/null +++ b/app/src/main/res/xml/account_preferences.xml @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file