Example usage for android.os HandlerThread getLooper

List of usage examples for android.os HandlerThread getLooper

Introduction

In this page you can find the example usage for android.os HandlerThread getLooper.

Prototype

public Looper getLooper() 

Source Link

Document

This method returns the Looper associated with this thread.

Usage

From source file:com.cssweb.android.trade.stock.StockTrading.java

@Override
public void onCreate(Bundle paramBundle) {
    super.onCreate(paramBundle);
    sc = new ServiceControl(this);//??
    ///*from   w w  w. java 2s. co  m*/
    HandlerThread mHandlerThread = new HandlerThread("CSSWEB_THREAD");
    mHandlerThread.start();
    priceHandler = new PriceDataHandler(mHandlerThread.getLooper());

    setContentView(com.cssweb.android.main.R.layout.zr_trade_stock_trade);
    Bundle bundle = getIntent().getExtras();
    type = bundle.getInt("type");
    bsname = bundle.getString("bsname");
    String stockCode = bundle.getString("stkcode");

    initTitle(R.drawable.njzq_title_left_back, 0, bsname);

    LinearLayout localLinearLayout = (LinearLayout) findViewById(R.id.zrtradelayout);
    localLinearLayout.setOnFocusChangeListener(setOnEditFocusListener);
    this.m_vklayout = localLinearLayout;
    View localView1 = this.m_vklayout;
    localView1.setOnFocusChangeListener(setOnEditFocusListener);
    View localView2 = this.m_vklayout;
    localView2.setOnClickListener(setOnEditClickListener);

    viewFlipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01);
    preView = (ImageView) findViewById(R.id.previous_screen);

    leftIn = AnimationUtils.loadAnimation(this, R.anim.push_left_in_layout);
    leftOut = AnimationUtils.loadAnimation(this, R.anim.push_left_out_layout);
    rightIn = AnimationUtils.loadAnimation(this, R.anim.push_right_in_layout);
    rightOut = AnimationUtils.loadAnimation(this, R.anim.push_right_out_layout);

    priceView = (PriceMini) findViewById(R.id.zrviewprice);
    trendView = (TrendView) findViewById(R.id.zrviewtrend);
    trendView.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    });
    klineView = (KlineMini) findViewById(R.id.zrviewkline);
    klineView.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    });
    financeView = (FinanceMini) findViewById(R.id.zrviewfinance);

    stockHolder = (Spinner) findViewById(R.id.zrtxtaccount);
    queryMethod = (Spinner) findViewById(R.id.zrtxtbsflag);
    //      availableNum = (SeekBar) findViewById(R.id.zrcanbs);
    //      lblMaxNumber = (TextView)findViewById(R.id.txtMaxNumber);
    stkcode = (EditText) findViewById(R.id.zredtstockcode);
    stkname = (TextView) findViewById(R.id.zrtxtstockname);
    price = (EditText) findViewById(R.id.zredtprice);
    number = (EditText) findViewById(R.id.zredtcount);
    lblNumberUnit = (TextView) findViewById(R.id.lblNumberUnit);
    btn0 = (ShadowButton) findViewById(R.id.zr_surebutton);
    btn0.setOnClickListener(myShowProgreeBar);

    layoutprice0 = (LinearLayout) findViewById(R.id.LinearLayout03);
    layoutprice = (LinearLayout) findViewById(R.id.LinearLayout11);
    //layoutAvaiNumber = (LinearLayout)findViewById(R.id.LinearLayout04);
    //layoutAvaiAsset = (LinearLayout)findViewById(R.id.LinearLayout06);
    lblAvaiAsset = (TextView) findViewById(R.id.lblAvaiAsset);
    AvaiAsset = (TextView) findViewById(R.id.AvaiAsset);
    lblPrice = (TextView) findViewById(R.id.lblPrice);
    lblPrice1 = (TextView) findViewById(R.id.lblPrice1);
    lblNumber = (TextView) findViewById(R.id.lblNumber);
    avaiAsset = (TextView) findViewById(R.id.AvaiAsset);
    lblNumberUnit = (TextView) findViewById(R.id.lblNumberUnit);

    setDynamic();

    adjustDownPrice = (ImageView) findViewById(R.id.AdjustDownPrice);
    adjustDownPrice.setTag(0);
    adjustDownPrice.setOnClickListener(adjustIconListener);

    adjustUpPrice = (ImageView) findViewById(R.id.AdjustUpPrice);
    adjustUpPrice.setTag(1);
    adjustUpPrice.setOnClickListener(adjustIconListener);

    adjustDownNumber = (ImageView) findViewById(R.id.AdjustDownNumber);
    adjustDownNumber.setTag(2);
    adjustDownNumber.setOnClickListener(adjustIconListener);

    adjustUpNumber = (ImageView) findViewById(R.id.AdjustUpNumber);
    adjustUpNumber.setTag(3);
    adjustUpNumber.setOnClickListener(adjustIconListener);

    stkcode.setText(stockCode);
    if (stkcode.getText().length() == 6) {
        showProgress();
    }

    stkcode.setInputType(InputType.TYPE_NULL);
    stkcode.setFocusable(true);
    stkcode.setTag("STOCK");
    stkcode.setOnClickListener(setOnEditClickListener);
    stkcode.setOnFocusChangeListener(setOnEditFocusListener);

    price.setInputType(InputType.TYPE_NULL);
    price.setFocusable(true);
    price.setTag("NUMDOT");
    price.setOnClickListener(setOnEditClickListener);
    price.setOnFocusChangeListener(setOnEditFocusListener);

    number.setInputType(InputType.TYPE_NULL);
    number.setFocusable(true);
    number.setTag("");
    number.setOnClickListener(setOnEditClickListener);
    number.setOnFocusChangeListener(setOnEditFocusListener);

    stkcode.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable arg0) {
            //queryStock(queryCode.getText());
            OnTextChanged(arg0);
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }

    });

    holder = TradeUser.getInstance().getHolder();

    stockHolderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            (String[]) holder.toArray(new String[holder.size()]));
    stockHolderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    stockHolder.setAdapter(stockHolderAdapter);

    String[] arrayOfString = getResources().getStringArray(R.array.other_market_bs_methods);
    for (int i = 0; i < arrayOfString.length; i++) {
        Log.e("arrayOfString", arrayOfString[i]);
    }

    queryMethodAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayOfString);
    queryMethodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    queryMethod.setAdapter(queryMethodAdapter);
    queryMethod.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position != 0) {
                layoutprice0.setVisibility(View.GONE);
                layoutprice.setVisibility(View.VISIBLE);
            } else {
                layoutprice0.setVisibility(View.VISIBLE);
                layoutprice.setVisibility(View.GONE);
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });

    int h = R.drawable.forminput;
    Resources localResources = getResources();
    Drawable localDrawable = null;
    localDrawable = localResources.getDrawable(h);
    int spinnerheight = localDrawable.getIntrinsicHeight() - 4;
    //      Log.e("<<<<<<<<<<<<<<<<<<<eeeeeeeeeeeeeeeeeeeeeeeeeee>>>>>>>>>>>>>>", String.valueOf(spinnerheight));
    LinearLayout.LayoutParams linearParams1 = (LinearLayout.LayoutParams) stockHolder.getLayoutParams();//?stockHolder?
    linearParams1.height = spinnerheight;//??
    stockHolder.setLayoutParams(linearParams1);

    LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) queryMethod.getLayoutParams();//?queryMethod?
    linearParams.height = spinnerheight;//??
    queryMethod.setLayoutParams(linearParams);
}

From source file:org.runbuddy.tomahawk.services.PlaybackService.java

private void initMediaSession() {
    ComponentName componentName = new ComponentName(this, MediaButtonReceiver.class);
    mMediaSession = new MediaSessionCompat(getApplicationContext(), "Tomahawk", componentName, null);
    mMediaSession.setFlags(//from w  ww. j  a  v  a2  s  .  co  m
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    Intent intent = new Intent(PlaybackService.this, TomahawkMainActivity.class);
    intent.setAction(TomahawkMainActivity.SHOW_PLAYBACKFRAGMENT_ON_STARTUP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(PlaybackService.this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mMediaSession.setSessionActivity(pendingIntent);
    HandlerThread thread = new HandlerThread("playbackservice_callback");
    thread.start();
    mCallbackHandler = new Handler(thread.getLooper());
    mMediaSession.setCallback(mMediaSessionCallback, mCallbackHandler);
    mMediaSession.setRatingType(RatingCompat.RATING_HEART);
    Bundle extras = new Bundle();
    extras.putString(EXTRAS_KEY_PLAYBACKMANAGER, mPlaybackManager.getId());
    mMediaSession.setExtras(extras);
    updateMediaPlayState();
    setSessionToken(mMediaSession.getSessionToken());
}

From source file:com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.java

/**
 * Schedule an auto-reconnect attempt using backoff logic.
 *
 * @return true if attempt was scheduled, false otherwise.
 *//*  w  w  w .  ja  va 2s.  c om*/
private boolean scheduleReconnect() {
    LOGGER.info("schedule Reconnect attempt " + autoReconnectsAttempted + " of " + maxAutoReconnectAttempts
            + " in " + currentReconnectRetryTime + " seconds.");
    // schedule a reconnect if unlimited or if we haven't yet hit the limit

    if (maxAutoReconnectAttempts == -1 || autoReconnectsAttempted < maxAutoReconnectAttempts) {
        //Start a separate thread to do reconnect, because connection must not occur on the main thread.
        final HandlerThread ht = new HandlerThread("Reconnect thread");
        ht.start();
        Looper looper = ht.getLooper();
        Handler handler = new Handler(looper);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LOGGER.debug("TID: " + ht.getThreadId() + " trying to reconnect to session");
                if (mqttClient != null && !mqttClient.isConnected()) {
                    reconnectToSession();
                }
            }
        }, MILLIS_IN_ONE_SECOND * currentReconnectRetryTime);
        currentReconnectRetryTime = Math.min(currentReconnectRetryTime * 2, maxReconnectRetryTime);
        return true;
    } else {
        LOGGER.warn("schedule reconnect returns false");
        return false;
    }
}

From source file:uk.co.pjmobile.mobile_apps.page_turner_reader.ReadingActivity.java

/** Called when the activity is first created. */
@Override/*from www.  ja v  a2 s.  c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Restore preferences
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.read_book);
    setupConstants();

    this.uiHandler = new Handler();

    HandlerThread bgThread = new HandlerThread("background");
    bgThread.start();
    this.backgroundHandler = new Handler(bgThread.getLooper());

    this.waitDialog = new ProgressDialog(this);
    this.waitDialog.setOwnerActivity(this);
    this.waitDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            // This just consumes all key events and does nothing.
            return true;
        }
    });

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    this.gestureDetector = new GestureDetector(this, new NavGestureDetector(bookView, this, metrics));
    //      this.gestureDetector = new GestureDetector(new NavGestureDetector(
    //bookView, this, metrics));

    this.gestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    };

    this.progressBar.setFocusable(true);
    this.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        private int seekValue;

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            bookView.navigateToPercentage(this.seekValue);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                seekValue = progress;
                percentageField.setText(progress + "% ");
            }
        }
    });

    this.viewSwitcher.setOnTouchListener(gestureListener);
    bookView.setOnTouchListener(gestureListener);

    bookView.addListener(this);
    bookView.setSpanner(getInjector().getInstance(HtmlSpanner.class));
    //      this.bookView.setSpanner(new HtmlSpanner());

    this.oldBrightness = config.isBrightnessControlEnabled();
    this.oldStripWhiteSpace = config.isStripWhiteSpaceEnabled();
    this.oldFontName = config.getFontFamily().getName();

    registerForContextMenu(bookView);

    String file = getIntent().getStringExtra("file_name");
    if (file == null && getIntent().getData() != null) {
        file = getIntent().getData().getPath();
    }

    if (file == null) {
        file = config.getLastOpenedFile();
    }

    updateFromPrefs();
    updateFileName(savedInstanceState, file);

    if ("".equals(fileName)) {

        //         Intent intent = new Intent(this, LibraryActivity.class);
        //         startActivity(intent);
        //         finish();
        //         return;
        //         Util.toast(this, "Launch library activity. Empty file name");

    } else {

        /**         if (savedInstanceState == null && config.isSyncEnabled()) {
                    new DownloadProgressTask().execute();
                 } else {**/
        bookView.restore();
        //         }
    }

}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    LogUtil.d(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    brand = Build.MODEL + Build.BRAND;/*from w w  w. j  ava 2s. co m*/
    TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    uuid = tm.getDeviceId();
    messageDao = MessageDao.getInstance(this);
    toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();

    // ???
    initView();
    // ???
    initActivityState(savedInstanceState);

    final ArrayList<ECMessage> list = IMessageSqlManager.queryIMessageList(mThread, 20,
            getMessageAdapterLastMessageTime() + "");
    mListView.post(new Runnable() {

        @Override
        public void run() {
            mChattingAdapter.setData(list);
            if (mChattingAdapter.getCount() < 20) {
                //mPullDownView.setPullEnabled(false);
                //mPullDownView.setPullViewVisibed(false);
            }
            mListView.clearFocus();
            mChattingAdapter.notifyDataSetChanged();
            mListView.setSelection(mChattingAdapter.getCount());
        }
    });

    // ?IM?API
    mChatManager = SDKCoreHelper.getECChatManager();
    HandlerThread thread = new HandlerThread("ChattingVoiceRecord", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mChattingLooper = thread.getLooper();
    mVoiceHandler = new Handler(mChattingLooper);
    mVoiceHandler.post(new Runnable() {

        @Override
        public void run() {
            doEmojiPanel();
        }
    });
}

From source file:im.vector.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs/*from www. j av  a 2s.  c  om*/
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    cursor.close();
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mConsoleMessageListFragment.uploadMediaContent(fMediaUrl, fMimeType,
                                                fFilename);
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

From source file:io.realm.TypeBasedNotificationsTests.java

@Test
@RunTestInLooperThread//w  ww.  j av a  2s .  com
public void callback_with_relevant_commit_from_different_looper_realmobject_async() {
    final CountDownLatch looperThread1Done = new CountDownLatch(1);
    final CountDownLatch looperThread2Done = new CountDownLatch(1);
    final CountDownLatch looperThread3Done = new CountDownLatch(1);
    final HandlerThread looperThread1 = new HandlerThread("looperThread1");
    final HandlerThread looperThread2 = new HandlerThread("looperThread2");
    final HandlerThread looperThread3 = new HandlerThread("looperThread3");
    looperThread1.start();
    looperThread2.start();
    looperThread3.start();
    final Handler looperHandler1 = new Handler(looperThread1.getLooper());
    final Handler looperHandler2 = new Handler(looperThread2.getLooper());
    final Handler looperHandler3 = new Handler(looperThread3.getLooper());
    final Realm realm = looperThread.realm;
    realm.addChangeListener(new RealmChangeListener() {
        @Override
        public void onChange() {
            globalCommitInvocations.incrementAndGet();
        }
    });

    final Dog dog = realm.where(Dog.class).findFirstAsync();
    assertTrue(dog.load());
    dog.addChangeListener(new RealmChangeListener() {
        @Override
        public void onChange() {
            switch (typebasedCommitInvocations.incrementAndGet()) {
            case 1: // triggered by COMPLETED_ASYNC_REALM_OBJECT from calling dog.load()
                assertTrue(dog.isLoaded());
                assertFalse(dog.isValid());

                looperHandler1.post(new Runnable() {
                    @Override
                    public void run() {
                        Realm realmLooperThread1 = Realm.getInstance(realm.getConfiguration());
                        realmLooperThread1.beginTransaction();
                        realmLooperThread1.commitTransaction();
                        realmLooperThread1.close();
                        looperThread1Done.countDown();
                    }
                });
                break;
            case 2: // triggered by the irrelevant commit (not affecting Dog table) from LooperThread1
                assertTrue(dog.isLoaded());
                assertFalse(dog.isValid());

                looperHandler2.post(new Runnable() {
                    @Override
                    public void run() {
                        Realm realmLooperThread2 = Realm.getInstance(realm.getConfiguration());
                        // trigger first callback invocation
                        realmLooperThread2.beginTransaction();
                        Dog dog = realmLooperThread2.createObject(Dog.class);
                        dog.setName("Akamaru");
                        realmLooperThread2.commitTransaction();
                        realmLooperThread2.close();
                        looperThread2Done.countDown();
                    }
                });
                break;

            case 3: // triggered by relevant commit from LooperThread2
                assertEquals("Akamaru", dog.getName());
                realm.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // trigger second callback invocation
                        looperHandler3.post(new Runnable() {
                            @Override
                            public void run() {
                                Realm realmLooperThread3 = Realm.getInstance(realm.getConfiguration());
                                realmLooperThread3.beginTransaction();
                                realmLooperThread3.where(Dog.class).findFirst().setAge(17);
                                realmLooperThread3.commitTransaction();
                                realmLooperThread3.close();
                                looperThread3Done.countDown();
                            }
                        });
                    }
                });
                break;
            case 4:
                assertEquals("Akamaru", dog.getName());
                assertEquals(17, dog.getAge());
                // posting as an event will give the handler a chance
                // to deliver the notification for globalCommitInvocations
                // otherwise, test will exit before the callback get a chance to be invoked
                realm.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        assertEquals(3, globalCommitInvocations.get());
                        assertEquals(4, typebasedCommitInvocations.get());
                        looperThread1.quit();
                        looperThread2.quit();
                        looperThread3.quit();
                        TestHelper.awaitOrFail(looperThread1Done);
                        TestHelper.awaitOrFail(looperThread2Done);
                        TestHelper.awaitOrFail(looperThread3Done);
                        looperThread.testComplete();
                    }
                });
                break;
            }
        }
    });

}

From source file:org.matrix.console.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs/* www  .ja  va 2  s .com*/
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    if (null != cursor) {
                                        cursor.close();
                                    }
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if ((null != fMimeType) && fMimeType.startsWith("video/")) {
                                            mConsoleMessageListFragment.uploadVideoContent(fMediaUrl, null,
                                                    fMimeType);
                                        } else {
                                            mConsoleMessageListFragment.uploadFileContent(fMediaUrl, fMimeType,
                                                    fFilename);
                                        }
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();//from   www  .j a va  2s .com
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command");
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log");
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats");
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for interactive state changes
    last_interactive = Util.isInteractive(this);
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    ifInteractive.addAction(ACTION_SCREEN_OFF_DELAYED);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}