这篇主要是具体例子,可以先看一下理论,网址是:Android中Preference的使用以及监听事件分析

我们可以先看一下效果图


我们先截取不小段布局,代码如下:

<ListPreference
android:defaultValue="@string/usb_default_value"
android:dialogTitle="@string/test_USB_change"
android:entries="@array/USBChange"
android:entryValues="@array/USBChange_value"
android:key="key_amt3_USB_change"
android:title="@string/test_USB_change" >
</ListPreference>

我们可以看见代码中引用到了string和array,也给出相应的代码,array相对重要些:

<string name="test_USB_change">USB 切换</string>
<string name="usb_default_value">001</string>
 <string-array name="USBChange"><item>AP</item><item>CP</item><item>CP Update</item><item>@string/EncryptionCard</item></string-array><string-array name="USBChange_value"><item>001</item><item>002</item><item>003</item><item>004</item></string-array>
array由2块组成,下面为具体的java代码,本身为了记录,没有处理,很容易看懂

package com.leadcore.amt3;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemProperties;
import android.os.PowerManager;
import android.app.AlertDialog.Builder;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.widget.Toast;
import android.util.Log;
import com.android.internal.telephony.TelephonyIntents;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.preference.ListPreference;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;

/**
* AMT3 main entry
*/
public class Amt3MainActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener {

/**
* TAG
*/
private static final String TAG = "Amt3MainActivity";

private static final String KEY_AMT3_CONTINUOUS_TEST = "key_amt3_continuous_test";
private static final String KEY_AMT3_INDIVIDUAL_TEST = "key_amt3_individual_test";
private static final String KEY_AMT3_TEST_RESULT = "key_amt3_test_result";
private static final String KEY_AMT3_CUSTOM_CALIBRATION_STATION = "key_amt3_custom_calibration_station";
private static final String KEY_AMT3_USB_AMT1 = "key_amt3_usb_amt1";
private static final String KEY_AMT3_USB_ChANGE = "key_amt3_USB_change";
private static final String KEY_AMT3_ROOT_ChANGE = "key_amt3_ROOT_change";
private static final String KEY_AMT3_TEST_RESTART_CP = "key_amt3_test_restart_CP";

private static final String STATUS = "amt.normal.amt.switch_status";

public static final String PROPERTY_AMT3_MMI_STATION = "persist.sys.lc.amt.mmi.station";

public static final String MMI_PASS = "MMI-PASS";

public static final String MMI_FAIL = "MMI-FAIL";

public static final String MMI_NO_TEST = "MMI-NO-TEST";

/**
* Initialize AMT Service failed.
*/
private static final int MSG_ID_MAIN_AMT3_INIT_FAILED = 1;

private Preference mContinuousTest = null;
private Preference mIndividualTest = null;
private Preference mTestResult = null;
private Preference mCalibration = null;
private CheckBoxPreference mCheckBoxPreference = null;
private ListPreference mUSBPreference = null;
private ListPreference mROOTPreference = null;
private Preference mRestartCP = null;

/**
* To receive message
* MSG_ID_MAIN_AMT3_INIT_FAILED.
*/
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.v(TAG, "handleMessage msg.what = " + msg.what);
if (msg.what == MSG_ID_MAIN_AMT3_INIT_FAILED) {
mContinuousTest.setEnabled(false);
mIndividualTest.setEnabled(false);
mTestResult.setEnabled(false);
mCalibration.setEnabled(false);
mUSBPreference.setEnabled(false);
mROOTPreference.setEnabled(false);
mRestartCP.setEnabled(false);
} else {
Log.v(TAG, "handleMessage invalid message");
}
}
};

private boolean isKillProcess = false;

public static Activity mActivity = null;

private boolean mGpsEnabled;

private WifiManager wifiManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate");
super.onCreate(savedInstanceState);

int isFinish = getIntent().getIntExtra("finish", 0);
boolean isHistory = ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0);
Log.v(TAG, "onCreate isFinish = " + isFinish + " isHistory = " + isHistory);

if (isHistory) {
Log.v(TAG, "onCreate launch from history");
int status = SystemProperties.getInt(STATUS, 0);
Log.v(TAG, "onCreate status = " + status);
if (1 == status) {
Log.v(TAG, "onCreate in AMT MODE exit");
Toast.makeText(Amt3MainActivity.this, R.string.amt_in_amt_mode_exit, Toast.LENGTH_SHORT).show();
//isKillProcess = true;
if (Amt3ChangeModeActivity.mActivity != null) {
isKillProcess = true;
}
finish();

//Intent intent = new Intent("android.action.amt3.start");
//sendBroadcast(intent);

return;
}
} else {
if (isFinish == 1) {
finish();
return;
}
}

addPreferencesFromResource(R.layout.amt3_main_activity);

mContinuousTest = findPreference(KEY_AMT3_CONTINUOUS_TEST);
mIndividualTest = findPreference(KEY_AMT3_INDIVIDUAL_TEST);
mTestResult = findPreference(KEY_AMT3_TEST_RESULT);
mCalibration = findPreference(KEY_AMT3_CUSTOM_CALIBRATION_STATION);
mCheckBoxPreference = (CheckBoxPreference)findPreference(KEY_AMT3_USB_AMT1);
mUSBPreference = (ListPreference)findPreference(KEY_AMT3_USB_ChANGE);
mROOTPreference = (ListPreference)findPreference(KEY_AMT3_ROOT_ChANGE);
mRestartCP = findPreference(KEY_AMT3_TEST_RESTART_CP);

mContinuousTest.setLayoutResource(R.layout.main_preference);
mIndividualTest.setLayoutResource(R.layout.main_preference);
mTestResult.setLayoutResource(R.layout.main_preference);
mCalibration.setLayoutResource(R.layout.main_preference);

mUSBPreference.setOnPreferenceChangeListener(this);
mROOTPreference.setOnPreferenceChangeListener(this);

int ret = TestWrap.init();
Log.v(TAG, "onCreate initialize = " + ret);
//if (ret < 0) {
// Toast.makeText(this, "error in mode initialization", Toast.LENGTH_LONG).show();
// mHandler.sendEmptyMessageDelayed(MSG_ID_MAIN_AMT3_INIT_FAILED, 100);
//}

mActivity = this;

mGpsEnabled = Settings.Secure.isLocationProviderEnabled(getContentResolver(),
LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(getContentResolver(),
LocationManager.GPS_PROVIDER, true);
Log.d("leo","onCreate mGpsEnabled:"+mGpsEnabled);
//[yeez_yuxiang.zhang added 2013.5.2 start. start locating at first]
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = lm.getBestProvider(criteria, true);
lm.requestLocationUpdates(provider, 1*1000, 100, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {}
});

wifiManager = (WifiManager) getSystemService(Service.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}


@Override
protected void onResume() {
SystemProperties.set("persist.sys.amt3", "1");
Log.v(TAG, "onResume");
super.onResume();

int status = SystemProperties.getInt(STATUS, 0);
Log.v(TAG, "onResume status = " + status);
if (1 == status) {
Log.v(TAG, "onResume in AMT MODE exit");
Toast.makeText(Amt3MainActivity.this, R.string.amt_in_amt_mode_exit, Toast.LENGTH_SHORT).show();
//isKillProcess = true;
if (Amt3ChangeModeActivity.mActivity != null) {
isKillProcess = true;
}
finish();

//Intent intent = new Intent("android.action.amt3.start");
//sendBroadcast(intent);
} else {
//mCheckBoxPreference.setChecked(isUsbAmt1());
mCheckBoxPreference.setChecked(Utils.isPowerUsbAmt1());
}

SystemProperties.get("debug.mgrt.set");
}

/**
* Called as part of the activity lifecycle when an activity is going into
* the background, but has not (yet) been killed. The counterpart to
* {@link #onResume}.
*
* <p>When activity B is launched in front of activity A, this callback will
* be invoked on A. B will not be created until A's {@link #onPause} returns,
* so be sure to not do anything lengthy here.
*
* <p>This callback is mostly used for saving any persistent state the
* activity is editing, to present a "edit in place" model to the user and
* making sure nothing is lost if there are not enough resources to start
* the new activity without first killing this one. This is also a good
* place to do things like stop animations and other things that consume a
* noticeable amount of CPU in order to make the switch to the next activity
* as fast as possible, or to close resources that are exclusive access
* such as the camera.
*
* <p>In situations where the system needs more memory it may kill paused
* processes to reclaim resources. Because of this, you should be sure
* that all of your state is saved by the time you return from
* this function. In general {@link #onSaveInstanceState} is used to save
* per-instance state in the activity and this method is used to store
* global persistent data (in content providers, files, etc.)
*
* <p>After receiving this call you will usually receive a following call
* to {@link #onStop} (after the next activity has been resumed and
* displayed), however in some cases there will be a direct call back to
* {@link #onResume} without going through the stopped state.
*
* <p><em>Derived classes must call through to the super class's
* implementation of this method. If they do not, an exception will be
* thrown.</em></p>
*/
@Override
protected void onPause() {
Log.v(TAG, "onPause");
super.onPause();
}

/**
* Perform any final cleanup before an activity is destroyed. This can
* happen either because the activity is finishing (someone called
* {@link #finish} on it, or because the system is temporarily destroying
* this instance of the activity to save space. You can distinguish
* between these two scenarios with the {@link #isFinishing} method.
*
* <p><em>Note: do not count on this method being called as a place for
* saving data! For example, if an activity is editing data in a content
* provider, those edits should be committed in either {@link #onPause} or
* {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
* free resources like threads that are associated with an activity, so
* that a destroyed activity does not leave such things around while the
* rest of its application is still running. There are situations where
* the system will simply kill the activity's hosting process without
* calling this method (or any others) in it, so it should not be used to
* do things that are intended to remain around after the process goes
* away.
*
* <p><em>Derived classes must call through to the super class's
* implementation of this method. If they do not, an exception will be
* thrown.</em></p>
*/
@Override
protected void onDestroy() {
Log.v(TAG, "onDestroy");
Settings.Secure.setLocationProviderEnabled(getContentResolver(),
LocationManager.GPS_PROVIDER, mGpsEnabled);
super.onDestroy();

updateTestResultSummary();

int ret = TestWrap.deinit();
Log.v(TAG, "onDestroy finalize = " + ret);
//if (ret < 0) {
// Toast.makeText(this, "error in mode finalization", Toast.LENGTH_LONG).show();
//}

if (isKillProcess) {
Log.v(TAG, "onDestroy KillProcess");
//android.os.Process.killProcess(android.os.Process.myPid());
Intent intent = new Intent(TelephonyIntents.SECRET_CODE_ACTION,
Uri.parse("android_secret_code://" + "388"));
sendBroadcast(intent);
}

mActivity = null;
SystemProperties.set("persist.sys.amt3", "0");
}

/**
* This is called for activities that set launchMode to "singleTop" in
* their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
* flag when calling {@link #startActivity}. In either case, when the
* activity is re-launched while at the top of the activity stack instead
* of a new instance of the activity being started, onNewIntent() will be
* called on the existing instance with the Intent that was used to
* re-launch it.
*
* <p>An activity will always be paused before receiving a new intent, so
* you can count on {@link #onResume} being called after this method.
*
* <p>Note that {@link #getIntent} still returns the original Intent. You
* can use {@link #setIntent} to update it to this new Intent.
*
* @param intent The new intent that was started for the activity.
*/
@Override
protected void onNewIntent(Intent intent) {
Log.v(TAG, "onNewIntent");
int isFinish = getIntent().getIntExtra("finish", 0);
Log.v(TAG, "onNewIntent isFinish = " + isFinish);
int status = SystemProperties.getInt(STATUS, 0);
Log.v(TAG, "onNewIntent status = " + status);
if (1 == status || 1 == isFinish) {
Toast.makeText(Amt3MainActivity.this, R.string.amt_in_amt_mode_exit, Toast.LENGTH_SHORT).show();
isKillProcess = true;
finish();
}
}

/**
* Called when a preference in the tree rooted at this
* {@link PreferenceScreen} has been clicked.
*
* @param preferenceScreen The {@link PreferenceScreen} that the
* preference is located in.
* @param preference The preference that was clicked.
* @return Whether the click was handled.
*/
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
Log.v(TAG, "onPreferenceTreeClick preference = " + preference.getKey());
if (preference == mContinuousTest) {
Intent intent = new Intent();
intent.setClass(this, Amt3ContinuousTestActivity.class);
startActivity(intent);
} else if (preference == mIndividualTest) {
Intent intent = new Intent();
intent.setClass(this, Amt3IndividualTestActivity.class);
startActivity(intent);
} else if (preference == mTestResult) {
Intent intent = new Intent();
intent.setClass(this, Amt3ResultSummaryActivity.class);
intent.putExtra("mode", TestWrap.TEST_MODE_SUMMARY);
startActivity(intent);
} else if (preference == mCalibration) {
Intent intent = new Intent();
intent.setClass(this, Amt3CalibrationActivity.class);
startActivity(intent);
} else if (preference == mCheckBoxPreference) {
clickCheckBoxPreference();
} else if (preference == mUSBPreference) {

} else if (preference == mROOTPreference) {

} else if (preference == mRestartCP) {
setFile("/sys/misc-config/modem_pwr", "0");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setFile("/sys/misc-config/modem_pwr", "1");
setFile("/sys/misc-config/spower_key", "1");
Toast.makeText(this, getString(R.string.restart_cp_result), Toast.LENGTH_SHORT).show();
} else {
Log.v(TAG, "onPreferenceTreeClick preference invalid");
}

return super.onPreferenceTreeClick(preferenceScreen, preference);
}

private boolean isUsbAmt1() {
int result = Native.app_amt3_usb_amt1(2);
Log.v(TAG, "isUsbAmt1 result = " + result);
if (1 == result) {
return true;
}

return false;
}

private void clickCheckBoxPreference() {
int result = -1;
mCheckBoxPreference.setEnabled(false);
ProgressDialog pdialog = new ProgressDialog(Amt3MainActivity.this);
pdialog.setMessage(getString(R.string.waiting));
pdialog.setIndeterminate(true);
pdialog.setCancelable(false);
pdialog.setCanceledOnTouchOutside(false);
pdialog.show();
Log.v(TAG, "clickCheckBoxPreference ProgressDialog show");
boolean isChecked = mCheckBoxPreference.isChecked();
Log.v(TAG, "clickCheckBoxPreference isChecked = " + isChecked);
mCheckBoxPreference.setChecked(!isChecked);
if (isChecked) {
result = Native.app_amt3_usb_amt1(1);
} else {
result = Native.app_amt3_usb_amt1(0);
}
Log.v(TAG, "clickCheckBoxPreference result = " + result);
if (0 != result) {
mCheckBoxPreference.setChecked(!isChecked);
Log.v(TAG, "clickCheckBoxPreference set failed");
} else {
mCheckBoxPreference.setChecked(isChecked);
}
pdialog.dismiss();
pdialog = null;
Log.v(TAG, "clickCheckBoxPreference ProgressDialog dismiss");
mCheckBoxPreference.setEnabled(true);
}

private int updateTestResultSummary() {
boolean isAllPass = true;
boolean isAllNoTest = true;
Log.v(TAG, "updateTestResultSummary");

final String mMmiStation = SystemProperties.get(PROPERTY_AMT3_MMI_STATION, "18");
Log.v(TAG, "updateTestResultSummary mMmiStation = " + mMmiStation);
int station = Integer.parseInt(mMmiStation);
if (station < 13 || station > 18) {
Log.v(TAG, "updateTestResultSummary invalid station index");
return -1;
}

int result = TestWrap.readStation(station);
String description = TestWrap.readStationDescription(station);
Log.v(TAG, "updateTestResultSummary description = " + description + " result = " + result);

DataBuilder mDataBuilder = DataBuilder.getInstance(this);
List<ITestItem> mItemsList = mDataBuilder.getContinuousTestItemsList();
for (ITestItem it: mItemsList) {
String key = it.getKey();
int itemResult = TestWrap.readResult(key);
Log.v(TAG, "updateTestResultSummary key = " + key + " itemResult = " + itemResult);
if (itemResult == TestWrap.RESULT_PASS) {
isAllNoTest = false;
} else if (itemResult == TestWrap.RESULT_FAIL) {
isAllPass = false;
isAllNoTest = false;
} else if (itemResult == TestWrap.RESULT_NO_TEST) {
isAllPass = false;
}
}
Log.v(TAG, "updateTestResultSummary isAllPass = " + isAllPass + " isAllNoTest = " + isAllNoTest);

if (isAllPass) {
description = MMI_PASS;
result = TestWrap.RESULT_PASS;
} else if (isAllNoTest) {
description = MMI_NO_TEST;
result = TestWrap.RESULT_NO_TEST;
} else {
description = MMI_FAIL;
result = TestWrap.RESULT_FAIL;
}
Log.v(TAG, "updateTestResultSummary description = " + description + " result = " + result);

return TestWrap.writeStationDescription(station, result, description);
}

public boolean onPreferenceChange(Preference preference, Object objValue) {
Log.v(TAG, "onPreferenceChange----->"+String.valueOf(preference.getKey()));
if (preference == mUSBPreference){
Log.v(TAG, " Old Value"+ mUSBPreference.getValue()+" NewDeptName"+objValue);
if(objValue.equals("001")){
setFile("/sys/misc-config/usbsw", "0");
}else if(objValue.equals("002")){
setFile("/sys/misc-config/usbsw", "1");
}else if(objValue.equals("003")){
setFile("/sys/misc-config/usbsw", "1");
setFile("/sys/misc-config/spower", "3");
}else if(objValue.equals("004")){

}
}else if(preference == mROOTPreference){

Log.v(TAG, " Old Value2"+ mROOTPreference.getValue()+" NewDeptName2"+objValue);
if(objValue.equals("005")){
SystemProperties.set("debug.mgrt.set","0");
dialogExit(Amt3MainActivity.this,getString(R.string.CommonlyPattern));
}else if(objValue.equals("006")){
SystemProperties.set("debug.mgrt.set","1");
dialogExit(Amt3MainActivity.this,getString(R.string.RootPattern));
}
}
return true;
}

void setFile(String path, String val) {
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
byte[] buf = val.getBytes();
out.write(buf, 0, buf.length);
} catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException: setFile " + e);
} catch (IOException e) {
Log.e(TAG, "IOException: setFile " + e);
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}

String getFile(String path) {
FileInputStream is = null;
String val = null;
try {
is = new FileInputStream(path);
byte[] buffer = new byte[64];
int count = is.read(buffer);
if (count > 0) {
val = new String(buffer, 0, count);
}
} catch (IOException e) {
Log.d(TAG, "IOException: getFile " + e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (val != null) {
val = val.trim();
}
return val;
}


void dialogExit(Context context,String name){

AlertDialog.Builder builder = new Builder(context);
builder.setMessage(name+getString(R.string.comfirm_restart));
builder.setTitle(R.string.prompt);
builder.setPositiveButton(R.string.ok,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();

}
});
builder.create().show();

}


}







更多相关文章

  1. Android Studio中如何编写JNI代码及编译so库
  2. 编译Android4.3内核源代码
  3. Java se之静态代码块、代码块、构造函数执行顺序问题
  4. Java普通代码块,构造代码块,静态代码块区别,执行顺序的代码实例
  5. 编写自己的代码库(javascript常用实例的实现与封装)[转]
  6. 一篇不错的Android Audio架构代码梳理总结
  7. demo_代码注册广播接受者_Service
  8. Android学习笔记--《第一行代码Android》273页代码解密
  9. Linux下 使用Repo和Git下载Android源代码并编译

随机推荐

  1. android 系统开发之开机动画
  2. android ndk log
  3. Android的selector,背景选择器
  4. Android多分辨率适配框架(2)— 原理剖析
  5. 性能优化之Java(Android)代码优化
  6. Android UI布局之RelativeLayout
  7. Android 第七课——UI布局
  8. Android(安卓)Studio 3.5 安装apk失败问
  9. (4.1.23)Android Animation学习笔记
  10. Android之TextView------属性大全