目录搜索
androidManifestManifest.permissionManifest.permission_groupandroid.accessibilityserviceAccessibilityServiceandroid.accountsAccountandroid.appNotificationManagerandroid.bluetoothBluetoothAdapterBluetoothClassBluetoothClass.DeviceBluetoothClass.Device.MajorBluetoothClass.ServiceBluetoothDeviceBluetoothServerSocketBluetoothSocketandroid.contentSharedPreferencesandroid.database.sqliteSQLiteCursorDriverSQLiteOpenHelperandroid.graphicsBitmapandroid.locationLocationListenerGeocoderGpsStatusGpsStatus.ListenerGpsStatus.NmeaListenerGpsSatelliteandroid.mediaAudioFormatAsyncPlayerAudioRecordAudioRecord.OnRecordPositionUpdateListenerThumbnailUtilsAudioManagerandroid.netTrafficStatsMailToLocalSocketandroid.osAsyncTaskAsyncTask.StatusCountDownTimerMessageMessageQueueHandlerThreadandroid.textHtmlandroid.utilJsonWriterandroid.viewContextMenuContextMenu.ContextMenuInfoDisplayViewManagerViewViewStubViewTreeObserverViewParentWindowManagerGestureDetectorGravityMenuInflaterScaleGestureDetectorSoundEffectConstantsandroid.view.inputmethodInputConnectionInputMethodInputMethodSessionBaseInputConnectionInputMethodManagerandroid.widgetAbsListViewAbsListView.LayoutParamsAbsListView.OnScrollListenerAbsListView.RecyclerListenerAbsoluteLayoutAbsoluteLayout.LayoutParamsAbsSeekBarAbsSpinnerAdapterViewAdapterView.AdapterContextMenuInfoAdapterView.OnItemLongClickListenerAdapterView.OnItemSelectedListenerAdapterView.OnItemClickListenerAnalogClockBaseAdapterBaseExpandableListAdapterButtonCheckBoxCheckedTextViewCheckableChronometerChronometer.OnChronometerTickListenerCompoundButtonCompoundButton.OnCheckedChangeListenerCursorAdapterCursorTreeAdapterDatePickerDatePicker.OnDateChangedListenerDialerFilterDigitalClockEditTextFilterFilter.FilterListenerFilter.FilterResultsExpandableListAdapterExpandableListView.OnChildClickListenerExpandableListView.OnGroupClickListenerExpandableListView.OnGroupCollapseListenerExpandableListView.OnGroupExpandListenerFilterableGalleryGallery.LayoutParamsGridViewGridLayoutGridLayout.AlignmentRadioGroupImageViewImageView.ScaleTypeHorizontalScrollViewImageButtonImageSwitcherFilterQueryProviderListAdapterListViewMediaControllerMultiAutoCompleteTextViewMultiAutoCompleteTextView.CommaTokenizerMultiAutoCompleteTextView.TokenizerQuickContactBadgeRadioButtonRatingBarRatingBar.OnRatingBarChangeListenerRelativeLayoutRemoteViewsResourceCursorAdapterResourceCursorTreeAdapterScrollerScrollViewSearchViewSearchView.OnCloseListenerSearchView.OnQueryTextListenerSearchView.OnSuggestionListenerSeekBarSeekBar.OnSeekBarChangeListenerSimpleAdapterSimpleAdapter.ViewBinderSimpleCursorAdapterSimpleCursorAdapter.CursorToStringConverterSimpleCursorAdapter.ViewBinderSimpleCursorTreeAdapterSimpleCursorTreeAdapter.ViewBinderSimpleExpandableListAdapterSlidingDrawerSlidingDrawer.OnDrawerCloseListenerSlidingDrawer.OnDrawerOpenListenerSlidingDrawer.OnDrawerScrollListenerSpinnerSpinnerAdapterWrapperListAdapterTabHostTabHost.TabSpecTextViewTimePickerTimePicker.OnTimeChangedListenerToastTableLayoutTableLayout.LayoutParamsTableRowTableRow.LayoutParamsTabWidgetTextSwitcherToggleButtonTwoLineListItemVideoViewViewAnimatorViewFlipperViewSwitcherViewSwitcher.ViewFactoryZoomButtonsControllerZoomButtonsController.OnZoomListenerZoomButtonZoomControlsdalvik.systemDexFile
文字


SharedPreferences

翻译版本:2010-11-1

结构

继承关系

public interface SharedPreferences

        

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 boolean contains (String key)

判断preferences是否包含一个preference

参数

key 想要判断的preference的名称

返回值

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

 

public abstract SharedPreferences.Editor edit ()

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

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

返回值

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

 

public abstract Map<String, ?> getAll ()

取得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 int getInt (String key, int defValue)

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

    参数

key            获取的preference的名称

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

返回值

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

异常

ClassCastException   

 

public abstract long getLong (String key, long defValue)

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

    参数

key            获取的preference的名称

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

返回值

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

异常

ClassCastException   

 

public abstract String getString (String key, String defValue)

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

    参数

key            获取的preference的名称

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

返回值

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

异常

ClassCastException   

 

public abstract void registerOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)

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

参数

listener    将会被调用的回调函数

        参见

    unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener)

 

public abstract void unregisterOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)

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

参数

listener    要被注销的回调函数

参见

    registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener)

 

补充

    文章精选

        SharedPreferences

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

                   SharedPreferences用法

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

                  

    示例代码

        译注:Shared Preferences保存位置:/data/data/app_name/shared_prefs
public class DemoActivity extends Activity {
   
    public static String SOCKET_ADDRESS = "your.local.socket.address";
   
    // background threads use this Handler to post messages to
    // the main application thread
    private final Handler handler = new Handler();
   
    public class NotificationRunnable implements Runnable {
        private String message = null;
       
        public void run() {
            if (message != null && message.length() > 0) {
                showNotification(message);
            }
        }
       
       
        public void setMessage(String message) {
            this.message = message;
        }
    }
   
    // post this to the Handler when the background thread notifies
    private final NotificationRunnable notificationRunnable = new NotificationRunnable();
   
    public void showNotification(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
   
    class SocketListener extends Thread {
        private Handler handler = null;
        private NotificationRunnable runnable = null;
       
        public SocketListener(Handler handler, NotificationRunnable runnable) {
            this.handler = handler;
            this.runnable = runnable;
            this.handler.post(this.runnable);
        }
       
       
        private void showMessage(String message) {
            this.runnable.setMessage(message);
            this.handler.post(this.runnable);
        }
       
        @Override
        public void run() {
            //showMessage("DEMO: SocketListener started!");
            try {
                LocalServerSocket server = new LocalServerSocket(SOCKET_ADDRESS);
                while (true) {
                    LocalSocket receiver = server.accept();
                    if (receiver != null) {
                        InputStream input = receiver.getInputStream();
                       
                        // simply for java.util.ArrayList
                        int readed = input.read();
                        int size = 0;
                        int capacity = 0;
                        byte[] bytes = new byte[capacity];
                       
                        // reading
                        while (readed != -1) {
                            // java.util.ArrayList.Add(E e);
                            capacity = (capacity * 3)/2 + 1;
                            //bytes = Arrays.copyOf(bytes, capacity);
                            byte[] copy = new byte[capacity];
                            System.arraycopy(bytes, 0, copy, 0, bytes.length);
                            bytes = copy;
                            bytes[size++] = (byte)readed;
                           
                            // read next byte
                            readed = input.read();
                        }
                       
                        showMessage(new String(bytes, 0, size));
                    }
                }
            } catch (IOException e) {
                Log.e(getClass().getName(), e.getMessage());
            }
        }
    }
   
    public static void writeSocket(String message) throws IOException {
        LocalSocket sender = new LocalSocket();
        sender.connect(new LocalSocketAddress(SOCKET_ADDRESS));
        sender.getOutputStream().write(message.getBytes());
        sender.getOutputStream().close();
    }
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        new SocketListener(this.handler, this.notificationRunnable).start();
       
        Button send1 = (Button)findViewById(R.id.send_1_button);
        send1.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                try {
                    writeSocket("hello");
                } catch (IOException e) {
                    Log.e(getClass().getName(), e.getMessage());
                }
            }
           
        });
    }
}

        

 


上一篇:下一篇: