Testing of override of toString()

本文介绍了如何在 Java 中为 POJO 类覆盖 toString 方法来方便地打印对象属性。通过使用 Apache Commons Lang 库中的 ToStringBuilder,可以简洁地实现这一功能,并展示了两种不同的实现方式及其输出效果。

At fisrt,thanks for the tips of Xia,I just  run the situation he described.

        When we want to print the properties of POJO, we can override the function toString() for conveninence , here is my testing code:

        Created a object Student:

       

package mysrc;
import java.io.Serializable;

import org.apache.commons.lang.builder.ToStringBuilder;

public class Student implements Serializable{

	int id;
	String name;
	//construct
	Student (){		
	}
	
	Student(int id,String name){
		this.id = id;
		this.name = name;
	}
	
	//override
	public  String toString(){		
		return ToStringBuilder.reflectionToString(this);
	}
	
	//the different way to implement this function
	public String toStr(){
		return new ToStringBuilder(this).append("id",id).append("name",name).toString();
	}

}

    Then test these two methods:

   

package mysrc;

public class ToStringTest {	
	public static void main(String args[]){		
		Student stu = new Student(10086,"tanglei");		
		System.out.println(stu.toString());
		System.out.println(stu.toStr());
	}
}

   Then the result is :

          mysrc.Student@a62fc3[id=10086,name=tanglei]
          mysrc.Student@a62fc3[id=10086,name=tanglei]

   Ok,that's all

package com.oplus.engineermode.anti.anticase.touch; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.OplusKeyEventManager; import android.provider.Settings; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.oplus.engineermode.R; import com.oplus.engineermode.anti.anticase.AntiCaseBase; import com.oplus.engineermode.anti.bandsetting.rftoolkit.Tech; import com.oplus.engineermode.anti.bandsetting.rftoolkit.TxParam; import com.oplus.engineermode.anti.constant.Constants; import com.oplus.engineermode.anti.utils.Utils; import com.oplus.engineermode.core.sdk.utils.Log; import com.oplus.engineermode.device.base.DeviceManager; import com.oplus.engineermode.display.lcd.base.LcdTimingColorModeManager; import com.oplus.engineermode.display.sdk.LcdRefreshRateManager; import com.oplus.engineermode.lights.base.LightsManager; import com.oplus.engineermode.misc.sdk.utils.OplusMiscHelper; import com.oplus.engineermode.touchpanel.sdk.utils.OplusTouchHelper; import com.oplus.engineermode.touchscreen.base.AutoTestResult; import com.oplus.engineermode.touchscreen.base.TouchScreenAutoTest; import com.oplus.engineermode.touchscreen.base.TpCommonUtils; import com.oplus.engineermode.util.KeyEventInterceptor; import com.oplus.engineermode.util.ProjectFeatureOptions; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class TouchAntiCase extends AntiCaseBase { private static final String TAG = "TouchAntiCase"; private static final int INVALID_SETTING_PARAMETER = -1; private static final int MSG_START = 0x11; private static final int MSG_FIRMWARE = 0x12; private static final int MSG_TOUCH = 0x13; private static final int MSG_ALL_DONE = 0x14; private static final int MOVE_DELEYY = 10000; private static final int MOVE_WHAT = 1001; private static final int VDET_TARGET_VALUE = 950; private static final int VDET_UNIT = 10; private AutoTestResult mTpAutoTestResult; private AutoTestResult mScreenOffTpAutoTestResult; private TouchScreenAutoTest mTouchScreenAutoTest; private HandlerThread mSubHandlerThread; private HandlerThread mTkHandlerThread; private TouchCaseAdapter mTouchCaseAdapter; private boolean mTpAutoTestDone; private boolean mScreenOffTpAutoTestDone; private boolean mIsTouchScreenTpEnabled = true; private int mScreenRateSettings; private boolean mIsScreenOffTouchScreenTpEnabled; private int mOldBrightness = INVALID_SETTING_PARAMETER; private int mOldBrightnessMode = INVALID_SETTING_PARAMETER; private LightsManager mLightsManager; private int mTpIcId = OplusTouchHelper.DEFAULT_TP_IC_ID; private int mCycleTimes; private int mTestTime; private boolean mIsTouchFlag = false; private boolean mIsTouchNeedStart =false; private RelativeLayout rootView; private TextView mFirmwareTv; private TextView mResultTextView; private ListView mTouchListView; private List<AntiTouchResult> mAntiTouchResultList; private Handler mHandler; private StringBuilder testRecord; private StringBuilder testFailRecord; private AntiTouchResult mAntiTouchResult; private TxParam mTxParam; private final KeyEventInterceptor mKeyEventInterceptor = new KeyEventInterceptor(TouchAntiCase.this, TAG, new OplusKeyEventManager.OnKeyEventObserver() { @Override public void onKeyEvent(KeyEvent keyEvent) { Log.i(TAG, keyEvent.toString()); if ((keyEvent.getAction() == KeyEvent.ACTION_UP) && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK)) { runOnUiThread(new Runnable() { @Override public void run() { Log.i(TAG, "KEYCODE_BACK"); if (testRecord != null) { testRecord.append(getString(R.string.anti_back_pressed)).append("\n"); testFailRecord.append(getString(R.string.anti_back_pressed)).append("\n"); } onAntiSkip(getString(R.string.anti_back_pressed)); } }); } } }); private final TouchScreenAutoTest.AutoTestCallback mAutoTestCallback = new TouchScreenAutoTest.AutoTestCallback() { @Override public void onScreenOnTpAutoTestDone(AutoTestResult result) { if (result != null) { Log.i(TAG, "onScreenOnTpAutoTestDone " + result.toString()); testRecord.append(getSystemTime()).append("\t").append(getString(R.string.anti_auto_up_callback)) .append(result.toString()).append("\n"); } mTpAutoTestDone = true; mTpAutoTestResult = result; if ((mTpAutoTestResult != null) && !mTpAutoTestResult.getTestResult()) { mScreenOffTpAutoTestDone = true; } mHandler.sendEmptyMessage(MSG_FIRMWARE); } @Override public void onScreenOffTpAutoTestDone(AutoTestResult result) { if (result != null) { Log.i(TAG, "onScreenOffTpAutoTestDone " + result.toString()); testRecord.append(getSystemTime()).append("\t").append(getString(R.string.anti_auto_down_callback)) .append(result.toString()).append("\n"); } mScreenOffTpAutoTestDone = true; mScreenOffTpAutoTestResult = result; mHandler.sendEmptyMessage(MSG_FIRMWARE); } }; private Handler moveHandler = new Handler() { @Override public void handleMessage(Message message) { super.handleMessage(message); moveHandler.sendEmptyMessageDelayed(MOVE_WHAT, MOVE_DELEYY); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rootView.getLayoutParams(); layoutParams.topMargin += 90; layoutParams.leftMargin += 15; if (layoutParams.topMargin >= 900) { layoutParams.topMargin = 0; layoutParams.leftMargin = 0; } Log.i(TAG, "moveHandler:topMargin:" + layoutParams.topMargin + ",leftMargin:" + layoutParams.leftMargin); rootView.setLayoutParams(layoutParams); } }; @Override protected String getAntiItemName() { return TouchAntiItemSetting.getInstance().getAntiItemName(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.anti_touch_xml); testRecord = new StringBuilder().append(getString(R.string.anti_sensor_start_time_info)) .append(getSystemTime()).append(":").append("\n"); testFailRecord = new StringBuilder(); mTxParam = getIntent().getParcelableExtra(Constants.EXTRA_ANTI_RADIO_TXPARAM); int radioMeasurePower = getIntent().getIntExtra(Constants.EXTRA_ANTI_RADIO_TXMEASURE,Constants.TX_PARAM_DEFAULT_VALUE); Log.d(TAG, "radioMeasurePower : " + radioMeasurePower); if (mTxParam != null) { String txParamInfo = mTxParam.getTxParamInfo(); Log.d(TAG, "txParam info : " + txParamInfo); testRecord.append(getString(R.string.anti_sensor_channel_information)).append(txParamInfo) .append(Utils.getMeasurePowerInfo(getApplicationContext(), radioMeasurePower)).append("\n"); TextView tech = findViewById(R.id.tech_param); tech.setText(mTxParam.getTechInfo()); TextView band = findViewById(R.id.band_param); band.setText(String.valueOf(mTxParam.getBand())); TextView antenna = findViewById(R.id.antenna_param); antenna.setText(String.valueOf(mTxParam.getAntenna())); TextView channelType = findViewById(R.id.channelType_param); channelType.setText(mTxParam.getChannelTypeInfo()); TextView power = findViewById(R.id.power_param); TextView measurePower = findViewById(R.id.measure_power); if (Tech.BDS.name().equals(mTxParam.getTechInfo())) { TextView powerTitle = findViewById(R.id.power_title); powerTitle.setText(getString(R.string.anti_dialog_target_VDET)); TextView measurePowerTitle = findViewById(R.id.measure_power_title); measurePowerTitle.setText(getString(R.string.anti_dialog_measure_VDET)); power.setText(String.valueOf(VDET_TARGET_VALUE)); measurePower.setText(String.valueOf(radioMeasurePower / VDET_UNIT)); } else { power.setText(String.valueOf(mTxParam.getPower())); measurePower.setText(String.valueOf(radioMeasurePower)); } } rootView = (RelativeLayout) findViewById(R.id.rootView); mResultTextView = (TextView) findViewById(R.id.result_tv); mFirmwareTv = findViewById(R.id.anti_firmware); mTouchListView = findViewById(R.id.anti_touch_listview); mAntiTouchResultList = new ArrayList<>(); mTouchCaseAdapter = new TouchCaseAdapter(this, mAntiTouchResultList); mTouchListView.setAdapter(mTouchCaseAdapter); mScreenRateSettings = LcdRefreshRateManager.queryLCMFrequencySetting(this); mLightsManager = new LightsManager(this); final int maxBrightness = mLightsManager.getLcdBacklightMaximumBrightnessLevel(); mOldBrightness = mLightsManager.getLcdBackLightBrightness(this); mOldBrightnessMode = LightsManager.getLcdBrightnessMode(this); if (ProjectFeatureOptions.FEATURE_ARIES_DISPLAY) { LcdTimingColorModeManager.displayTimingAndColorModeInit(getApplicationContext()); LcdTimingColorModeManager.setRefreshRateByMode(120.0f); } else { LcdRefreshRateManager.updateLCMFrequencySetting(this, LcdRefreshRateManager.REFRESH_RATE_60HZ); } Log.i(TAG, "mMaxBrightness: " + maxBrightness + ", mOldBrightness: " + mOldBrightness + ", FEATURE_ARIES_DISPLAY=" + ProjectFeatureOptions.FEATURE_ARIES_DISPLAY); setLcdBackLightBrightness(maxBrightness); mIsScreenOffTouchScreenTpEnabled = false; final String tpDeviceInfo = OplusMiscHelper.getTPDeviceInfo(mTpIcId); final String strProductVersion = getResources().getString(R.string.tp_bin_version) + DeviceManager.getVersionFromDeviceInfo(tpDeviceInfo); mFirmwareTv.setText(strProductVersion); mResultTextView.setText(R.string.tp_autotest_warning); mSubHandlerThread = new HandlerThread("ANTI_TOUCH_PANEL_AUTO_TEST"); mSubHandlerThread.start(); mTkHandlerThread = new HandlerThread("ANTI_TOUCH_RESULT"); mTkHandlerThread.start(); mTouchScreenAutoTest = new TouchScreenAutoTest(this, getMainLooper(), mSubHandlerThread.getLooper()); mTouchScreenAutoTest.setTpIcId(mTpIcId); mTouchScreenAutoTest.init(mIsTouchScreenTpEnabled, mIsScreenOffTouchScreenTpEnabled); mTouchScreenAutoTest.setAutoTestCallback(mAutoTestCallback); mTouchScreenAutoTest.setAgingMode(true); } @Override public boolean onTouchEvent(MotionEvent event) { Log.i(TAG, "TouchEvent action =" + event.getAction()); if (mIsTouchNeedStart) { if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) { mIsTouchFlag = true; String format = String.format(Locale.US, "%s: %.2f, %s, %.2f", "x:", event.getX(), "y:", event.getY()); testRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); testFailRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); return true; } } return false; } @Override protected void onResume() { super.onResume(); mTouchListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.i(TAG, "OnTouchListener action = " + event.getAction()); if (mIsTouchNeedStart) { if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) { mIsTouchFlag = true; String format = String.format(Locale.US, "%s: %f, %s, %f", "x:", event.getX(), "y:", event.getY()); testRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); testFailRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); return true; } } return false; } }); setHandler(); initAntiSetting(); if (OplusTouchHelper.isTPCalibrationSupport(mTpIcId) && TpCommonUtils.isSamsungSoftScreen(mTpIcId)) { mResultTextView.append("\n" + getString(R.string.tp_autotest_soft_screen_warning)); mTouchScreenAutoTest.setBackgroundColor(Color.WHITE); mHandler.sendEmptyMessageDelayed(MSG_START, 1500); } else { mHandler.sendEmptyMessage(MSG_START); } mKeyEventInterceptor.registerKeyEventInterceptor(KeyEventInterceptor.KEY_MODE_FULL_MASK); moveHandler.sendEmptyMessageDelayed(MOVE_WHAT, MOVE_DELEYY); } @Override protected void onPause() { super.onPause(); mKeyEventInterceptor.unregisterKeyEventInterceptor(); moveHandler.removeCallbacksAndMessages(null); } @Override protected void onDestroy() { super.onDestroy(); LcdRefreshRateManager.updateLCMFrequencySetting(this, mScreenRateSettings); if (INVALID_SETTING_PARAMETER != mOldBrightness) { mLightsManager.setLcdBackLightBrightness(this, mOldBrightness); mOldBrightness = INVALID_SETTING_PARAMETER; } if (mOldBrightnessMode != INVALID_SETTING_PARAMETER) { LightsManager.setLcdBrightnessMode(this, mOldBrightnessMode); mOldBrightnessMode = INVALID_SETTING_PARAMETER; } mHandler.removeCallbacksAndMessages(null); mKeyEventInterceptor.unregisterKeyEventInterceptor(); if (mTouchScreenAutoTest != null) { mTouchScreenAutoTest.stop(); } if (mSubHandlerThread != null) { mSubHandlerThread.quit(); } if (mTkHandlerThread != null) { mTkHandlerThread.quit(); } if (testRecord != null) { testRecord.append(getString(R.string.anti_sensor_end_time_info)) .append(getSystemTime()).append("\n"); testRecord.append("-----------------------------------------------"); saveAntiItemRecordToSDcard(testRecord.toString()); testRecord = null; } if (testFailRecord != null) { testFailRecord = null; } if (moveHandler != null) { moveHandler.removeCallbacksAndMessages(null); moveHandler = null; } } private void setHandler() { mHandler = new Handler(mTkHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.i(TAG, "message = " + msg.what); switch (msg.what) { case MSG_START: if (mCycleTimes > 0) { mAntiTouchResult = new AntiTouchResult(AntiTouchResult.ANTI_TOUCH_TESTING, AntiTouchResult.ANTI_TOUCH_NOT_START); mTouchScreenAutoTest.start(); mAntiTouchResultList.add(mAntiTouchResult); mCycleTimes--; runOnUiThread(new Runnable() { @Override public void run() { mTouchCaseAdapter.notifyDataSetChanged(); } }); } else { sendEmptyMessage(MSG_ALL_DONE); } break; case MSG_FIRMWARE: if (mTpAutoTestDone && mScreenOffTpAutoTestDone) { boolean screenOnTpResult = false; boolean screenOffTpResult = false; if (mTpAutoTestResult != null) { screenOnTpResult = mTpAutoTestResult.getTestResult(); Log.i(TAG, "screenOnTpResult = " + screenOnTpResult); } if (mScreenOffTpAutoTestResult != null) { screenOffTpResult = mScreenOffTpAutoTestResult.getTestResult(); Log.i(TAG, "screenOffTpResult = " + screenOffTpResult); } if (screenOnTpResult && screenOffTpResult) { if (mAntiTouchResult != null) { mAntiTouchResult.setAutoTestResult(AntiTouchResult.ANTI_TOUCH_PASS); } } else { testFailRecord.append(getString(R.string.anti_touch_firmware_fail)).append("\n"); if (mAntiTouchResult != null) { mAntiTouchResult.setAutoTestResult(AntiTouchResult.ANTI_TOUCH_FAIL); } } mAntiTouchResult.setTouchResult(AntiTouchResult.ANTI_TOUCH_TESTING); runOnUiThread(new Runnable() { @Override public void run() { mTouchCaseAdapter.notifyDataSetChanged(); } }); mIsTouchNeedStart = true; mTpAutoTestDone = false; mScreenOffTpAutoTestDone = false; sendEmptyMessageDelayed(MSG_TOUCH, mTestTime * 1000); } break; case MSG_TOUCH: mIsTouchNeedStart = false; if (mIsTouchFlag) { if (mAntiTouchResult != null) { mAntiTouchResult.setTouchResult(AntiTouchResult.ANTI_TOUCH_FAIL); } mIsTouchFlag = false; } else { if (mAntiTouchResult != null) { mAntiTouchResult.setTouchResult(AntiTouchResult.ANTI_TOUCH_PASS); } } runOnUiThread(new Runnable() { @Override public void run() { mTouchCaseAdapter.notifyDataSetChanged(); } }); mAntiTouchResult =new AntiTouchResult(); sendEmptyMessage(MSG_START); break; case MSG_ALL_DONE: boolean result = true; for (int i = 0; i < mAntiTouchResultList.size(); i++) { int autoTestResult = mAntiTouchResultList.get(i).isAutoTestResult(); int touchResult = mAntiTouchResultList.get(i).isTouchResult(); if (autoTestResult != AntiTouchResult.ANTI_TOUCH_PASS || touchResult != AntiTouchResult.ANTI_TOUCH_PASS) { result = false; break; } } if (result) { runOnUiThread(new Runnable() { @Override public void run() { mResultTextView.setText(R.string.pass); mResultTextView.setTextColor(Color.GREEN); } }); onAntiPass(); } else { runOnUiThread(new Runnable() { @Override public void run() { mResultTextView.setText(R.string.fail); } }); onAntiFail(testFailRecord.toString()); } break; default: break; } } }; } private void initAntiSetting() { mCycleTimes = TouchAntiItemSetting.getInstance().getAntiTouchCycleTimes(getAntiItemSetting()); Log.i(TAG, "mCycleTimes = " + mCycleTimes); mTestTime =TouchAntiItemSetting.getInstance().getAntiTouchTestTime(getAntiItemSetting()); Log.i(TAG, "mTestTime = " + mTestTime); } private void setLcdBackLightBrightness(int brightness) { Log.i(TAG, "setLcdBackLightBrightness " + brightness); if (Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL != LightsManager.getLcdBrightnessMode(this)) { LightsManager.setLcdBrightnessMode(this, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); } //disable ghbm, avoid light sensor enabled background if (0 != LightsManager.getGlobalHighBrightnessMode(this)) { LightsManager.setGlobalHighBrightnessMode(this, 0); } mLightsManager.setLcdBackLightBrightness(this, brightness); } private String getSystemTime() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss.SSS"); return simpleDateFormat.format(System.currentTimeMillis()); } } 给这段代码加中文注释
07-08
以下是对这段 Android Java 代码的中文注释,帮助理解其结构和功能。该类 `TouchAntiCase` 是一个用于触摸屏抗干扰测试的 Activity 类。 ```java package com.oplus.engineermode.anti.anticase.touch; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.OplusKeyEventManager; import android.provider.Settings; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.oplus.engineermode.R; import com.oplus.engineermode.anti.anticase.AntiCaseBase; import com.oplus.engineermode.anti.bandsetting.rftoolkit.Tech; import com.oplus.engineermode.anti.bandsetting.rftoolkit.TxParam; import com.oplus.engineermode.anti.constant.Constants; import com.oplus.engineermode.anti.utils.Utils; import com.oplus.engineermode.core.sdk.utils.Log; import com.oplus.engineermode.device.base.DeviceManager; import com.oplus.engineermode.display.lcd.base.LcdTimingColorModeManager; import com.oplus.engineermode.display.sdk.LcdRefreshRateManager; import com.oplus.engineermode.lights.base.LightsManager; import com.oplus.engineermode.misc.sdk.utils.OplusMiscHelper; import com.oplus.engineermode.touchpanel.sdk.utils.OplusTouchHelper; import com.oplus.engineermode.touchscreen.base.AutoTestResult; import com.oplus.engineermode.touchscreen.base.TouchScreenAutoTest; import com.oplus.engineermode.touchscreen.base.TpCommonUtils; import com.oplus.engineermode.util.KeyEventInterceptor; import com.oplus.engineermode.util.ProjectFeatureOptions; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class TouchAntiCase extends AntiCaseBase { // TAG 用于日志打印 private static final String TAG = "TouchAntiCase"; // 无效设置参数标记 private static final int INVALID_SETTING_PARAMETER = -1; // Handler 消息类型定义 private static final int MSG_START = 0x11; private static final int MSG_FIRMWARE = 0x12; private static final int MSG_TOUCH = 0x13; private static final int MSG_ALL_DONE = 0x14; // 移动视图延迟时间(毫秒) private static final int MOVE_DELEYY = 10000; private static final int MOVE_WHAT = 1001; // VDET 目标值和单位 private static final int VDET_TARGET_VALUE = 950; private static final int VDET_UNIT = 10; // 自动测试结果对象 private AutoTestResult mTpAutoTestResult; private AutoTestResult mScreenOffTpAutoTestResult; // 触摸屏自动测试类实例 private TouchScreenAutoTest mTouchScreenAutoTest; // 子线程 Handler 实例 private HandlerThread mSubHandlerThread; private HandlerThread mTkHandlerThread; // 测试结果适配器 private TouchCaseAdapter mTouchCaseAdapter; // 测试完成标志 private boolean mTpAutoTestDone; private boolean mScreenOffTpAutoTestDone; // 是否启用触摸屏测试 private boolean mIsTouchScreenTpEnabled = true; // 屏幕刷新率设置 private int mScreenRateSettings; private boolean mIsScreenOffTouchScreenTpEnabled; // 亮度相关变量 private int mOldBrightness = INVALID_SETTING_PARAMETER; private int mOldBrightnessMode = INVALID_SETTING_PARAMETER; // 灯光管理器 private LightsManager mLightsManager; // TP IC ID private int mTpIcId = OplusTouchHelper.DEFAULT_TP_IC_ID; // 循环次数和测试时间 private int mCycleTimes; private int mTestTime; // 触摸标志 private boolean mIsTouchFlag = false; private boolean mIsTouchNeedStart =false; // 根布局和 UI 组件 private RelativeLayout rootView; private TextView mFirmwareTv; private TextView mResultTextView; private ListView mTouchListView; // 测试结果列表 private List<AntiTouchResult> mAntiTouchResultList; // 主 Handler private Handler mHandler; // 测试记录字符串构建器 private StringBuilder testRecord; private StringBuilder testFailRecord; // 当前测试结果对象 private AntiTouchResult mAntiTouchResult; // Tx 参数 private TxParam mTxParam; // 键盘事件拦截器 private final KeyEventInterceptor mKeyEventInterceptor = new KeyEventInterceptor(TouchAntiCase.this, TAG, new OplusKeyEventManager.OnKeyEventObserver() { @Override public void onKeyEvent(KeyEvent keyEvent) { Log.i(TAG, keyEvent.toString()); if ((keyEvent.getAction() == KeyEvent.ACTION_UP) && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK)) { runOnUiThread(new Runnable() { @Override public void run() { Log.i(TAG, "KEYCODE_BACK"); if (testRecord != null) { testRecord.append(getString(R.string.anti_back_pressed)).append("\n"); testFailRecord.append(getString(R.string.anti_back_pressed)).append("\n"); } onAntiSkip(getString(R.string.anti_back_pressed)); } }); } } }); // 自动测试回调接口实现 private final TouchScreenAutoTest.AutoTestCallback mAutoTestCallback = new TouchScreenAutoTest.AutoTestCallback() { @Override public void onScreenOnTpAutoTestDone(AutoTestResult result) { if (result != null) { Log.i(TAG, "onScreenOnTpAutoTestDone " + result.toString()); testRecord.append(getSystemTime()).append("\t").append(getString(R.string.anti_auto_up_callback)) .append(result.toString()).append("\n"); } mTpAutoTestDone = true; mTpAutoTestResult = result; if ((mTpAutoTestResult != null) && !mTpAutoTestResult.getTestResult()) { mScreenOffTpAutoTestDone = true; } mHandler.sendEmptyMessage(MSG_FIRMWARE); } @Override public void onScreenOffTpAutoTestDone(AutoTestResult result) { if (result != null) { Log.i(TAG, "onScreenOffTpAutoTestDone " + result.toString()); testRecord.append(getSystemTime()).append("\t").append(getString(R.string.anti_auto_down_callback)) .append(result.toString()).append("\n"); } mScreenOffTpAutoTestDone = true; mScreenOffTpAutoTestResult = result; mHandler.sendEmptyMessage(MSG_FIRMWARE); } }; // 移动 Handler,模拟界面元素移动 private Handler moveHandler = new Handler() { @Override public void handleMessage(Message message) { super.handleMessage(message); moveHandler.sendEmptyMessageDelayed(MOVE_WHAT, MOVE_DELEYY); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rootView.getLayoutParams(); layoutParams.topMargin += 90; layoutParams.leftMargin += 15; if (layoutParams.topMargin >= 900) { layoutParams.topMargin = 0; layoutParams.leftMargin = 0; } Log.i(TAG, "moveHandler:topMargin:" + layoutParams.topMargin + ",leftMargin:" + layoutParams.leftMargin); rootView.setLayoutParams(layoutParams); } }; // 获取当前测试项名称 @Override protected String getAntiItemName() { return TouchAntiItemSetting.getInstance().getAntiItemName(); } // onCreate 方法初始化界面和相关组件 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.anti_touch_xml); testRecord = new StringBuilder().append(getString(R.string.anti_sensor_start_time_info)) .append(getSystemTime()).append(":").append("\n"); testFailRecord = new StringBuilder(); // 获取传递过来的 TxParam 和功率信息 mTxParam = getIntent().getParcelableExtra(Constants.EXTRA_ANTI_RADIO_TXPARAM); int radioMeasurePower = getIntent().getIntExtra(Constants.EXTRA_ANTI_RADIO_TXMEASURE,Constants.TX_PARAM_DEFAULT_VALUE); Log.d(TAG, "radioMeasurePower : " + radioMeasurePower); if (mTxParam != null) { String txParamInfo = mTxParam.getTxParamInfo(); Log.d(TAG, "txParam info : " + txParamInfo); testRecord.append(getString(R.string.anti_sensor_channel_information)).append(txParamInfo) .append(Utils.getMeasurePowerInfo(getApplicationContext(), radioMeasurePower)).append("\n"); // 设置各种 TextView 显示参数信息 TextView tech = findViewById(R.id.tech_param); tech.setText(mTxParam.getTechInfo()); TextView band = findViewById(R.id.band_param); band.setText(String.valueOf(mTxParam.getBand())); TextView antenna = findViewById(R.id.antenna_param); antenna.setText(String.valueOf(mTxParam.getAntenna())); TextView channelType = findViewById(R.id.channelType_param); channelType.setText(mTxParam.getChannelTypeInfo()); TextView power = findViewById(R.id.power_param); TextView measurePower = findViewById(R.id.measure_power); if (Tech.BDS.name().equals(mTxParam.getTechInfo())) { TextView powerTitle = findViewById(R.id.power_title); powerTitle.setText(getString(R.string.anti_dialog_target_VDET)); TextView measurePowerTitle = findViewById(R.id.measure_power_title); measurePowerTitle.setText(getString(R.string.anti_dialog_measure_VDET)); power.setText(String.valueOf(VDET_TARGET_VALUE)); measurePower.setText(String.valueOf(radioMeasurePower / VDET_UNIT)); } else { power.setText(String.valueOf(mTxParam.getPower())); measurePower.setText(String.valueOf(radioMeasurePower)); } } // 初始化 UI 组件 rootView = findViewById(R.id.rootView); mResultTextView = findViewById(R.id.result_tv); mFirmwareTv = findViewById(R.id.anti_firmware); mTouchListView = findViewById(R.id.anti_touch_listview); mAntiTouchResultList = new ArrayList<>(); mTouchCaseAdapter = new TouchCaseAdapter(this, mAntiTouchResultList); mTouchListView.setAdapter(mTouchCaseAdapter); // 初始化显示设置和灯光管理器 mScreenRateSettings = LcdRefreshRateManager.queryLCMFrequencySetting(this); mLightsManager = new LightsManager(this); final int maxBrightness = mLightsManager.getLcdBacklightMaximumBrightnessLevel(); mOldBrightness = mLightsManager.getLcdBackLightBrightness(this); mOldBrightnessMode = LightsManager.getLcdBrightnessMode(this); if (ProjectFeatureOptions.FEATURE_ARIES_DISPLAY) { LcdTimingColorModeManager.displayTimingAndColorModeInit(getApplicationContext()); LcdTimingColorModeManager.setRefreshRateByMode(120.0f); } else { LcdRefreshRateManager.updateLCMFrequencySetting(this, LcdRefreshRateManager.REFRESH_RATE_60HZ); } Log.i(TAG, "mMaxBrightness: " + maxBrightness + ", mOldBrightness: " + mOldBrightness + ", FEATURE_ARIES_DISPLAY=" + ProjectFeatureOptions.FEATURE_ARIES_DISPLAY); setLcdBackLightBrightness(maxBrightness); mIsScreenOffTouchScreenTpEnabled = false; // 获取 TP 设备信息并设置固件版本 final String tpDeviceInfo = OplusMiscHelper.getTPDeviceInfo(mTpIcId); final String strProductVersion = getResources().getString(R.string.tp_bin_version) + DeviceManager.getVersionFromDeviceInfo(tpDeviceInfo); mFirmwareTv.setText(strProductVersion); mResultTextView.setText(R.string.tp_autotest_warning); // 创建 HandlerThread 并启动 mSubHandlerThread = new HandlerThread("ANTI_TOUCH_PANEL_AUTO_TEST"); mSubHandlerThread.start(); mTkHandlerThread = new HandlerThread("ANTI_TOUCH_RESULT"); mTkHandlerThread.start(); // 初始化 TouchScreenAutoTest mTouchScreenAutoTest = new TouchScreenAutoTest(this, getMainLooper(), mSubHandlerThread.getLooper()); mTouchScreenAutoTest.setTpIcId(mTpIcId); mTouchScreenAutoTest.init(mIsTouchScreenTpEnabled, mIsScreenOffTouchScreenTpEnabled); mTouchScreenAutoTest.setAutoTestCallback(mAutoTestCallback); mTouchScreenAutoTest.setAgingMode(true); } // onTouchEvent 处理触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { Log.i(TAG, "TouchEvent action =" + event.getAction()); if (mIsTouchNeedStart) { if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) { mIsTouchFlag = true; String format = String.format(Locale.US, "%s: %.2f, %s, %.2f", "x:", event.getX(), "y:", event.getY()); testRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); testFailRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); return true; } } return false; } // onResume 中注册监听器并启动测试 @Override protected void onResume() { super.onResume(); mTouchListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.i(TAG, "OnTouchListener action = " + event.getAction()); if (mIsTouchNeedStart) { if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) { mIsTouchFlag = true; String format = String.format(Locale.US, "%s: %f, %s, %f", "x:", event.getX(), "y:", event.getY()); testRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); testFailRecord.append(getString(R.string.anti_touch_fail)).append(format).append("\n"); return true; } } return false; } }); setHandler(); initAntiSetting(); if (OplusTouchHelper.isTPCalibrationSupport(mTpIcId) && TpCommonUtils.isSamsungSoftScreen(mTpIcId)) { mResultTextView.append("\n" + getString(R.string.tp_autotest_soft_screen_warning)); mTouchScreenAutoTest.setBackgroundColor(Color.WHITE); mHandler.sendEmptyMessageDelayed(MSG_START, 1500); } else { mHandler.sendEmptyMessage(MSG_START); } mKeyEventInterceptor.registerKeyEventInterceptor(KeyEventInterceptor.KEY_MODE_FULL_MASK); moveHandler.sendEmptyMessageDelayed(MOVE_WHAT, MOVE_DELEYY); } // onPause 中取消注册监听器 @Override protected void onPause() { super.onPause(); mKeyEventInterceptor.unregisterKeyEventInterceptor(); moveHandler.removeCallbacksAndMessages(null); } // onDestroy 清理资源 @Override protected void onDestroy() { super.onDestroy(); LcdRefreshRateManager.updateLCMFrequencySetting(this, mScreenRateSettings); if (INVALID_SETTING_PARAMETER != mOldBrightness) { mLightsManager.setLcdBackLightBrightness(this, mOldBrightness); mOldBrightness = INVALID_SETTING_PARAMETER; } if (mOldBrightnessMode != INVALID_SETTING_PARAMETER) { LightsManager.setLcdBrightnessMode(this, mOldBrightnessMode); mOldBrightnessMode = INVALID_SETTING_PARAMETER; } mHandler.removeCallbacksAndMessages(null); mKeyEventInterceptor.unregisterKeyEventInterceptor(); if (mTouchScreenAutoTest != null) { mTouchScreenAutoTest.stop(); } if (mSubHandlerThread != null) { mSubHandlerThread.quit(); } if (mTkHandlerThread != null) { mTkHandlerThread.quit(); } if (testRecord != null) { testRecord.append(getString(R.string.anti_sensor_end_time_info)) .append(getSystemTime()).append("\n"); testRecord.append("-----------------------------------------------"); saveAntiItemRecordToSDcard(testRecord.toString()); testRecord = null; } if (testFailRecord != null) { testFailRecord = null; } if (moveHandler != null) { moveHandler.removeCallbacksAndMessages(null); moveHandler = null; } } // 设置 Handler,处理不同消息 private void setHandler() { mHandler = new Handler(mTkHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.i(TAG, "message = " + msg.what); switch (msg.what) { case MSG_START: if (mCycleTimes > 0) { mAntiTouchResult = new AntiTouchResult(AntiTouchResult.ANTI_TOUCH_TESTING, AntiTouchResult.ANTI_TOUCH_NOT_START); mTouchScreenAutoTest.start(); mAntiTouchResultList.add(mAntiTouchResult); mCycleTimes--; runOnUiThread(new Runnable() { @Override public void run() { mTouchCaseAdapter.notifyDataSetChanged(); } }); } else { sendEmptyMessage(MSG_ALL_DONE); } break; case MSG_FIRMWARE: if (mTpAutoTestDone && mScreenOffTpAutoTestDone) { boolean screenOnTpResult = false; boolean screenOffTpResult = false; if (mTpAutoTestResult != null) { screenOnTpResult = mTpAutoTestResult.getTestResult(); Log.i(TAG, "screenOnTpResult = " + screenOnTpResult); } if (mScreenOffTpAutoTestResult != null) { screenOffTpResult = mScreenOffTpAutoTestResult.getTestResult(); Log.i(TAG, "screenOffTpResult = " + screenOffTpResult); } if (screenOnTpResult && screenOffTpResult) { if (mAntiTouchResult != null) { mAntiTouchResult.setAutoTestResult(AntiTouchResult.ANTI_TOUCH_PASS); } } else { testFailRecord.append(getString(R.string.anti_touch_firmware_fail)).append("\n"); if (mAntiTouchResult != null) { mAntiTouchResult.setAutoTestResult(AntiTouchResult.ANTI_TOUCH_FAIL); } } mAntiTouchResult.setTouchResult(AntiTouchResult.ANTI_TOUCH_TESTING); runOnUiThread(new Runnable() { @Override public void run() { mTouchCaseAdapter.notifyDataSetChanged(); } }); mIsTouchNeedStart = true; mTpAutoTestDone = false; mScreenOffTpAutoTestDone = false; sendEmptyMessageDelayed(MSG_TOUCH, mTestTime * 1000); } break; case MSG_TOUCH: mIsTouchNeedStart = false; if (mIsTouchFlag) { if (mAntiTouchResult != null) { mAntiTouchResult.setTouchResult(AntiTouchResult.ANTI_TOUCH_FAIL); } mIsTouchFlag = false; } else { if (mAntiTouchResult != null) { mAntiTouchResult.setTouchResult(AntiTouchResult.ANTI_TOUCH_PASS); } } runOnUiThread(new Runnable() { @Override public void run() { mTouchCaseAdapter.notifyDataSetChanged(); } }); mAntiTouchResult = new AntiTouchResult(); sendEmptyMessage(MSG_START); break; case MSG_ALL_DONE: boolean result = true; for (int i = 0; i < mAntiTouchResultList.size(); i++) { int autoTestResult = mAntiTouchResultList.get(i).isAutoTestResult(); int touchResult = mAntiTouchResultList.get(i).isTouchResult(); if (autoTestResult != AntiTouchResult.ANTI_TOUCH_PASS || touchResult != AntiTouchResult.ANTI_TOUCH_PASS) { result = false; break; } } if (result) { runOnUiThread(new Runnable() { @Override public void run() { mResultTextView.setText(R.string.pass); mResultTextView.setTextColor(Color.GREEN); } }); onAntiPass(); } else { runOnUiThread(new Runnable() { @Override public void run() { mResultTextView.setText(R.string.fail); } }); onAntiFail(testFailRecord.toString()); } break; default: break; } } }; } // 初始化测试设置参数 private void initAntiSetting() { mCycleTimes = TouchAntiItemSetting.getInstance().getAntiTouchCycleTimes(getAntiItemSetting()); Log.i(TAG, "mCycleTimes = " + mCycleTimes); mTestTime = TouchAntiItemSetting.getInstance().getAntiTouchTestTime(getAntiItemSetting()); Log.i(TAG, "mTestTime = " + mTestTime); } // 设置屏幕亮度 private void setLcdBackLightBrightness(int brightness) { Log.i(TAG, "setLcdBackLightBrightness " + brightness); if (Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL != LightsManager.getLcdBrightnessMode(this)) { LightsManager.setLcdBrightnessMode(this, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); } if (0 != LightsManager.getGlobalHighBrightnessMode(this)) { LightsManager.setGlobalHighBrightnessMode(this, 0); } mLightsManager.setLcdBackLightBrightness(this, brightness); } // 获取系统时间 private String getSystemTime() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss.SSS"); return simpleDateFormat.format(System.currentTimeMillis()); } } ``` --- ### 解释 - **类结构**:`TouchAntiCase` 继承自 `AntiCaseBase`,是用于执行触摸屏抗干扰测试的 Activity。 - **常量与变量**: - 定义了多个常量,如消息类型、延时时间等。 - 使用 `HandlerThread` 创建子线程处理任务。 - 包含多个 UI 控件引用、测试状态变量等。 - **onCreate**:初始化界面、获取传入数据、配置显示设置、创建测试线程。 - **onResume/onPause**:注册/注销触摸事件监听器和按键事件拦截器。 - **Handler 消息机制**:通过 `mHandler` 处理测试流程控制,包括开始测试、等待测试完成、判断是否失败、结束测试等。 - **触摸事件处理**:在 `onTouchEvent` 和 `OnTouchListener` 中记录用户触摸行为,用于判断是否有异常操作。 - **清理资源**:在 `onDestroy` 中释放所有资源,保存测试记录。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值