ディレクトリ 検索
android Manifest Manifest.permission Manifest.permission_group android.accessibilityservice AccessibilityService android.accounts Account android.app NotificationManager android.bluetooth BluetoothAdapter BluetoothClass BluetoothClass.Device BluetoothClass.Device.Major BluetoothClass.Service BluetoothDevice BluetoothServerSocket BluetoothSocket android.content SharedPreferences android.database.sqlite SQLiteCursorDriver SQLiteOpenHelper android.graphics Bitmap android.location LocationListener Geocoder GpsStatus GpsStatus.Listener GpsStatus.NmeaListener GpsSatellite android.media AudioFormat AsyncPlayer AudioRecord AudioRecord.OnRecordPositionUpdateListener ThumbnailUtils AudioManager android.net TrafficStats MailTo LocalSocket android.os AsyncTask AsyncTask.Status CountDownTimer Message MessageQueue HandlerThread android.text Html android.util JsonWriter android.view ContextMenu ContextMenu.ContextMenuInfo Display ViewManager View ViewStub ViewTreeObserver ViewParent WindowManager GestureDetector Gravity MenuInflater ScaleGestureDetector SoundEffectConstants android.view.inputmethod InputConnection InputMethod InputMethodSession BaseInputConnection InputMethodManager android.widget AbsListView AbsListView.LayoutParams AbsListView.OnScrollListener AbsListView.RecyclerListener AbsoluteLayout AbsoluteLayout.LayoutParams AbsSeekBar AbsSpinner AdapterView AdapterView.AdapterContextMenuInfo AdapterView.OnItemLongClickListener AdapterView.OnItemSelectedListener AdapterView.OnItemClickListener AnalogClock BaseAdapter BaseExpandableListAdapter Button CheckBox CheckedTextView Checkable Chronometer Chronometer.OnChronometerTickListener CompoundButton CompoundButton.OnCheckedChangeListener CursorAdapter CursorTreeAdapter DatePicker DatePicker.OnDateChangedListener DialerFilter DigitalClock EditText Filter Filter.FilterListener Filter.FilterResults ExpandableListAdapter ExpandableListView.OnChildClickListener ExpandableListView.OnGroupClickListener ExpandableListView.OnGroupCollapseListener ExpandableListView.OnGroupExpandListener Filterable Gallery Gallery.LayoutParams GridView GridLayout GridLayout.Alignment RadioGroup ImageView ImageView.ScaleType HorizontalScrollView ImageButton ImageSwitcher FilterQueryProvider ListAdapter ListView MediaController MultiAutoCompleteTextView MultiAutoCompleteTextView.CommaTokenizer MultiAutoCompleteTextView.Tokenizer QuickContactBadge RadioButton RatingBar RatingBar.OnRatingBarChangeListener RelativeLayout RemoteViews ResourceCursorAdapter ResourceCursorTreeAdapter Scroller ScrollView SearchView SearchView.OnCloseListener SearchView.OnQueryTextListener SearchView.OnSuggestionListener SeekBar SeekBar.OnSeekBarChangeListener SimpleAdapter SimpleAdapter.ViewBinder SimpleCursorAdapter SimpleCursorAdapter.CursorToStringConverter SimpleCursorAdapter.ViewBinder SimpleCursorTreeAdapter SimpleCursorTreeAdapter.ViewBinder SimpleExpandableListAdapter SlidingDrawer SlidingDrawer.OnDrawerCloseListener SlidingDrawer.OnDrawerOpenListener SlidingDrawer.OnDrawerScrollListener Spinner SpinnerAdapter WrapperListAdapter TabHost TabHost.TabSpec TextView TimePicker TimePicker.OnTimeChangedListener Toast TableLayout TableLayout.LayoutParams TableRow TableRow.LayoutParams TabWidget TextSwitcher ToggleButton TwoLineListItem VideoView ViewAnimator ViewFlipper ViewSwitcher ViewSwitcher.ViewFactory ZoomButtonsController ZoomButtonsController.OnZoomListener ZoomButton ZoomControls dalvik.system DexFile
テキスト


SharedPreferences

翻译版本:2010-11-1

结构

继承关系

public interfaceSharedPreferences

android.content.SharedPreferences

类概述

用于访问和修改getSharedPreferences(String, int)返回偏好设置数据(preference data)的一个接口。对于任何一组特殊的preferences,所有的客户端共享一个此类单独的实例。

修改Preferences必须通过一个SharedPreferences.Editor对象,以确保当他们提交存储数据的操作时,preference值保持一致的状态。

注意:当前此类不支持多线程访问。后续将添加。

(译者注:这里译为偏好设定,类似于ini文件,用于保存应用程序的属性设置)

参见

getSharedPreferences(String, int)

内部类

interface SharedPreferences.Editor

用于修改SharedPreferences对象设定值的接口。

interface SharedPreferences.OnSharedPreferenceChangeListener

接口定义一个用于在偏好设定(shared preference)改变时调用的回调函数。

公共方法

public abstract booleancontains(String key)

判断preferences是否包含一个preference

参数

key想要判断的preference的名称

返回值

如果preferences中存在preference,则返回true,否则返回false

public abstract SharedPreferences.Editoredit()

针对preferences创建一个新的Editor对象,通过它你可以修改preferences里的数据,并且原子化的将这些数据提交回SharedPreferences对象。(译者注:原子化——作为一个整体提交,原子性)

注意:如果你想要在SharedPreferences中实时显示,刚通过Editor对象进行的修改,那么你必须调用commit()方法。

返回值

返回一个SharedPreferences.Editor的新实例,允许你修改SharedPreferences对象里的值。

public abstract MapgetAll()

取得preferences里面的所有值

返回值

返回一个map,其中包含一列preferences中的键值对

异常

空指针异常(NullPointerException)

public abstract boolean getBoolean (String key, boolean defValue)

preferences中获取一个boolean类型的值。

参数

key获取的preference的名称

defValue当此preference不存在时返回的默认值

返回值

如果preference存在,则返回preference的值,否则返回defValue。如果使用此名称的preference不是一个boolean类型,则抛出ClassCastException

异常

ClassCastException

public abstract float getFloat (String key, float defValue)

preferences中获取一个float类型的值。

参数

key获取的preference的名称

defValue当此preference不存在时返回的默认值

返回值

如果preference存在,则返回preference的值,否则返回defValue。如果使用此名称的preference不是一个float类型,则抛出ClassCastException

异常

ClassCastException

public abstract intgetInt(String key, int defValue)

preferences中获取一个int类型的值。

参数

key获取的preference的名称

defValue当此preference不存在时返回的默认值

返回值

如果preference存在,则返回preference的值,否则返回defValue。如果使用此名称的preference不是一个int类型,则抛出ClassCastException

异常

ClassCastException

public abstract longgetLong(String key, long defValue)

preferences中获取一个long类型的值。

参数

key获取的preference的名称

defValue当此preference不存在时返回的默认值

返回值

如果preference存在,则返回preference的值,否则返回defValue。如果使用此名称的preference不是一个long类型,则抛出ClassCastException

异常

ClassCastException

public abstract StringgetString(String key, String defValue)

preferences中获取一个String类型的值。

参数

key获取的preference的名称

defValue当此preference不存在时返回的默认值

返回值

如果preference存在,则返回preference的值,否则返回defValue。如果使用此名称的preference不是一个String类型,则抛出ClassCastException

异常

ClassCastException

public abstract voidregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)

注册一个回调函数,当一个preference发生变化时调用。

参数

listener将会被调用的回调函数

参见

unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener)

public abstract voidunregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)

注销一个之前(注册)的回调函数

参数

listener要被注销的回调函数

参见

registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener)

补充

文章精选

SharedPreferences

[Android开发者指南]第十八讲:Android SharedPreferencesFile

SharedPreferences用法

Android程式設計(十五)使用SharedPreferences

示例代码

译注:Shared Preferences保存位置:/data/data/app_name/shared_prefs
publicclassDemoActivityextendsActivity{

publicstaticStringSOCKET_ADDRESS="your.local.socket.address";

// background threads use this Handler to post messages to
// the main application thread
privatefinalHandlerhandler=newHandler();

publicclassNotificationRunnableimplementsRunnable{
privateStringmessage=null;

publicvoidrun(){
if(message!=null&&message.length()>0){
showNotification(message);
}
}


publicvoidsetMessage(Stringmessage){
this.message=message;
}
}

// post this to the Handler when the background thread notifies
privatefinalNotificationRunnablenotificationRunnable=newNotificationRunnable();

publicvoidshowNotification(Stringmessage){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}

classSocketListenerextendsThread{
privateHandlerhandler=null;
privateNotificationRunnablerunnable=null;

publicSocketListener(Handlerhandler,NotificationRunnablerunnable){
this.handler=handler;
this.runnable=runnable;
this.handler.post(this.runnable);
}


privatevoidshowMessage(Stringmessage){
this.runnable.setMessage(message);
this.handler.post(this.runnable);
}

@Override
publicvoidrun(){
//showMessage("DEMO: SocketListener started!");
try{
LocalServerSocketserver=newLocalServerSocket(SOCKET_ADDRESS);
while(true){
LocalSocketreceiver=server.accept();
if(receiver!=null){
InputStreaminput=receiver.getInputStream();

// simply for java.util.ArrayList
intreaded=input.read();
intsize=0;
intcapacity=0;
byte[]bytes=newbyte[capacity];

// reading
while(readed!=-1){
// java.util.ArrayList.Add(E e);
capacity=(capacity*3)/2+1;
//bytes = Arrays.copyOf(bytes, capacity);
byte[]copy=newbyte[capacity];
System.arraycopy(bytes,0,copy,0,bytes.length);
bytes=copy;
bytes[size++]=(byte)readed;

// read next byte
readed=input.read();
}

showMessage(newString(bytes,0,size));
}
}
}catch(IOExceptione){
Log.e(getClass().getName(),e.getMessage());
}
}
}

publicstaticvoidwriteSocket(Stringmessage)throwsIOException{
LocalSocketsender=newLocalSocket();
sender.connect(newLocalSocketAddress(SOCKET_ADDRESS));
sender.getOutputStream().write(message.getBytes());
sender.getOutputStream().close();
}

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

newSocketListener(this.handler,this.notificationRunnable).start();

Buttonsend1=(Button)findViewById(R.id.send_1_button);
send1.setOnClickListener(newOnClickListener(){

@Override
publicvoidonClick(Viewv){
try{
writeSocket("hello");
}catch(IOExceptione){
Log.e(getClass().getName(),e.getMessage());
}
}

});
}
}


前の記事: 次の記事: