GVKun编程网logo

Mongoose API Reference

13

对于想了解MongooseAPIReference的读者,本文将提供新的信息,并且为您提供关于Adifferenttwistonpre-compilingJSPs--reference、android

对于想了解Mongoose API Reference的读者,本文将提供新的信息,并且为您提供关于A different twist on pre-compiling JSPs--reference、android – PreferenceManager.getDefaultSharedPreferences()vs getPreferences()、android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences、android.preference.Preference.OnPreferenceChangeListener的实例源码的有价值信息。

本文目录一览:

Mongoose API Reference

Mongoose API Reference

Mongoose API Reference

struct mg_server *mg_create_server(void *server_param);

Creates web server instance. Returns opaque instance pointer, or NULL if there is not enough memory.server_param: Could be any pointer, or NULL. This pointer will be passed to the callback functions asstruct mg_connection::server_param field. A common use case is to passthis pointer of the C++ wrapper class asuser_param, to let the callback get the pointer to the C++ object.

Note that this function doesn''t make the server instance to serve. Serving is done bymg_poll_server() function. Mongoose has single-threaded, event-driven, asynchronous, non-blocking core. When server instance is created, it contains an information about the configuration and the state of each connection. Server instance is capable on listening on only one port. After creation,struct mg_server has a list of active connections and configuration parameters.

Side-effect: on UNIX, mg_create_server() ignores SIGPIPE signals. If custom processing is required SIGPIPE, signal handler must be set up after callingmg_create_server().

Important: Mongoose does not installSIGCHLD handler. If CGI is used,SIGCHLD handler must be set up to reap CGI zombie processes.

void mg_destroy_server(struct mg_server **server);

Deallocates web server instance, closes all pending connections, and makes server pointer a NULL pointer.

const char mg_set_option(struct mg_server *server, const char *name,
                         const char *value);

Sets a particular server option. Note that at least one option,listening_port, must be specified. To serve static files,document_root must be specified too. Ifdocument_root option is left unset, Mongoose will not access filesystem at all.mg_set_option() returns NULL if option was set successfully, otherwise it returns human-readable error string. It is allowed to callmg_set_option() by the same thread that doesmg_poll_server() (Mongoose thread) and change server configuration while it is serving, in betweenmg_poll_server() calls.

int mg_poll_server(struct mg_server *server, int milliseconds);

Performs one iteration of IO loop by iterating over all active connections, performingselect() syscall on all sockets with a timeout ofmilliseconds. When select() returns, Mongoose does an IO for each socket that has data to be sent or received. Application code must callmg_poll_server() in a loop. It is an error to have more then one thread callingmg_poll_server(), mg_set_option() or any other function that take struct mg_server * parameter. Mongoose does not mutex-protect struct mg_server *, therefore only single thread (Mongoose thread) should make Mongoose calls.

mg_poll_server() calls user-specified event handler when certain events occur. Sequence of events for the accepted connection is this:

  • MG_AUTH - Mongoose asks whether this connection is authorized. If event handler returnsMG_FALSE, then Mongoose does not serve the request but sends authorization request to the client. IfMG_TRUE is returned, then Mongoose continues on with the request.
  • MG_REQUEST - Mongoose asks event handler to serve the request. If event handler serves the request by sending a reply, it should returnMG_TRUE. Otherwise, it should returnMG_FALSE which tells Mongoose that request is not served and Mongoose should serve it. For example, event handler might choose to serve only RESTful API requests with URIs that start with certain prefix, and let Mongoose serve all static files. If event handler decides to serve the request, but doesn''t have all the data at the moment, it should returnMG_MORE. That tells Mongoose to keep the connection open after callback returns.

mg_connection::connection_param pointer is a placeholder to keep user-specific data. For example, handler could decide to open a DB connection and store DB connection handle in connection_param. *MG_POLL is sent to every connection on every iteration ofmg_poll_server(). Event handler should returnMG_FALSE to ignore this event. If event handler returnsMG_TRUE, then Mongoose assumes that event handler has finished sending data, and Mongoose will close the connection. *MG_HTTP_ERROR sent when Mongoose is about to send HTTP error back to the client. Event handler can choose to send a reply itself, in which case event handler must returnMG_TRUE. Otherwise, event handler must returnMG_FALSE. * MG_CLOSE is sent when the connection is closed. This event is used to cleanup per-connection state stored inconnection_param if it was allocated. Event handler return value is ignored.

Sequence of events for the client connection is this:

  • MG_CONNECT sent when Mongoose has connected to the remote host. This event is sent to the connection initiated bymg_connect() call. Connection status is held inmg_connection::status_code: if zero, then connection was successful, otherwise connection was not established. User should send a request upon successful connection. Event handler should returnMG_TRUE if connection was successful and HTTP request has been sent. Otherwise, it should sendMG_FALSE.
  • MG_REPLY is sent when response has been received from the remote host. If event handler sends another request, then it should returnMG_TRUE. Otherwise it should returnMG_FALSE and Mongoose will close the connection.
  • MG_CLOSE same as for the accepted connection.

When mongoose buffers in HTTP request and successfully parses it, it sendsMG_REQUEST event for GET requests immediately. For POST requests, Mongoose delays the call until the whole POST request is buffered in memory. POST data is available to the callback asstruct mg_connection::content, and POST data length is instruct mg_connection::content_len.

Note that websocket connections are treated the same way. Mongoose buffers websocket frame in memory, and calls event handler when frame is fully buffered. Frame data is availablestruct mg_connection::content, and data length is instruct mg_connection::content_len, i.e. very similar to the POST request.struct mg_connection::is_websocket flag indicates whether the request is websocket or not. Also, for websocket requests, there isstruct mg_connection::wsbits field which contains first byte of the websocket frame which URI handler can examine. Note that to reply to the websocket client,mg_websocket_write() should be used. To reply to the plain HTTP client,mg_write_data() should be used.

Return value: number of active connections.

const char **mg_get_valid_option_names(void);

Returns a NULL-terminated array of option names and their default values. There are two entries per option in an array: an option name followed by a default value. A default value could be NULL. A NULL name indicates an end of the array.

const char *mg_get_option(const struct mg_server *server, const char *name);

Returns the value of particular configuration parameter. If given parameter name is not valid, NULL is returned. For valid names, return value is guaranteed to be non-NULL. If parameter is not set, zero-length string is returned.

void mg_wakeup_server_ex(struct mg_server *, mg_handler_t func,
                         const char *fmt, ...);

Sends string message to a server. Functionfunc is called for every active connection. String message is passed instruct mg_connection::callback_param. This function is designed to push data to the connected clients, and can be called from any thread. There is a limitation on the length of the message, currently at 8 kilobytes.

void mg_send_status(struct mg_connection *, int status_code);
void mg_send_header(struct mg_connection *, const char *name,
                    const char *value);
void mg_send_data(struct mg_connection *, const void *data, int data_len);
void mg_printf_data(struct mg_connection *, const char *format, ...);

These functions are used to construct a response to the client. HTTP response consists of three parts: a status line, zero or more HTTP headers, a response body. Mongoose provides functions for all three parts: * mg_send_status() is used to create status line. This function can be called zero or once. Ifmg_send_status() is not called, then Mongoose will send status 200 (success) implicitly. *mg_send_header() adds HTTP header to the response. This function could be called zero or more times. *mg_send_data() and mg_printf_data() are used to send data to the client. Note that Mongoose addsTransfer-Encoding: chunked header implicitly, and sends data in chunks. Therefore, it is not necessary to setContent-Length header. Note thatmg_send_data() and mg_printf_data() do not send data immediately. Instead, they spool data in memory, and Mongoose sends that data later after URI handler returns. If data to be sent is huge, an URI handler might send data in pieces by saving state instruct mg_connection::connection_param variable and returning0. Then Mongoose will call a handler repeatedly after each socket write.

 void mg_send_file(struct mg_connection *, const char *path);

Tells Mongoose to serve given file. Mongoose handles file according to it''s extensions, i.e. Mongoose will invoke CGI script ifpath has CGI extension, it''ll render SSI file ifpath has SSI extension, etc. Ifpath points to a directory, Mongoose will show directory listing. If this function is used, no calls tomg_send* or mg_printf* functions must be made, and event handler must return MG_MORE.

int mg_websocket_write(struct mg_connection* conn, int opcode,
                       const char *data, size_t data_len);

Similar to mg_write(), but wraps the data into a websocket frame with a given websocketopcode.

const char *mg_get_header(const struct mg_connection *, const char *name);

Get the value of particular HTTP header. This is a helper function. It traverses http_headers array, and if the header is present in the array, returns its value. If it is not present, NULL is returned.

int mg_get_var(const struct mg_connection *conn, const char *var_name,
               char *buf, size_t buf_len);

Gets HTTP form variable. Both POST buffer and query string are inspected. Form variable is url-decoded and written to the buffer. On success, this function returns the length of decoded variable. On error, -1 is returned if variable not found, and -2 is returned if destination buffer is too small to hold the variable. Destination buffer is guaranteed to be ''\0'' - terminated if it is not NULL or zero length.

int mg_parse_header(const char *hdr, const char *var_name, char *buf,
                    size_t buf_size);

This function parses HTTP header and fetches given variable''s value in a buffer. A header should be likex=123, y=345, z="other value". This function is designed to parse Cookie headers, Authorization headers, and similar. Returns the length of the fetched value, or 0 if variable not found.

int mg_modify_passwords_file(const char *passwords_file_name,
                             const char *domain,
                             const char *user,
                             const char *password);

Add, edit or delete the entry in the passwords file.This function allows an application to manipulate .htpasswd files on the fly by adding, deleting and changing user records. This is one of the several ways of implementing authentication on the server side.If password is not NULL, entry is added (or modified if already exists). If password is NULL, entry is deleted.Return: 1 on success, 0 on error.

int mg_parse_multipart(const char *buf, int buf_len,
                       char *var_name, int var_name_len,
                       char *file_name, int file_name_len,
                       const char **data, int *data_len);

Parses a buffer that contains multipart form data. Stores chunk name in avar_name buffer. If chunk is an uploaded file, thenfile_name will have a file name.data and data_len will point to the chunk data. Returns number of bytes to skip to the next chunk.

 struct mg_connection *mg_connect(struct mg_server *server,
                                  const char *host, int port, int use_ssl);

Create connection to the remote host. ReturnsNULL on error, non-null if the connection has been scheduled for connection. Upon a connection, Mongoose will sendMG_CONNECT event to the event handler. 

A different twist on pre-compiling JSPs--reference

A different twist on pre-compiling JSPs--reference

I’ve blogged about this topic earlier and expressed my frustrations as to how web containers don’t provide good support for precompiling JSP,with the exception of. As I’ve said before,WebLogic offers by adding a few simple snippets inside the weblogic.xml file.

"1.0" encoding="UTF-8" ?>

stems,Inc.//DTD Web Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd">weblogic-web-appjsp-descriptorjsp-paramparam-namecompileCommandparam-nameparam-valuejavacparam-valuejsp-paramjsp-paramparam-nameprecompileparam-nameparam-valuetrueparam-valuejsp-paramjsp-paramparam-nameworkingDirparam-nameparam-value./precompile/myappparam-valuejsp-paramjsp-paramparam-namekeepgeneratedparam-nameparam-valuetrueparam-valuejsp-paramjsp-descriptorweblogic-web-app

As you can see from the snippet of XML above,all you have to do is pass in a parameter called precompile and set it to true. You can set additional attributes like compiler (jikes or javac),package for generated source code and classes,etc. Check out the  on the additional parameters.

Now Tomcat or Jetty doesn’t support this type of functionality directly. Tomcat has  on how to use Ant and the JavaServer Page compiler,JSPC. The process involves setting up a task in Ant,and then running org.apache.jasper.JspC on the JSP pages to generate all the classes for the JSP pages. Once the JSP’s are compiled,you have to modify the web.xml to include a servlet mapping for each of the compiled servlet. Yuck! I kNow this works,but it’s just so ugly and such a hack. I like the WebLogic’s declarative way of doing this – Just specify a parameter in an XML file and your JSP’s are compiled at deploy time.

I didn’t want to use the Ant task to precompile as I thought I was just hacking ant to do what I need to do. And if I am going to just hack it,I’m going to create my own hack.

:)  and it says that any request to a JSP page that has a request parameter with name jsp_precompile is a precompilation request. The jsp_precompile parameter may have no value,or may have values true or false. In all cases,the request should not be delivered to the JSP page. Instead,the intention of the precompilation request is that of a suggestion to the JSP container to precompile the JSP page into its JSP page implementation class. So requests like http://localhost:8080/myapp/index.jsp?jsp_precompile or http://localhost:8080/myapp/index.jsp?jsp_precompile=true or http://localhost:8080/myapp/index.jsp?jsp_precompile=false or http://localhost:8080/myapp/index.jsp?data=xyz&jsp_precompile=true are all valid requests. Anything other than true,false or nothing passed into jsp_precompile will get you an HTTP 500. This is a great feature and gave me an idea on how to precompile my JSP’s.

Taking advantage of Precompilation Protocol,I wrote a simple Servlet that was loaded at startup via a attribute in the web.xml. Once the web application is deployed,this servlet would connect to each of the JSP. I also decided to stuff in the details my servlet is going to need to precompile the JSP’s. Here’s the web.xml that defines my PreCompile servlet and all the other attributes it needs. Instead of using the web.xml,I Could have use a property file or a -D parameter from the command line but this was just a proof-of-concept and so I used the web.xml.

"1.0" encoding="ISO-8859-1"?>

stems,Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

web-app

servletservlet-namepreCompileservlet-nameservlet-classcom.j2eegeek.servlet.util.PreCompileServletservlet-classinit-paramparam-namejsp.delimiterparam-nameparam-value;param-valueinit-paraminit-paramparam-namejsp.file.listparam-nameparam-valueindex.jsp;login.jsp;mainmenu.jsp;include/stuff.jsp….param-valueinit-paraminit-paramparam-namejsp.server.urlparam-nameparam-valuehttp://localhost:8080/myapp/param-valueinit-paramload-on-startup9load-on-startupservlet

servlet-mappingservlet-namepreCompileservlet-nameurl-pattern/preCompileurl-patternservlet-mapping

web-app

The web.xml is pretty simple and just defines the PreCompile servlet. The PreCompile servlet is a simple servlet that takes advantage of the servlet lifecycle and uses the init() method of the servlet to connect to each JSP individually and precompile them. In addition to the init() method,we are also defining that the servlet be loaded at the web application deploy time. Here’s a little snippet from the servlet that show the precompilation of the JSPs.

/** * Called by the servlet container to indicate to a servlet that * the servlet is being placed into service. * * @param javax.servlet.ServletConfig config * @throws javax.servlet.servletexception servletexception */publicvoidfig) throwsservletexception {

"Starting init() in "tinitParameter(SERVER_PREFIX); String jsp_delim = config.getinitParameter(JSP_DELIMITER); String jsps = config.getinitParameter(JSP_FILE_LIST);

ifnullnewwhileetokens()) { String jsp = st.nextToken(); log.info("Starting precompile for ""Precompiling JSP’s complete"

In digging into the ,I learned that I can also use the sub-element in conjunction with a JSP page. Another interesting approach to solve this pre-compile issue.

Here’s the fully commented servlet ( | ) that does the precompiling. I currently use this as a standalone war that’s deployed after your main application. You can also ‘touch’ the precompile.war file to reload the PreCompile servlet and precompile an application. I whipped this up just to prove a point and don’t really recommend using this in production,even though I am currently doing that. I am going to send feedback to the  and ask them to look into making precompiling a standard and mandatory option that can be described in the web.xml. If you think this is an issue as well,I’d recommend you do the same. Drop me an email or a comment if you think I am on the right track or completely off my rocker.

reference from:http://www.j2eegeek.com/2004/05/03/a-different-twist-on-pre-compiling-jsps/

android – PreferenceManager.getDefaultSharedPreferences()vs getPreferences()

android – PreferenceManager.getDefaultSharedPreferences()vs getPreferences()

PreferenceManager.getDefaultSharedPreferences(context)

getPreferences()

似乎检索不同的首选项.

PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
                        "userWasAskedToEnableGps", false);

对我来说,返回false,

getPreferences(MODE_PRIVATE).getBoolean("userWasAskedToEnableGps", false);

返回true.

Preference是用编辑器编写的

Editor e = getPreferences(MODE_PRIVATE).edit(); 
e.putBoolean (...);
e.commit();

如何在Context中的Activity之外获得相同的Preferences?

解决方法:

从android github repo(1),我们可以看到getPreferences除了使用当前类名调用getSharedPreferences方法之外什么都不做.

public SharedPreferences getPreferences( int mode ) {
    return getSharedPreferences( getLocalClassName(), mode );
}

没有什么限制其他活动/代码使用适当的类名访问共享首选项.更重要的是,我不想使用getPreferences,因为这意味着=>永远不会更改活动名称.如果更改,则使用明确提及的早期类名称(升级前)来处理访问共享首选项.

android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences

android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences

如果我具有Preference-Activity或-Fragment,则可以提供preference.xml文件来构建我的PreferenceScreen,并通过addPreferenceFromresource(R.xml.preference)进行显示.

然后可以通过PreferenceManager.getDefaultSharedPreferences(Context)检索更改的值.

我只是想知道是否可以将片段的默认首选项设置为默认值.

我希望有一个PreferenceFragment能够将其首选项(通过xml提供)存储在可以通过context.getSharedPreferences(“ customPrefName”,Context.MODE_PRIVATE)检索的Preferences中.
但是我在xml中找不到类似的东西

<PreferenceScreen android:prefName="customPrefName">...

解决方法:

如果要具有自定义首选项xml文件,则需要设置首选项名称,然后再将其从PreferenceFragment类的xml添加到屏幕.

public class CustomNamePreferenceFragment extends PreferenceFragment {

    private static final String PREF_FILE_NAME = "custom_name_xml";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PreferenceManager preferenceManager = getPreferenceManager();
        preferenceManager.setSharedPreferencesName(PREF_FILE_NAME);
        addPreferencesFromresource(R.xml.prefs);
        ... //rest of the code
    }
}

注意:您需要在onCreate()的超级调用之后和调用addPreferencesFromresource()方法之前设置共享首选项名称.

android.preference.Preference.OnPreferenceChangeListener的实例源码

android.preference.Preference.OnPreferenceChangeListener的实例源码

项目:Vafrinn    文件:DocumentModePreference.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.document_mode_preferences);
    getActivity().setTitle(R.string.tabs_and_apps_title);

    mDocumentModeManager = DocumentModeManager.getInstance(getActivity());

    mDocumentModeSwitch = (SwitchPreference) findPreference(PREF_DOCUMENT_MODE_SWITCH);

    boolean isdocumentModeEnabled = !mDocumentModeManager.isOptedOutOfDocumentMode();
    mDocumentModeSwitch.setChecked(isdocumentModeEnabled);

    mDocumentModeSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            if ((boolean) newValue == !mDocumentModeManager.isOptedOutOfDocumentMode()) {
                return true;
            }
            createOptOutAlertDialog((boolean) newValue).show();
            return true;
        }
    });
}
项目:lineagex86    文件:SoundSettings.java   
private void initVibrateWhenRinging(PreferenceCategory root) {
    mVibrateWhenRinging = (TwoStatePreference) root.findPreference(KEY_VIBRATE_WHEN_RINGING);
    if (mVibrateWhenRinging == null) {
        Log.i(TAG,"Preference not found: " + KEY_VIBRATE_WHEN_RINGING);
        return;
    }
    if (!mVoiceCapable || !Utils.isUserOwner()) {
        root.removePreference(mVibrateWhenRinging);
        mVibrateWhenRinging = null;
        return;
    }
    mVibrateWhenRinging.setPersistent(false);
    updateVibrateWhenRinging();
    mVibrateWhenRinging.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            final boolean val = (Boolean) newValue;
            return Settings.System.putInt(getContentResolver(),Settings.System.VIBRATE_WHEN_RINGING,val ? 1 : 0);
        }
    });
}
项目:chromium-for-android-56-debug-video    文件:HomepagePreferences.java   
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mHomepageManager = HomepageManager.getInstance(getActivity());
    getActivity().setTitle(R.string.options_homepage_title);
    addPreferencesFromresource(R.xml.homepage_preferences);

    mHomepageSwitch = (ChromeSwitchPreference) findPreference(PREF_HOMEPAGE_SWITCH);
    boolean isHomepageEnabled = mHomepageManager.getPrefHomepageEnabled();
    mHomepageSwitch.setChecked(isHomepageEnabled);
    mHomepageSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            mHomepageManager.setPrefHomepageEnabled((boolean) newValue);
            return true;
        }
    });

    mHomepageEdit = findPreference(PREF_HOMEPAGE_EDIT);
    updateCurrentHomepageUrl();
}
项目:chromium-for-android-56-debug-video    文件:DoNottrackPreference.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.do_not_track_preferences);
    getActivity().setTitle(R.string.do_not_track_title);

    ChromeSwitchPreference doNottrackSwitch =
            (ChromeSwitchPreference) findPreference(PREF_DO_NOT_TRACK_SWITCH);

    boolean isDoNottrackEnabled = PrefServiceBridge.getInstance().isDoNottrackEnabled();
    doNottrackSwitch.setChecked(isDoNottrackEnabled);

    doNottrackSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PrefServiceBridge.getInstance().setDoNottrackEnabled((boolean) newValue);
            return true;
        }
    });
}
项目:chromium-for-android-56-debug-video    文件:PhysicalWebPreferenceFragment.java   
private void initPhysicalWebSwitch() {
    ChromeSwitchPreference physicalWebSwitch =
            (ChromeSwitchPreference) findPreference(PREF_PHYSICAL_WEB_SWITCH);

    physicalWebSwitch.setChecked(
            PrivacyPreferencesManager.getInstance().isPhysicalWebEnabled());

    physicalWebSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            boolean enabled = (boolean) newValue;
            if (enabled) {
                PhysicalWebUma.onPrefsFeatureEnabled(getActivity());
                ensureLocationPermission();
            } else {
                PhysicalWebUma.onPrefsFeaturedisabled(getActivity());
            }
            PrivacyPreferencesManager.getInstance().setPhysicalWebEnabled(enabled);
            return true;
        }
    });
}
项目:chromium-for-android-56-debug-video    文件:AutofillPreferences.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.autofill_preferences);
    getActivity().setTitle(R.string.prefs_autofill);

    ChromeSwitchPreference autofillSwitch =
            (ChromeSwitchPreference) findPreference(PREF_AUTOFILL_SWITCH);
    autofillSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PersonalDataManager.setAutofillEnabled((boolean) newValue);
            return true;
        }
    });

    setPreferenceCategoryIcons();
}
项目:AndroidChromium    文件:HomepagePreferences.java   
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mHomepageManager = HomepageManager.getInstance(getActivity());
    getActivity().setTitle(R.string.options_homepage_title);
    addPreferencesFromresource(R.xml.homepage_preferences);

    mHomepageSwitch = (ChromeSwitchPreference) findPreference(PREF_HOMEPAGE_SWITCH);
    boolean isHomepageEnabled = mHomepageManager.getPrefHomepageEnabled();
    mHomepageSwitch.setChecked(isHomepageEnabled);
    mHomepageSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            mHomepageManager.setPrefHomepageEnabled((boolean) newValue);
            return true;
        }
    });

    mHomepageEdit = findPreference(PREF_HOMEPAGE_EDIT);
    updateCurrentHomepageUrl();
}
项目:AndroidChromium    文件:DoNottrackPreference.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.do_not_track_preferences);
    getActivity().setTitle(R.string.do_not_track_title);

    ChromeSwitchPreference doNottrackSwitch =
            (ChromeSwitchPreference) findPreference(PREF_DO_NOT_TRACK_SWITCH);

    boolean isDoNottrackEnabled = PrefServiceBridge.getInstance().isDoNottrackEnabled();
    doNottrackSwitch.setChecked(isDoNottrackEnabled);

    doNottrackSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PrefServiceBridge.getInstance().setDoNottrackEnabled((boolean) newValue);
            return true;
        }
    });
}
项目:AndroidChromium    文件:PhysicalWebPreferenceFragment.java   
private void initPhysicalWebSwitch() {
    ChromeSwitchPreference physicalWebSwitch =
            (ChromeSwitchPreference) findPreference(PREF_PHYSICAL_WEB_SWITCH);

    physicalWebSwitch.setChecked(
            PrivacyPreferencesManager.getInstance().isPhysicalWebEnabled());

    physicalWebSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            boolean enabled = (boolean) newValue;
            if (enabled) {
                PhysicalWebUma.onPrefsFeatureEnabled(getActivity());
                ensureLocationPermission();
            } else {
                PhysicalWebUma.onPrefsFeaturedisabled(getActivity());
            }
            PrivacyPreferencesManager.getInstance().setPhysicalWebEnabled(enabled);
            return true;
        }
    });
}
项目:AndroidChromium    文件:AutofillPreferences.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.autofill_preferences);
    getActivity().setTitle(R.string.prefs_autofill);

    ChromeSwitchPreference autofillSwitch =
            (ChromeSwitchPreference) findPreference(PREF_AUTOFILL_SWITCH);
    autofillSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PersonalDataManager.setAutofillEnabled((boolean) newValue);
            return true;
        }
    });

    setPreferenceCategoryIcons();
}
项目:foursquared    文件:PreferenceActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    registerReceiver(mLoggedOutReceiver,new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));

    addPreferencesFromresource(R.xml.preferences);
    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    Preference advanceSettingsPreference = getPreferenceScreen().findPreference(
            Preferences.PREFERENCE_ADVANCED_SETTINGS);
    advanceSettingsPreference.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            ((Foursquared) getApplication()).requestUpdateUser();
            return false;
        }
    });
}
项目:atmosphere-ime    文件:AtmosphereIMESettings.java   
private void initPreferences() {
    addPreferencesFromresource(R.xml.prefs);

    hardwareKeyboardNotice = findPreference(getString(R.string.hardware_keyboard_notice_key));
    imeNotSetNotice = findPreference(getString(R.string.ime_not_set_notice_key));
    displayImePreference = (CheckBoxPreference) findPreference(getString(R.string.display_ime_key));
    displayAnimationPreference = (CheckBoxPreference) findPreference(getString(R.string.display_animation_key));

    displayImePreference.setonPreferencechangelistener(new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            Boolean shoulddisplayIme = (Boolean) newValue;

            if (!shoulddisplayIme) {
                displayAnimationPreference.setChecked(false);
            }

            return true;
        }
    });

    refreshPreferences();
}
项目:mytracks    文件:StatsSettingsActivity.java   
/**
 * Configures the preferred units list preference.
 */
private void configUnitsListPreference() {
  @SuppressWarnings("deprecation")
  ListPreference listPreference = (ListPreference) findPreference(
      getString(R.string.stats_units_key));
  OnPreferencechangelistener listener = new OnPreferencechangelistener() {

      @Override
    public boolean onPreferenceChange(Preference pref,Object newValue) {
      boolean metricUnits = PreferencesUtils.STATS_UNITS_DEFAULT.equals((String) newValue);
      configRateListPreference(metricUnits);
      return true;
    }
  };
  String value = PreferencesUtils.getString(
      this,R.string.stats_units_key,PreferencesUtils.STATS_UNITS_DEFAULT);
  String[] values = getResources().getStringArray(R.array.stats_units_values);
  String[] options = getResources().getStringArray(R.array.stats_units_options);
  configureListPreference(listPreference,options,values,value,listener);
}
项目:mytracks    文件:SensorSettingsActivity.java   
@SuppressWarnings("deprecation")
private void configSensorType(boolean hasAntSupport) {
  ListPreference preference = (ListPreference) findPreference(
      getString(R.string.sensor_type_key));
  String value = PreferencesUtils.getString(
      this,R.string.sensor_type_key,PreferencesUtils.SENSOR_TYPE_DEFAULT);
  String[] options = getResources().getStringArray(
      hasAntSupport ? R.array.sensor_type_all_options : R.array.sensor_type_bluetooth_options);
  String[] values = getResources().getStringArray(
      hasAntSupport ? R.array.sensor_type_all_values : R.array.sensor_type_bluetooth_values);

  if (!hasAntSupport && value.equals(R.string.sensor_type_value_ant)) {
    value = PreferencesUtils.SENSOR_TYPE_DEFAULT;
    PreferencesUtils.setString(this,value);
  }

  OnPreferencechangelistener listener = new OnPreferencechangelistener() {
      @Override
    public boolean onPreferenceChange(Preference pref,Object newValue) {
      updateUiBySensorType((String) newValue);
      return true;
    }
  };
  configureListPreference(preference,listener);
}
项目:mytracks    文件:MapSettingsActivity.java   
/**
 * Configures the track color mode preference.
 */
@SuppressWarnings("deprecation")
private void configTrackColorModePerference() {
  ListPreference preference = (ListPreference) findPreference(
      getString(R.string.track_color_mode_key));
  OnPreferencechangelistener listener = new OnPreferencechangelistener() {
      @Override
    public boolean onPreferenceChange(Preference pref,Object newValue) {
      updateUiByTrackColorMode((String) newValue);
      return true;
    }
  };
  String value = PreferencesUtils.getString(
      this,R.string.track_color_mode_key,PreferencesUtils.TRACK_COLOR_MODE_DEFAULT);
  String[] values = getResources().getStringArray(R.array.track_color_mode_values);
  String[] options = getResources().getStringArray(R.array.track_color_mode_options);
  String[] summary = getResources().getStringArray(R.array.track_color_mode_summary);
  configureListPreference(preference,summary,listener);
}
项目:mytracks    文件:AbstractSettingsActivity.java   
/**
 * Configures a list preference.
 * 
 * @param listPreference the list preference
 * @param summary the summary array
 * @param options the options array
 * @param values the values array
 * @param value the value
 * @param listener optional listener
 */
protected void configureListPreference(ListPreference listPreference,final String[] summary,final String[] options,final String[] values,String value,final OnPreferencechangelistener listener) {
  listPreference.setEntryValues(values);
  listPreference.setEntries(options);
  listPreference.setonPreferencechangelistener(new Preference.OnPreferencechangelistener() {
      @Override
    public boolean onPreferenceChange(Preference pref,Object newValue) {
      updatePreferenceSummary(pref,(String) newValue);
      if (listener != null) {
        listener.onPreferenceChange(pref,newValue);
      }
      return true;
    }
  });
  updatePreferenceSummary(listPreference,value);
  if (listener != null) {
    listener.onPreferenceChange(listPreference,value);
  }
}
项目:Vafrinn    文件:HomepagePreferences.java   
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mHomepageManager = HomepageManager.getInstance(getActivity());
    getActivity().setTitle(R.string.options_homepage_title);
    addPreferencesFromresource(R.xml.homepage_preferences);

    mHomepageSwitch = (ChromeSwitchPreference) findPreference(PREF_HOMEPAGE_SWITCH);
    boolean isHomepageEnabled = mHomepageManager.getPrefHomepageEnabled();
    mHomepageSwitch.setChecked(isHomepageEnabled);
    mHomepageSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            mHomepageManager.setPrefHomepageEnabled((boolean) newValue);
            return true;
        }
    });

    mHomepageEdit = findPreference(PREF_HOMEPAGE_EDIT);
    updateCurrentHomepageUrl();
}
项目:Vafrinn    文件:DoNottrackPreference.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.do_not_track_preferences);
    getActivity().setTitle(R.string.do_not_track_title);

    ChromeSwitchPreference doNottrackSwitch =
            (ChromeSwitchPreference) findPreference(PREF_DO_NOT_TRACK_SWITCH);

    boolean isDoNottrackEnabled = PrefServiceBridge.getInstance().isDoNottrackEnabled();
    doNottrackSwitch.setChecked(isDoNottrackEnabled);

    doNottrackSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PrefServiceBridge.getInstance().setDoNottrackEnabled((boolean) newValue);
            return true;
        }
    });
}
项目:openbmap    文件:SettingsActivity.java   
/**
 * Initializes gps logging interval.
 */
private void initGpsLogIntervalControl() {
    // Update GPS logging interval summary to the current value
    final Preference pref = findPreference(org.openbmap.Preferences.KEY_GPS_LOGGING_INTERVAL);
    pref.setSummary(
               PreferenceManager.getDefaultSharedPreferences(this).getString(org.openbmap.Preferences.KEY_GPS_LOGGING_INTERVAL,org.openbmap.Preferences.VAL_GPS_LOGGING_INTERVAL)
                       + " " + getResources().getString(R.string.prefs_gps_logging_interval_seconds)
                       + ". " + getResources().getString(R.string.prefs_gps_logging_interval_summary));
    pref.setonPreferencechangelistener(new OnPreferencechangelistener() {
           @Override
           public boolean onPreferenceChange(final Preference preference,final Object newValue) {
               // Set summary with the interval and "seconds"
               preference.setSummary(newValue
                       + " " + getResources().getString(R.string.prefs_gps_logging_interval_seconds)
                       + ". " + getResources().getString(R.string.prefs_gps_logging_interval_summary));
               return true;
           }
       });
}
项目:meshchat    文件:SettingsActivity.java   
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.preferences);

    sPref = this.getSharedPreferences(Globals.SHARED_PREF,Context.MODE_PRIVATE);

    p = (EditTextPreference) findPreference(Globals.NICKNAME_DATA);
    nicklistener = new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            SharedPreferences.Editor editor = sPref.edit();
            editor.putString(Globals.NICKNAME_DATA,(String) newValue);
            Log.d(Globals.TAG,""+newValue.toString());
            editor.commit();
            return true;
        }
    };
}
项目:AndroidPreferenceActivity    文件:BehaviorPreferenceFragment.java   
/**
 * Creates a listener,which allows to adapt the behavior of the {@link PreferenceActivity} when
 * the value,which determines,whether the action bar's back button should be overwritten,has
 * been changed.
 *
 * @return The listener,which has been created,as an instance of the type {@link
 * OnPreferencechangelistener}
 */
private OnPreferencechangelistener createOverrideBackButtonchangelistener() {
    return new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            if (newValue != null) {
                boolean overrideNavigationIcon = (boolean) newValue;
                ((PreferenceActivity) getActivity()).overrideNavigationIcon(overrideNavigationIcon);
            }

            return true;
        }

    };
}
项目:AndroidPreferenceActivity    文件:BehaviorPreferenceFragment.java   
/**
 * Creates a listener,whether the navigation should be hidden,has been changed.
 *
 * @return The listener,as an instance of the type {@link
 * OnPreferencechangelistener}
 */
private OnPreferencechangelistener createHideNavigationchangelistener() {
    return new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            if (newValue != null) {
                boolean hideNavigation = (boolean) newValue;
                ((PreferenceActivity) getActivity()).hideNavigation(hideNavigation);
            }

            return true;
        }

    };
}
项目:nxt-remote-control    文件:SettingsActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.settings);
    CheckBoxPreference cb_speed = (CheckBoxPreference) findPreference("PREF_REG_SPEED");
    cb_sync = (CheckBoxPreference) findPreference("PREF_REG_SYNC");

    cb_speed.setonPreferencechangelistener(new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            if (!((Boolean) newValue).booleanValue()) {
                cb_sync.setChecked(false);
            }
            return true;
        }
    });
}
项目:accengage-android-sdk-samples    文件:SampleSettings.java   
@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    addPreferencesFromresource(R.xml.samplesettings);
    setTitle("View : CoffeeSettings");
    mInappdisplayLock = (CheckBoxPreference) findPreference("displayLocked");

    mInappdisplayLock.setonPreferencechangelistener(new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            if(newValue.toString().equals("true")) {
                mInappdisplayLock.setChecked(true);
                A4S.get(SampleSettings.this).setInAppdisplayLocked(true);
            }
            else {
                mInappdisplayLock.setChecked(false);
                A4S.get(SampleSettings.this).setInAppdisplayLocked(false);
            }
            return false;
        }
    });
}
项目:AndroidMaterialPreferences    文件:PreferenceFragment.java   
/**
 * Creates and returns a listener,which allows to adapt,whether the preference's values should
 * be shown as summaries,or not,when the corresponding setting has been changed.
 *
 * @return The listener,as an instance of the type {@link
 * OnPreferencechangelistener}
 */
private OnPreferencechangelistener createShowValueAsSummaryListener() {
    return new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            boolean showValueAsSummary = (Boolean) newValue;
            editTextPreference.showValueAsSummary(showValueAsSummary);
            listPreference.showValueAsSummary(showValueAsSummary);
            multiChoiceListPreference.showValueAsSummary(showValueAsSummary);
            seekBarPreference.showValueAsSummary(showValueAsSummary);
            numberPickerPreference.showValueAsSummary(showValueAsSummary);
            digitPickerPreference.showValueAsSummary(showValueAsSummary);
            resolutionPreference.showValueAsSummary(showValueAsSummary);
            colorPalettePreference.showValueAsSummary(showValueAsSummary);
            adaptSwitchPreferenceSummary(showValueAsSummary);
            return true;
        }

    };
}
项目:AndroidMaterialPreferences    文件:PreferenceFragment.java   
/**
 * Creates and returns a listener,whether the headers of the
 * preference's dialogs should be shown,when the corresponding setting has been
 * changed.
 *
 * @return The listener,as an instance of the type {@link
 * OnPreferencechangelistener}
 */
private OnPreferencechangelistener createShowDialogHeaderListener() {
    return new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            boolean showDialogHeader = (Boolean) newValue;
            dialogPreference.showDialogHeader(showDialogHeader);
            editTextPreference.showDialogHeader(showDialogHeader);
            listPreference.showDialogHeader(showDialogHeader);
            multiChoiceListPreference.showDialogHeader(showDialogHeader);
            seekBarPreference.showDialogHeader(showDialogHeader);
            numberPickerPreference.showDialogHeader(showDialogHeader);
            digitPickerPreference.showDialogHeader(showDialogHeader);
            resolutionPreference.showDialogHeader(showDialogHeader);
            colorPalettePreference.showDialogHeader(showDialogHeader);
            return true;
        }

    };
}
项目:AndroidMaterialPreferences    文件:PreferenceFragment.java   
/**
 * Creates and returns a listener,whether the button bar dividers of the
 * preference's dialogs should be shown,as an instance of the type {@link
 * OnPreferencechangelistener}
 */
private OnPreferencechangelistener createShowDialogbuttonbarDividerListener() {
    return new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            boolean showDialogbuttonbarDivider = (Boolean) newValue;
            dialogPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            editTextPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            listPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            multiChoiceListPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            seekBarPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            numberPickerPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            digitPickerPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            resolutionPreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            colorPalettePreference.showDialogbuttonbarDivider(showDialogbuttonbarDivider);
            return true;
        }

    };
}
项目:appcan-plugin-pdfreader-android    文件:PreferencesDecorator.java   
public void decoratebrowserSettings() {
    final boolean isTablet = iuiManager.instance.isTabletUi(parent.getActivity()) && !AndroidVersion.lessthan3x;
    enableSettings(isTablet,SHOW_REMOVABLE_MEDIA.key,SHOW_SCANNING_MEDIA.key);

    addListener(CACHE_LOCATION.key,new OnPreferencechangelistener() {

        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            final CacheLocation newLocation = EnumUtils.getByResValue(CacheLocation.class,LengthUtils.toString(newValue),null);
            if (newLocation != null) {
                CacheManager.moveCacheLocation(preference.getContext(),newLocation);
            }
            return true;
        }
    });
}
项目:appcan-plugin-pdfreader-android    文件:PreferencesDecorator.java   
protected void decorateEditPreference(final EditTextPreference textPrefs) {
    final CharSequence summary = textPrefs.getSummary();
    summaries.put(textPrefs.getKey(),summary);

    final String value = textPrefs.getText();

    setPreferenceSummary(textPrefs,value);

    addListener(textPrefs,final Object newValue) {
            setPreferenceSummary(textPrefs,(String) newValue);
            return true;
        }
    });
}
项目:appcan-plugin-pdfreader-android    文件:PreferencesDecorator.java   
protected void decorateSeekPreference(final SeekBarPreference textPrefs) {
    final CharSequence summary = textPrefs.getSummary();
    summaries.put(textPrefs.getKey(),summary);

    final int value = textPrefs.getValue();

    setPreferenceSummary(textPrefs,"" + value);

    addListener(textPrefs,(String) newValue);
            return true;
        }
    });
}
项目:appcan-plugin-pdfreader-android    文件:PreferencesDecorator.java   
protected void decorateListPreference(final ListPreference listPrefs) {
    final CharSequence summary = listPrefs.getSummary();
    summaries.put(listPrefs.getKey(),summary);

    final String value = listPrefs.getValue();

    setListPreferenceSummary(listPrefs,value);

    addListener(listPrefs,final Object newValue) {
            setListPreferenceSummary(listPrefs,(String) newValue);
            return true;
        }
    });
}
项目:QuickControlPanel    文件:SwipeDetectorPrefsFragment.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.swipe_detector_prefs);

    mDetectorHeightPref = (SliderPreference) findPreference(Keys.Launch.SWIPE_DETECTOR_SIZE_1);
    mDetectorWidthPref = (SliderPreference) findPreference(Keys.Launch.SWIPE_DETECTOR_SIZE_2);

    findPreference("dimens_swipe_detector_align").setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            if("MIDDLE".equals(newValue)) {
                mDetectorWidthPref.setTitle(R.string.swipe_detector_width_pref);
                mDetectorHeightPref.setTitle(R.string.swipe_detector_height_pref);
            } else {
                mDetectorWidthPref.setTitle(R.string.swipe_detector_height_pref);
                mDetectorHeightPref.setTitle(R.string.swipe_detector_width_pref);
            }
            return true;
        }
    });
}
项目:evercam-play-android2    文件:CameraPrefsActivity.java   
private void setUpSleepTime()
{
    final ThemedListPreference sleepListPrefs = (ThemedListPreference)
            getPreferenceManager().findPreference(PrefsManager.KEY_AWAKE_TIME);
    sleepListPrefs.setSummary(getSummary(sleepListPrefs.getEntry() + ""));
    sleepListPrefs.setonPreferencechangelistener(new OnPreferencechangelistener()
    {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue)
        {
            int index = sleepListPrefs.findindexOfValue(newValue.toString());
            String entry = sleepListPrefs.getEntries()[index].toString();
            sleepListPrefs.setSummary(getSummary(entry));
            return true;
        }
    });
}
项目:topodroid    文件:MyEditPreference.java   
private void init()
{
  setonPreferencechangelistener( new OnPreferencechangelistener() {
    @Override
    public boolean onPreferenceChange( Preference p,Object v ) 
    {
      String value = (String)v;
      String new_value = TDSetting.enforcePreferenceBounds( p.getKey(),value );
      // Log.v("distoX",p.getKey() + ": value " + ((String)v) + " -> " + new_value + " text " + getText() );
      // if ( ! new_value.equals( value ) )
      {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString( p.getKey(),new_value );
        editor.commit();
        EditTextPreference ep = (EditTextPreference)p;
        ep.setSummary( new_value );
        ep.setText( new_value );
      }
      return false; // state of preference has already been updated
    }
  } );
}
项目:365browser    文件:HomepagePreferences.java   
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mHomepageManager = HomepageManager.getInstance(getActivity());
    getActivity().setTitle(R.string.options_homepage_title);
    addPreferencesFromresource(R.xml.homepage_preferences);

    mHomepageSwitch = (ChromeSwitchPreference) findPreference(PREF_HOMEPAGE_SWITCH);
    boolean isHomepageEnabled = mHomepageManager.getPrefHomepageEnabled();
    mHomepageSwitch.setChecked(isHomepageEnabled);
    mHomepageSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            mHomepageManager.setPrefHomepageEnabled((boolean) newValue);
            return true;
        }
    });

    mHomepageEdit = findPreference(PREF_HOMEPAGE_EDIT);
    updateCurrentHomepageUrl();
}
项目:365browser    文件:DoNottrackPreference.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromresource(R.xml.do_not_track_preferences);
    getActivity().setTitle(R.string.do_not_track_title);

    ChromeSwitchPreference doNottrackSwitch =
            (ChromeSwitchPreference) findPreference(PREF_DO_NOT_TRACK_SWITCH);

    boolean isDoNottrackEnabled = PrefServiceBridge.getInstance().isDoNottrackEnabled();
    doNottrackSwitch.setChecked(isDoNottrackEnabled);

    doNottrackSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PrefServiceBridge.getInstance().setDoNottrackEnabled((boolean) newValue);
            return true;
        }
    });
}
项目:365browser    文件:PhysicalWebPreferenceFragment.java   
private void initPhysicalWebSwitch() {
    ChromeSwitchPreference physicalWebSwitch =
            (ChromeSwitchPreference) findPreference(PREF_PHYSICAL_WEB_SWITCH);

    physicalWebSwitch.setChecked(
            PrivacyPreferencesManager.getInstance().isPhysicalWebEnabled());

    physicalWebSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            boolean enabled = (boolean) newValue;
            if (enabled) {
                PhysicalWebUma.onPrefsFeatureEnabled();
                ensureLocationPermission();
            } else {
                PhysicalWebUma.onPrefsFeaturedisabled();
            }
            PrivacyPreferencesManager.getInstance().setPhysicalWebEnabled(enabled);
            return true;
        }
    });
}
项目:365browser    文件:AutofillAndPaymentsPreferences.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PreferenceUtils.addPreferencesFromresource(this,R.xml.autofill_and_payments_preferences);
    getActivity().setTitle(R.string.prefs_autofill_and_payments);

    ChromeSwitchPreference autofillSwitch =
            (ChromeSwitchPreference) findPreference(PREF_AUTOFILL_SWITCH);
    autofillSwitch.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            PersonalDataManager.setAutofillEnabled((boolean) newValue);
            return true;
        }
    });

    if (ChromeFeatureList.isEnabled(ChromeFeatureList.ANDROID_PAYMENT_APPS)) {
        Preference pref = new Preference(getActivity());
        pref.setTitle(getActivity().getString(R.string.payment_apps_title));
        pref.setFragment(AndroidPaymentAppsFragment.class.getCanonicalName());
        pref.setShoulddisableView(true);
        pref.setKey(PREF_ANDROID_PAYMENT_APPS);
        getPreferenceScreen().addPreference(pref);
    }
}
项目:PhoneProfilesPlus    文件:EventPreferencesScreen.java   
@Override
public void checkPreferences(PreferenceManager prefMng,Context context)
{
    final Preference eventTypePreference = prefMng.findPreference(PREF_EVENT_SCREEN_EVENT_TYPE);
    final PreferenceManager _prefMng = prefMng;

    if (eventTypePreference != null) {
        eventTypePreference.setonPreferencechangelistener(new OnPreferencechangelistener() {
            @Override
            public boolean onPreferenceChange(Preference preference,Object newValue) {
                String sNewValue = (String) newValue;
                int iNewValue;
                if (sNewValue.isEmpty())
                    iNewValue = 100;
                else
                    iNewValue = Integer.parseInt(sNewValue);

                setWhenUnlockedTitle(_prefMng,iNewValue);

                return true;
            }
        });
    }
}
项目:radiocells-scanner-android    文件:SettingsActivity.java   
/**
 * Initializes gps logging interval.
 */
private void initGpsLogIntervalControl() {
    // Update GPS logging interval summary to the current value
    final Preference pref = findPreference(org.openbmap.Preferences.KEY_GPS_LOGGING_INTERVAL);
    pref.setSummary(
            PreferenceManager.getDefaultSharedPreferences(this).getString(org.openbmap.Preferences.KEY_GPS_LOGGING_INTERVAL,org.openbmap.Preferences.VAL_GPS_LOGGING_INTERVAL)
                    + " " + getResources().getString(R.string.prefs_gps_logging_interval_seconds)
                    + ". " + getResources().getString(R.string.prefs_gps_logging_interval_summary));
    pref.setonPreferencechangelistener(new OnPreferencechangelistener() {
        @Override
        public boolean onPreferenceChange(final Preference preference,final Object newValue) {
            // Set summary with the interval and "seconds"
            preference.setSummary(newValue
                    + " " + getResources().getString(R.string.prefs_gps_logging_interval_seconds)
                    + ". " + getResources().getString(R.string.prefs_gps_logging_interval_summary));
            return true;
        }
    });
}

我们今天的关于Mongoose API Reference的分享已经告一段落,感谢您的关注,如果您想了解更多关于A different twist on pre-compiling JSPs--reference、android – PreferenceManager.getDefaultSharedPreferences()vs getPreferences()、android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences、android.preference.Preference.OnPreferenceChangeListener的实例源码的相关信息,请在本站查询。

本文标签:

上一篇在 Mac 上通过 Docker 部署 Oracle Database 11.2.0 版本(mac docker安装部署)

下一篇Reverse Linked List II