Search in sources :

Example 1 with Connection

use of org.openhab.habdroid.core.connection.Connection in project openhab-android by openhab.

the class OpenHABMainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate()");
    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    // Set the theme to one from preferences
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    // Disable screen timeout if set in preferences
    if (mSettings.getBoolean(Constants.PREFERENCE_SCREENTIMEROFF, false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    Util.setActivityTheme(this);
    super.onCreate(savedInstanceState);
    String controllerClassName = getResources().getString(R.string.controller_class);
    try {
        Class<?> controllerClass = Class.forName(controllerClassName);
        Constructor<?> constructor = controllerClass.getConstructor(OpenHABMainActivity.class);
        mController = (ContentController) constructor.newInstance(this);
    } catch (Exception e) {
        Log.wtf(TAG, "Could not instantiate activity controller class '" + controllerClassName + "'");
        throw new RuntimeException(e);
    }
    setContentView(R.layout.activity_main);
    // inflate the controller dependent content view
    ViewStub contentStub = findViewById(R.id.content_stub);
    mController.inflateViews(contentStub);
    setupToolbar();
    setupDrawer();
    gcmRegisterBackground();
    mViewPool = new RecyclerView.RecycledViewPool();
    MemorizingTrustManager.setResponder(this);
    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        mOpenHABVersion = savedInstanceState.getInt("openHABVersion");
        mSitemapList = savedInstanceState.getParcelableArrayList("sitemapList");
        mSelectedSitemap = savedInstanceState.getParcelable("sitemap");
        mInitState = InitState.values()[savedInstanceState.getInt("initState")];
        int lastConnectionHash = savedInstanceState.getInt("connectionHash");
        if (lastConnectionHash != -1) {
            try {
                Connection c = ConnectionFactory.getUsableConnection();
                if (c != null && c.hashCode() == lastConnectionHash) {
                    mConnection = c;
                }
            } catch (ConnectionException e) {
            // ignored
            }
        }
        mController.onRestoreInstanceState(savedInstanceState);
        String lastControllerClass = savedInstanceState.getString("controller");
        if (mSelectedSitemap != null && !mController.getClass().getCanonicalName().equals(lastControllerClass)) {
            // Our controller type changed, so we need to make the new controller aware of the
            // page hierarchy. If the controller didn't change, the hierarchy will be restored
            // via the fragment state restoration.
            mController.recreateFragmentState();
        }
        updateSitemapDrawerItems();
    } else {
        mSitemapList = new ArrayList<>();
    }
    if (getIntent() != null) {
        processIntent(getIntent());
    }
    if (isFullscreenEnabled()) {
        registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STARTED"));
        registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STOPPED"));
        checkFullscreen();
    }
    // Create a new boolean and preference and set it to true
    boolean isFirstStart = mSettings.getBoolean("firstStart", true);
    SharedPreferences.Editor prefsEdit = sharedPrefs.edit();
    // If the activity has never started before...
    if (isFirstStart) {
        // Launch app intro
        final Intent i = new Intent(OpenHABMainActivity.this, IntroActivity.class);
        startActivityForResult(i, INTRO_REQUEST_CODE);
        prefsEdit.putBoolean("firstStart", false).apply();
    }
    OnUpdateBroadcastReceiver.updateComparableVersion(prefsEdit);
    prefsEdit.apply();
}
Also used : IntentFilter(android.content.IntentFilter) SharedPreferences(android.content.SharedPreferences) Connection(org.openhab.habdroid.core.connection.Connection) DemoConnection(org.openhab.habdroid.core.connection.DemoConnection) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) RecognizerIntent(android.speech.RecognizerIntent) CertificateExpiredException(java.security.cert.CertificateExpiredException) JSONException(org.json.JSONException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) CertificateRevokedException(java.security.cert.CertificateRevokedException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ConnectionException(org.openhab.habdroid.core.connection.exception.ConnectionException) CertPathValidatorException(java.security.cert.CertPathValidatorException) NoUrlInformationException(org.openhab.habdroid.core.connection.exception.NoUrlInformationException) ActivityNotFoundException(android.content.ActivityNotFoundException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) MalformedURLException(java.net.MalformedURLException) NetworkNotSupportedException(org.openhab.habdroid.core.connection.exception.NetworkNotSupportedException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ViewStub(android.view.ViewStub) RecyclerView(android.support.v7.widget.RecyclerView) ConnectionException(org.openhab.habdroid.core.connection.exception.ConnectionException)

Example 2 with Connection

use of org.openhab.habdroid.core.connection.Connection in project openhab-android by openhab.

the class OpenHABMainActivity method getNotificationSettings.

/**
 * Returns the notification settings object
 * @return Returns the NotificationSettings or null, if openHAB-cloud isn't used
 */
public NotificationSettings getNotificationSettings() {
    if (mNotifySettings != null) {
        return mNotifySettings;
    }
    Connection cloudConnection = ConnectionFactory.getConnection(TYPE_CLOUD);
    if (cloudConnection == null) {
        return null;
    }
    // check whether URL is valid
    try {
        new URL(cloudConnection.getOpenHABUrl());
        mNotifySettings = new NotificationSettings(cloudConnection);
        return mNotifySettings;
    } catch (MalformedURLException e) {
        return null;
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Connection(org.openhab.habdroid.core.connection.Connection) DemoConnection(org.openhab.habdroid.core.connection.DemoConnection) NotificationSettings(org.openhab.habdroid.core.notifications.NotificationSettings) URL(java.net.URL)

Example 3 with Connection

use of org.openhab.habdroid.core.connection.Connection in project openhab-android by openhab.

the class OpenHABNotificationAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(NotificationViewHolder holder, int position) {
    OpenHABNotification notification = mItems.get(position);
    holder.mCreatedView.setText(DateUtils.getRelativeDateTimeString(mContext, notification.createdTimestamp(), DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0));
    holder.mMessageView.setText(notification.message());
    if (notification.icon() != null) {
        Connection conn = ConnectionFactory.getConnection(Connection.TYPE_CLOUD);
        String iconUrl = String.format(Locale.US, "%simages/%s.png", conn.getOpenHABUrl(), Uri.encode(notification.icon()));
        holder.mIconView.setImageUrl(iconUrl, conn.getUsername(), conn.getPassword(), R.drawable.ic_openhab_appicon_24dp);
    } else {
        holder.mIconView.setImageResource(R.drawable.ic_openhab_appicon_24dp);
    }
}
Also used : OpenHABNotification(org.openhab.habdroid.model.OpenHABNotification) Connection(org.openhab.habdroid.core.connection.Connection)

Example 4 with Connection

use of org.openhab.habdroid.core.connection.Connection in project openhab-android by openhab.

the class OpenHABNotificationFragment method loadNotifications.

private void loadNotifications() {
    Connection conn = ConnectionFactory.getConnection(Connection.TYPE_CLOUD);
    if (conn == null) {
        return;
    }
    startProgressIndicator();
    mRequestHandle = conn.getAsyncHttpClient().get("/api/v1/notifications?limit=20", new MyHttpClient.ResponseHandler() {

        @Override
        public void onSuccess(Call call, int statusCode, Headers headers, byte[] responseBody) {
            stopProgressIndicator();
            Log.d(TAG, "Notifications request success");
            try {
                String jsonString = new String(responseBody, "UTF-8");
                JSONArray jsonArray = new JSONArray(jsonString);
                Log.d(TAG, jsonArray.toString());
                mNotifications.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        JSONObject sitemapJson = jsonArray.getJSONObject(i);
                        mNotifications.add(OpenHABNotification.fromJson(sitemapJson));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                mNotificationAdapter.notifyDataSetChanged();
            } catch (UnsupportedEncodingException | JSONException e) {
                Log.d(TAG, e.getMessage(), e);
            }
        }

        @Override
        public void onFailure(Call call, int statusCode, Headers headers, byte[] responseBody, Throwable error) {
            stopProgressIndicator();
            Log.e(TAG, "Notifications request failure");
        }
    });
}
Also used : Call(okhttp3.Call) JSONObject(org.json.JSONObject) Headers(okhttp3.Headers) Connection(org.openhab.habdroid.core.connection.Connection) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with Connection

use of org.openhab.habdroid.core.connection.Connection in project openhab-android by openhab.

the class OpenHABVoiceService method onConnectionChanged.

@Override
public void onConnectionChanged() {
    try {
        Connection conn = ConnectionFactory.getUsableConnection();
        for (Pair<String, Integer> entry : mPendingCommands) {
            sendItemCommand("VoiceCommand", entry.first, conn, entry.second);
        }
    } catch (ConnectionException e) {
        Log.w(TAG, "Couldn't determine OpenHAB URL", e);
        Toast.makeText(OpenHABVoiceService.this, R.string.error_couldnt_determine_openhab_url, Toast.LENGTH_SHORT).show();
    } finally {
        ConnectionFactory.removeListener(this);
        mPendingCommands.clear();
    }
}
Also used : Connection(org.openhab.habdroid.core.connection.Connection) ConnectionException(org.openhab.habdroid.core.connection.exception.ConnectionException)

Aggregations

Connection (org.openhab.habdroid.core.connection.Connection)7 ConnectionException (org.openhab.habdroid.core.connection.exception.ConnectionException)4 DemoConnection (org.openhab.habdroid.core.connection.DemoConnection)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 JSONException (org.json.JSONException)2 NetworkNotSupportedException (org.openhab.habdroid.core.connection.exception.NetworkNotSupportedException)2 NoUrlInformationException (org.openhab.habdroid.core.connection.exception.NoUrlInformationException)2 PendingIntent (android.app.PendingIntent)1 ActivityNotFoundException (android.content.ActivityNotFoundException)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 SharedPreferences (android.content.SharedPreferences)1 NetworkInfo (android.net.NetworkInfo)1 RecognizerIntent (android.speech.RecognizerIntent)1 RecyclerView (android.support.v7.widget.RecyclerView)1 ViewStub (android.view.ViewStub)1 IOException (java.io.IOException)1 ConnectException (java.net.ConnectException)1 SocketTimeoutException (java.net.SocketTimeoutException)1