Code example for SharedPreferences

Methods: editgetString

0
		return mPrefs.getBoolean(PREF_STARTED, false);
	} 
 
	// Sets whether or not the services has been started in the preferences. 
	private void setStarted(boolean started) {
		mPrefs.edit().putBoolean(PREF_STARTED, started).commit();		
		mStarted = started;
	} 
 
	private synchronized void start() { 
		log("Starting service..."); 
		 
		// Do nothing, if the service is already running. 
		if (mStarted == true) {
			Log.w(TAG, "Attempt to start connection that is already active");
			return; 
		} 
		 
		// Establish an MQTT connection 
		connect(); 
		 
		// Register a connectivity listener 
		registerReceiver(mConnectivityChanged, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));		
	} 
 
	private synchronized void stop() { 
		// Do nothing, if the service is not running. 
		if (mStarted == false) {
			Log.w(TAG, "Attempt to stop connection not active.");
			return; 
		} 
 
		// Save stopped state in the preferences 
		setStarted(false); 
 
		// Remove the connectivity receiver 
		unregisterReceiver(mConnectivityChanged);
		// Any existing reconnect timers should be removed, since we explicitly stopping the service. 
		cancelReconnect(); 
 
		// Destroy the MQTT connection if there is one 
		if (mConnection != null) {
			mConnection.disconnect();
			mConnection = null;
		} 
	} 
	 
	//  
	private synchronized void connect() {		 
		log("Connecting..."); 
		// fetch the device ID from the preferences. 
		String deviceID = mPrefs.getString(PREF_DEVICE_ID, null);
		// Create a new connection only if the device id is not NULL 
		if (deviceID == null) {
			log("Device ID not found."); 
		} else { 
			try { 
				mConnection = new MQTTConnection(MQTT_HOST, deviceID);
			} catch (MqttException e) {
				// Schedule a reconnect, if we failed to connect 
				log("MqttException: " + (e.getMessage() != null ? e.getMessage() : "NULL"));
	        	if (isNetworkAvailable()) { 
	        		scheduleReconnect(mStartTime);
	        	} 
			} 
			setStarted(true); 
		} 
	} 
 
	private synchronized void keepAlive() { 
		try { 
			// Send a keep alive, if there is a connection. 
			if (mStarted == true && mConnection != null) {
				mConnection.sendKeepAlive();
			} 
		} catch (MqttException e) {
			log("MqttException: " + (e.getMessage() != null? e.getMessage(): "NULL"), e);
			 
			mConnection.disconnect();
			mConnection = null;
			cancelReconnect(); 
		} 
	} 
 
	// Schedule application level keep-alives using the AlarmManager 
	private void startKeepAlives() { 
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_KEEPALIVE);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
		  System.currentTimeMillis() + KEEP_ALIVE_INTERVAL,
		  KEEP_ALIVE_INTERVAL, pi);
	} 
 
	// Remove all scheduled keep alives 
	private void stopKeepAlives() { 
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_KEEPALIVE);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmMgr.cancel(pi);
	} 
 
	// We schedule a reconnect based on the starttime of the service 
	public void scheduleReconnect(long startTime) {
		// the last keep-alive interval 
		long interval = mPrefs.getLong(PREF_RETRY, INITIAL_RETRY_INTERVAL);
 
		// Calculate the elapsed time since the start 
		long now = System.currentTimeMillis();
		long elapsed = now - startTime;
 
 
		// Set an appropriate interval based on the elapsed time since start  
		if (elapsed < interval) {
			interval = Math.min(interval * 4, MAXIMUM_RETRY_INTERVAL);
		} else { 
			interval = INITIAL_RETRY_INTERVAL;
		} 
		 
		log("Rescheduling connection in " + interval + "ms.");
 
		// Save the new internval 
		mPrefs.edit().putLong(PREF_RETRY, interval).commit();
 
		// Schedule a reconnect using the alarm manager. 
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_RECONNECT);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmMgr.set(AlarmManager.RTC_WAKEUP, now + interval, pi);
	} 
	 
	// Remove the scheduled reconnect 
	public void cancelReconnect() { 
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_RECONNECT);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmMgr.cancel(pi);
	} 
	 
	private synchronized void reconnectIfNecessary() {		 
		if (mStarted == true && mConnection == null) {
			log("Reconnecting..."); 
			connect(); 
		} 
	} 
 
	// This receiver listeners for network changes and updates the MQTT connection 
	// accordingly 
	private BroadcastReceiver mConnectivityChanged = new BroadcastReceiver() {
		@Override 
		public void onReceive(Context context, Intent intent) { 
			// Get network info 
			NetworkInfo info = (NetworkInfo)intent.getParcelableExtra (ConnectivityManager.EXTRA_NETWORK_INFO); 
			 
			// Is there connectivity? 
			boolean hasConnectivity = (info != null && info.isConnected()) ? true : false; 
 
			log("Connectivity changed: connected=" + hasConnectivity); 
 
			if (hasConnectivity) { 
				reconnectIfNecessary(); 
			} else if (mConnection != null) { 
				// if there no connectivity, make sure MQTT connection is destroyed 
				mConnection.disconnect(); 
				cancelReconnect(); 
				mConnection = null; 
			} 
		} 
	}; 
	 
	// Display the topbar notification 
	private void showNotification(String text) {
		Notification n = new Notification();
				 
		n.flags |= Notification.FLAG_SHOW_LIGHTS;
      	n.flags |= Notification.FLAG_AUTO_CANCEL;
 
        n.defaults = Notification.DEFAULT_ALL;
      	 
		n.icon = com.tokudu.demo.R.drawable.icon;
		n.when = System.currentTimeMillis();
 
		// Simply open the parent activity 
		PendingIntent pi = PendingIntent.getActivity(this, 0,
		  new Intent(this, PushActivity.class), 0);
 
		// Change the name of the notification here 
		n.setLatestEventInfo(this, NOTIF_TITLE, text, pi);
 
		mNotifMan.notify(NOTIF_CONNECTED, n);
	} 
	 
	// Check if we are online 
	private boolean isNetworkAvailable() { 
		NetworkInfo info = mConnMan.getActiveNetworkInfo();
		if (info == null) {
			return false; 
		} 
		return info.isConnected();
	} 
	 
	// This inner class is a wrapper on top of MQTT client. 
	private class MQTTConnection implements MqttSimpleCallback { 
		IMqttClient mqttClient = null;
		 
		// Creates a new connection given the broker address and initial topic 
		public MQTTConnection(String brokerHostName, String initTopic) throws MqttException {
			// Create connection spec 
	    	String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
	        	// Create the client and connect 
	        	mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
	        	String clientID = MQTT_CLIENT_ID + "/" + mPrefs.getString(PREF_DEVICE_ID, "");
	        	mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
 
		        // register this client app has being able to receive messages 
				mqttClient.registerSimpleHandler(this);