Search in sources :

Example 1 with PutDataMapRequest

use of com.google.android.gms.wearable.PutDataMapRequest in project muzei by romannurik.

the class WearableController method updateArtwork.

public static synchronized void updateArtwork(Context context) {
    if (ConnectionResult.SUCCESS != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)) {
        return;
    }
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
    ConnectionResult connectionResult = googleApiClient.blockingConnect(5, TimeUnit.SECONDS);
    if (!connectionResult.isSuccess()) {
        if (connectionResult.getErrorCode() != ConnectionResult.API_UNAVAILABLE) {
            Log.w(TAG, "onConnectionFailed: " + connectionResult);
        }
        return;
    }
    ContentResolver contentResolver = context.getContentResolver();
    Bitmap image = null;
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI), null, options);
        options.inJustDecodeBounds = false;
        if (options.outWidth > options.outHeight) {
            options.inSampleSize = ImageUtil.calculateSampleSize(options.outHeight, 320);
        } else {
            options.inSampleSize = ImageUtil.calculateSampleSize(options.outWidth, 320);
        }
        image = BitmapFactory.decodeStream(contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI), null, options);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Unable to read artwork to update Android Wear", e);
    }
    if (image != null) {
        int rotation = getRotation(context);
        if (rotation != 0) {
            // Rotate the image so that Wear always gets a right side up image
            Matrix matrix = new Matrix();
            matrix.postRotate(rotation);
            image = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, true);
        }
        final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
        Asset asset = Asset.createFromBytes(byteStream.toByteArray());
        PutDataMapRequest dataMapRequest = PutDataMapRequest.create("/artwork");
        Artwork artwork = MuzeiContract.Artwork.getCurrentArtwork(context);
        dataMapRequest.getDataMap().putDataMap("artwork", DataMap.fromBundle(artwork.toBundle()));
        dataMapRequest.getDataMap().putAsset("image", asset);
        Wearable.DataApi.putDataItem(googleApiClient, dataMapRequest.asPutDataRequest().setUrgent()).await();
    }
    googleApiClient.disconnect();
}
Also used : GoogleApiClient(com.google.android.gms.common.api.GoogleApiClient) Artwork(com.google.android.apps.muzei.api.Artwork) FileNotFoundException(java.io.FileNotFoundException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ContentResolver(android.content.ContentResolver) Bitmap(android.graphics.Bitmap) Matrix(android.graphics.Matrix) ConnectionResult(com.google.android.gms.common.ConnectionResult) Asset(com.google.android.gms.wearable.Asset) BitmapFactory(android.graphics.BitmapFactory) PutDataMapRequest(com.google.android.gms.wearable.PutDataMapRequest)

Example 2 with PutDataMapRequest

use of com.google.android.gms.wearable.PutDataMapRequest in project Talon-for-Twitter by klinker24.

the class TweetWearableService method sendImage.

public void sendImage(Bitmap image, String url, WearableUtils wearableUtils, GoogleApiClient googleApiClient) {
    PutDataMapRequest dataMap = PutDataMapRequest.create(KeyProperties.PATH);
    byte[] bytes = new IOUtils().convertToByteArray(image);
    dataMap.getDataMap().putByteArray(KeyProperties.KEY_IMAGE_DATA, bytes);
    dataMap.getDataMap().putString(KeyProperties.KEY_IMAGE_NAME, url);
    for (String node : wearableUtils.getNodes(googleApiClient)) {
        Wearable.MessageApi.sendMessage(googleApiClient, node, KeyProperties.PATH, dataMap.asPutDataRequest().getData());
        Log.v(TAG, "sent " + bytes.length + " bytes of data to node " + node);
    }
}
Also used : IOUtils(com.klinker.android.twitter.utils.IOUtils) PutDataMapRequest(com.google.android.gms.wearable.PutDataMapRequest)

Example 3 with PutDataMapRequest

use of com.google.android.gms.wearable.PutDataMapRequest in project Talon-for-Twitter by klinker24.

the class TweetWearableService method onMessageReceived.

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    final WearableUtils wearableUtils = new WearableUtils();
    final BitmapLruCache cache = App.getInstance(this).getBitmapCache();
    if (markReadHandler == null) {
        markReadHandler = new Handler();
    }
    final String message = new String(messageEvent.getData());
    Log.d(TAG, "got message: " + message);
    final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
    ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
    if (!connectionResult.isSuccess()) {
        Log.e(TAG, "Failed to connect to GoogleApiClient.");
        return;
    }
    if (message.equals(KeyProperties.GET_DATA_MESSAGE)) {
        AppSettings settings = AppSettings.getInstance(this);
        Cursor tweets = HomeDataSource.getInstance(this).getWearCursor(settings.currentAccount);
        PutDataMapRequest dataMap = PutDataMapRequest.create(KeyProperties.PATH);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> screennames = new ArrayList<String>();
        ArrayList<String> bodies = new ArrayList<String>();
        ArrayList<String> ids = new ArrayList<String>();
        if (tweets != null && tweets.moveToLast()) {
            do {
                String name = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_NAME));
                String screenname = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_SCREEN_NAME));
                String pic = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_PRO_PIC));
                String body = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_TEXT));
                long id = tweets.getLong(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_TWEET_ID));
                String retweeter;
                try {
                    retweeter = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_RETWEETER));
                } catch (Exception e) {
                    retweeter = "";
                }
                screennames.add(screenname);
                names.add(name);
                if (TextUtils.isEmpty(retweeter)) {
                    body = pic + KeyProperties.DIVIDER + body + KeyProperties.DIVIDER;
                } else {
                    body = pic + KeyProperties.DIVIDER + body + "<br><br>" + getString(R.string.retweeter) + retweeter + KeyProperties.DIVIDER;
                }
                bodies.add(Html.fromHtml(body.replace("<p>", KeyProperties.LINE_BREAK)).toString());
                ids.add(id + "");
            } while (tweets.moveToPrevious() && tweets.getCount() - tweets.getPosition() < MAX_ARTICLES_TO_SYNC);
            tweets.close();
        }
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_USER_NAME, names);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_USER_SCREENNAME, screennames);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_TWEET, bodies);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_ID, ids);
        // light background with orange accent or theme color accent
        dataMap.getDataMap().putInt(KeyProperties.KEY_PRIMARY_COLOR, Color.parseColor("#dddddd"));
        if (settings.addonTheme) {
            dataMap.getDataMap().putInt(KeyProperties.KEY_ACCENT_COLOR, settings.accentInt);
        } else {
            dataMap.getDataMap().putInt(KeyProperties.KEY_ACCENT_COLOR, getResources().getColor(R.color.orange_primary_color));
        }
        dataMap.getDataMap().putLong(KeyProperties.KEY_DATE, System.currentTimeMillis());
        for (String node : wearableUtils.getNodes(googleApiClient)) {
            byte[] bytes = dataMap.asPutDataRequest().getData();
            Wearable.MessageApi.sendMessage(googleApiClient, node, KeyProperties.PATH, bytes);
            Log.v(TAG, "sent " + bytes.length + " bytes of data to node " + node);
        }
    } else if (message.startsWith(KeyProperties.MARK_READ_MESSAGE)) {
        markReadHandler.removeCallbacksAndMessages(null);
        markReadHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                String[] messageContent = message.split(KeyProperties.DIVIDER);
                final long id = Long.parseLong(messageContent[1]);
                final AppSettings settings = AppSettings.getInstance(TweetWearableService.this);
                try {
                    HomeDataSource.getInstance(TweetWearableService.this).markPosition(settings.currentAccount, id);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
                sendBroadcast(new Intent("com.klinker.android.twitter.CLEAR_PULL_UNREAD"));
                final SharedPreferences sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);
                // mark tweetmarker if they use it
                if (AppSettings.getInstance(TweetWearableService.this).tweetmarker) {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            TweetMarkerHelper helper = new TweetMarkerHelper(settings.currentAccount, sharedPrefs.getString("twitter_screen_name_" + settings.currentAccount, ""), Utils.getTwitter(TweetWearableService.this, settings), sharedPrefs);
                            helper.sendCurrentId("timeline", id);
                            startService(new Intent(TweetWearableService.this, HandleScrollService.class));
                        }
                    }).start();
                } else {
                    startService(new Intent(TweetWearableService.this, HandleScrollService.class));
                }
            }
        }, 5000);
    } else if (message.startsWith(KeyProperties.REQUEST_FAVORITE)) {
        final long tweetId = Long.parseLong(message.split(KeyProperties.DIVIDER)[1]);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).createFavorite(tweetId);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_COMPOSE)) {
        final String status = message.split(KeyProperties.DIVIDER)[1];
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).updateStatus(status);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_RETWEET)) {
        final long tweetId = Long.parseLong(message.split(KeyProperties.DIVIDER)[1]);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).retweetStatus(tweetId);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_REPLY)) {
        final String tweet = message.split(KeyProperties.DIVIDER)[1];
        final long replyToId = Long.parseLong(message.split(KeyProperties.DIVIDER)[2]);
        final StatusUpdate status = new StatusUpdate(tweet);
        status.setInReplyToStatusId(replyToId);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).updateStatus(status);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_IMAGE)) {
        final String url = message.split(KeyProperties.DIVIDER)[1];
        Bitmap image = null;
        try {
            cache.get(url).getBitmap();
        } catch (Exception e) {
        }
        if (image != null) {
            image = adjustImage(image);
            sendImage(image, url, wearableUtils, googleApiClient);
        } else {
            // download it
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                        InputStream is = new BufferedInputStream(conn.getInputStream());
                        Bitmap image = decodeSampledBitmapFromResourceMemOpt(is, 500, 500);
                        try {
                            is.close();
                        } catch (Exception e) {
                        }
                        try {
                            conn.disconnect();
                        } catch (Exception e) {
                        }
                        cache.put(url, image);
                        image = adjustImage(image);
                        sendImage(image, url, wearableUtils, googleApiClient);
                    } catch (Exception e) {
                    }
                }
            }).start();
        }
    } else {
        Log.e(TAG, "message not recognized");
    }
}
Also used : WearableUtils(com.klinker.android.twitter.utils.WearableUtils) AppSettings(com.klinker.android.twitter.settings.AppSettings) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) URL(java.net.URL) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) PutDataMapRequest(com.google.android.gms.wearable.PutDataMapRequest) GoogleApiClient(com.google.android.gms.common.api.GoogleApiClient) SharedPreferences(android.content.SharedPreferences) TweetMarkerHelper(com.klinker.android.twitter.utils.api_helper.TweetMarkerHelper) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Handler(android.os.Handler) Intent(android.content.Intent) StatusUpdate(twitter4j.StatusUpdate) BitmapLruCache(uk.co.senab.bitmapcache.BitmapLruCache) HandleScrollService(com.klinker.android.twitter.activities.launcher_page.HandleScrollService) ConnectionResult(com.google.android.gms.common.ConnectionResult)

Aggregations

PutDataMapRequest (com.google.android.gms.wearable.PutDataMapRequest)3 Bitmap (android.graphics.Bitmap)2 ConnectionResult (com.google.android.gms.common.ConnectionResult)2 GoogleApiClient (com.google.android.gms.common.api.GoogleApiClient)2 ContentResolver (android.content.ContentResolver)1 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 Cursor (android.database.Cursor)1 BitmapFactory (android.graphics.BitmapFactory)1 Matrix (android.graphics.Matrix)1 Handler (android.os.Handler)1 Artwork (com.google.android.apps.muzei.api.Artwork)1 Asset (com.google.android.gms.wearable.Asset)1 HandleScrollService (com.klinker.android.twitter.activities.launcher_page.HandleScrollService)1 AppSettings (com.klinker.android.twitter.settings.AppSettings)1 IOUtils (com.klinker.android.twitter.utils.IOUtils)1 WearableUtils (com.klinker.android.twitter.utils.WearableUtils)1 TweetMarkerHelper (com.klinker.android.twitter.utils.api_helper.TweetMarkerHelper)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1