Example usage for android.os SystemClock elapsedRealtime

List of usage examples for android.os SystemClock elapsedRealtime

Introduction

In this page you can find the example usage for android.os SystemClock elapsedRealtime.

Prototype

@CriticalNative
native public static long elapsedRealtime();

Source Link

Document

Returns milliseconds since boot, including time spent in sleep.

Usage

From source file:com.yek.keyboard.keyboards.views.AnyKeyboardView.java

@Override
public void onDraw(Canvas canvas) {
    final boolean keyboardChanged = mKeyboardChanged;
    super.onDraw(canvas);
    // switching animation
    if (mAnimationLevel != AskPrefs.AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) {
        startAnimation(mInAnimation);//from  www.  j  a v  a2 s  .co m
        mInAnimation = null;
    }
    // text pop out animation
    if (mPopOutText != null && mAnimationLevel != AskPrefs.AnimationsLevel.None) {
        final int maxVerticalTravel = getHeight() / 2;
        final long currentAnimationTime = SystemClock.elapsedRealtime() - mPopOutTime;
        if (currentAnimationTime > TEXT_POP_OUT_ANIMATION_DURATION) {
            mPopOutText = null;
        } else {
            final float popOutPositionProgress = ((float) currentAnimationTime)
                    / ((float) TEXT_POP_OUT_ANIMATION_DURATION);
            final float animationProgress = mPopOutTextReverting ? 1f - popOutPositionProgress
                    : popOutPositionProgress;
            final float animationInterpolatorPosition = getPopOutAnimationInterpolator(false,
                    animationProgress);
            final int y = mPopOutStartPoint.y - (int) (maxVerticalTravel * animationInterpolatorPosition);
            final int x = mPopOutStartPoint.x;
            final int alpha = mPopOutTextReverting ? (int) (255 * animationProgress)
                    : 255 - (int) (255 * animationProgress);
            // drawing
            setPaintToKeyText(mPaint);
            // will disappear over time
            mPaint.setAlpha(alpha);
            mPaint.setShadowLayer(5, 0, 0, Color.BLACK);
            // will grow over time
            mPaint.setTextSize(mPaint.getTextSize() * (1.0f + animationInterpolatorPosition));
            canvas.translate(x, y);
            canvas.drawText(mPopOutText, 0, mPopOutText.length(), 0, 0, mPaint);
            canvas.translate(-x, -y);
            //we're doing reverting twice much faster
            if (mPopOutTextReverting) {
                mPopOutTime = mPopOutTime - (int) (60 * popOutPositionProgress);
            }
            // next frame
            postInvalidateDelayed(1000 / 60);// doing 60 frames per second;
        }
    }
    //showing alpha/beta icon if needed
    if (BuildConfig.TESTING_BUILD) {
        final float textSizeForBuildSign = mPaint.getTextSize() / 2f;
        final float x = getWidth() - (mBuildTypeSignText.length() * textSizeForBuildSign);
        final float y = getHeight() - textSizeForBuildSign - getPaddingBottom();
        canvas.translate(x, y);
        canvas.drawText(mBuildTypeSignText, 0, mBuildTypeSignText.length(), 0, 0, mBuildTypeSignPaint);
        canvas.translate(-x, -y);
    }
}

From source file:com.android.im.imps.HttpDataChannel.java

private void trySend(Primitive p) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {//from  w  w w  .  j  av a  2  s . c  o m
        mSerializer.serialize(p, out);
    } catch (SerializerException e) {
        mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.SERIALIZER_ERROR,
                "Internal serializer error, primitive: " + p.getType());
        out.close();
        return;
    }

    HttpPost req = new HttpPost(mPostUri);
    req.addHeader(mContentTypeHeader);
    if (mMsisdnHeader != null) {
        req.addHeader(mMsisdnHeader);
    }
    ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
    req.setEntity(entity);

    mLastActive = SystemClock.elapsedRealtime();
    if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) {
        long sendBytes = entity.getContentLength() + 176 /* approx. header length */;
        ImpsLog.log(mConnection.getLoginUserName() + " >> " + p.getType() + " HTTP payload approx. " + sendBytes
                + " bytes");
    }
    if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
        ImpsLog.dumpRawPacket(out.toByteArray());
        ImpsLog.dumpPrimitive(p);
    }

    HttpResponse res = mHttpClient.execute(req);
    StatusLine statusLine = res.getStatusLine();
    HttpEntity resEntity = res.getEntity();

    InputStream in = resEntity.getContent();

    if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
        Log.d(ImpsLog.PACKET_TAG, statusLine.toString());
        Header[] headers = res.getAllHeaders();
        for (Header h : headers) {
            Log.d(ImpsLog.PACKET_TAG, h.toString());
        }
        int len = (int) resEntity.getContentLength();
        if (len > 0) {
            byte[] content = new byte[len];
            int offset = 0;
            int bytesRead = 0;
            do {
                bytesRead = in.read(content, offset, len);
                offset += bytesRead;
                len -= bytesRead;
            } while (bytesRead > 0);
            in.close();
            ImpsLog.dumpRawPacket(content);
            in = new ByteArrayInputStream(content);
        }
    }

    try {
        if (statusLine.getStatusCode() != HttpURLConnection.HTTP_OK) {
            mTxManager.notifyErrorResponse(p.getTransactionID(), statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());
            return;
        }
        if (resEntity.getContentLength() == 0) {
            // empty responses are only valid for Polling-Request or
            // server initiated transactions
            if ((p.getTransactionMode() != TransactionMode.Response)
                    && !p.getType().equals(ImpsTags.Polling_Request)) {
                mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.ILLEGAL_SERVER_RESPONSE,
                        "bad response from server");
            }
            return;
        }

        Primitive response = mParser.parse(in);

        if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
            ImpsLog.dumpPrimitive(response);
        }

        if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) {
            long len = 2 + resEntity.getContentLength() + statusLine.toString().length() + 2;
            Header[] headers = res.getAllHeaders();
            for (Header header : headers) {
                len += header.getName().length() + header.getValue().length() + 4;
            }
            ImpsLog.log(mConnection.getLoginUserName() + " << " + response.getType() + " HTTP payload approx. "
                    + len + "bytes");
        }

        if (!mReceiveQueue.offer(response)) {
            // This is almost impossible for a LinkedBlockingQueue.
            // We don't even bother to assign an error code for it.
            mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.UNKNOWN_ERROR,
                    "receiving queue full");
        }
    } catch (ParserException e) {
        ImpsLog.logError(e);
        mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.PARSER_ERROR,
                "Parser error, received a bad response from server");
    } finally {
        //consume all the content so that the connection can be re-used.
        resEntity.consumeContent();
    }
}

From source file:com.lastsoft.plog.adapter.GameAdapter.java

@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
    //Log.d(TAG, "Element " + position + " set.");
    // Get element from your dataset at this position and replace the contents of the view
    // with that element
    //if (searchQuery.equals("") || (games.get(position).gameName.toLowerCase().contains(searchQuery.toLowerCase()))) {

    DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");

    if (games.get(position).tbtCount >= 5) {
        viewHolder.getNickDimeView().setVisibility(View.VISIBLE);
        if (games.get(position).tbtCount >= 25) {
            viewHolder.getNickDimeView().setText("25");
        } else if (games.get(position).tbtCount >= 10) {
            viewHolder.getNickDimeView().setText("10");
        } else {//from www  . j av a2s  . co m
            viewHolder.getNickDimeView().setText("5");
        }
    } else {
        viewHolder.getNickDimeView().setVisibility(View.GONE);
    }
    viewHolder.getTextView().setText(games.get(position).gameName);
    if (games.get(position).gameThumb != null && !games.get(position).gameThumb.equals("")) {
        //Log.d("V1", "gameThumb = " + games.get(position).gameThumb);
        //ImageLoader.getInstance().displayImage("http:" + games.get(position).gameThumb, viewHolder.getImageView(), options);
        Picasso.with(mActivity).load("http:" + games.get(position).gameThumb).into(viewHolder.getImageView());

    } else {
        viewHolder.getImageView().setImageDrawable(null);
    }

    if (games.get(position).recentPlay > 0) {
        Date theDate = new Date((long) games.get(position).recentPlay);
        long diff = new Date().getTime() - theDate.getTime();
        long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        String output_date2;
        if (days == 0) {
            output_date2 = mActivity.getString(R.string.less_than_a_day_ago);
        } else if (days == 1) {
            output_date2 = mActivity.getString(R.string.last_play_label) + days
                    + mActivity.getString(R.string.day_ago_label);
        } else if (days <= 6) {
            output_date2 = mActivity.getString(R.string.last_play_label) + days
                    + mActivity.getString(R.string.days_ago_label);
        } else {
            output_date2 = mActivity.getString(R.string.last_play_label) + outputFormatter.format(theDate); // Output : 01/20/2012
        }
        viewHolder.getRecentPlayView().setText(output_date2);
        viewHolder.getRecentPlayView().setVisibility(View.VISIBLE);
    } else {
        viewHolder.getRecentPlayView().setVisibility(View.INVISIBLE);
    }

    if (games.get(position).taggedToPlay > 0 && playListType == 2) {
        Date theDate = new Date(((long) games.get(position).taggedToPlay) * 1000L);
        long diff = new Date().getTime() - theDate.getTime();
        long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        String output_date;
        if (days == 0) {
            output_date = mActivity.getString(R.string.added)
                    + mActivity.getString(R.string.less_than_a_day_ago);
        } else if (days == 1) {
            output_date = mActivity.getString(R.string.added) + days
                    + mActivity.getString(R.string.day_ago_label);
        } else if (days <= 6) {
            output_date = mActivity.getString(R.string.added) + days
                    + mActivity.getString(R.string.days_ago_label);
        } else {
            output_date = mActivity.getString(R.string.added) + outputFormatter.format(theDate); // Output : 01/20/2012
        }
        //String output_date = outputFormatter.format(theDate); // Output : 01/20/2012
        viewHolder.getBucketDateView().setText(output_date);
        viewHolder.getBucketDateView().setVisibility(View.VISIBLE);
    } else {
        viewHolder.getBucketDateView().setVisibility(View.GONE);
    }

    if (playListType != 1) {
        viewHolder.getOverflowLayout().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playPopup(view, position);
            }
        });
        if (games.get(position).expansionFlag == false) {
            viewHolder.getClickLayout().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
                        return;
                    }
                    mLastClickTime = SystemClock.elapsedRealtime();
                    ((MainActivity) mActivity).openAddPlay(mFragment, games.get(position).gameName, -1, false);
                }
            });
        } else {
            viewHolder.getClickLayout().setOnClickListener(null);
        }
    } else {
        viewHolder.getOverflowLayout().setVisibility(View.GONE);
    }

    viewHolder.getGamePlaysView().setText(mActivity.getString(R.string.plays) + games.get(position).playCount);
    //}

}

From source file:com.xixicm.de.data.storage.SentenceDataRepository.java

private void setFetchAlarm(ScheduleFetchEvent.TYPE type) {
    LogUtils.d(Constants.TAG, "setFetchAlarm: " + type);
    ScheduleFetchEvent scheduleFetchEvent = new ScheduleFetchEvent(SystemClock.elapsedRealtime(), type);
    getEventBus().post(scheduleFetchEvent);
}

From source file:br.com.bioscada.apps.biotracks.widgets.TrackWidgetProvider.java

/**
 * Updates total time.//from www .j a v a2s . co m
 * 
 * @param context the context
 * @param remoteViews the remote views
 * @param ids the item's ids
 * @param tripStatistics the trip statistics
 */
private static void updateTotalTime(Context context, RemoteViews remoteViews, int[] ids,
        TripStatistics tripStatistics, boolean isRecording, boolean isPaused) {
    if (isRecording && !isPaused && tripStatistics != null) {
        long time = tripStatistics.getTotalTime() + System.currentTimeMillis() - tripStatistics.getStopTime();
        remoteViews.setChronometer(ids[3], SystemClock.elapsedRealtime() - time, null, true);
        remoteViews.setViewVisibility(ids[1], View.GONE);
        remoteViews.setViewVisibility(ids[2], View.GONE);
        remoteViews.setViewVisibility(ids[3], View.VISIBLE);
    } else {
        remoteViews.setChronometer(ids[3], SystemClock.elapsedRealtime(), null, false);
        remoteViews.setViewVisibility(ids[1], View.VISIBLE);
        remoteViews.setViewVisibility(ids[2], View.GONE);
        remoteViews.setViewVisibility(ids[3], View.GONE);

        String totalTime = tripStatistics == null ? context.getString(R.string.value_unknown)
                : StringUtils.formatElapsedTime(tripStatistics.getTotalTime());
        remoteViews.setTextViewText(ids[0], context.getString(R.string.stats_total_time));
        remoteViews.setTextViewText(ids[1], totalTime);
    }
}

From source file:com.example.android.mediarouter.player.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Be sure to call the super class.
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        mPlayer = (Player) savedInstanceState.getSerializable("mPlayer");
    }//from w ww  .ja  v a  2 s  .co m

    // Get the media router service.
    mMediaRouter = MediaRouter.getInstance(this);

    // Create a route selector for the type of routes that we care about.
    mSelector = new MediaRouteSelector.Builder().addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
            .addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
            .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
            .addControlCategory(SampleMediaRouteProvider.CATEGORY_SAMPLE_ROUTE).build();

    // Add a fragment to take care of media route discovery.
    // This fragment automatically adds or removes a callback whenever the activity
    // is started or stopped.
    FragmentManager fm = getSupportFragmentManager();
    DiscoveryFragment fragment = (DiscoveryFragment) fm.findFragmentByTag(DISCOVERY_FRAGMENT_TAG);
    if (fragment == null) {
        fragment = new DiscoveryFragment(mMediaRouterCB);
        fragment.setRouteSelector(mSelector);
        fm.beginTransaction().add(fragment, DISCOVERY_FRAGMENT_TAG).commit();
    } else {
        fragment.setCallback(mMediaRouterCB);
        fragment.setRouteSelector(mSelector);
    }

    // Populate an array adapter with streaming media items.
    String[] mediaNames = getResources().getStringArray(R.array.media_names);
    String[] mediaUris = getResources().getStringArray(R.array.media_uris);
    mLibraryItems = new LibraryAdapter();
    for (int i = 0; i < mediaNames.length; i++) {
        mLibraryItems.add(new MediaItem("[streaming] " + mediaNames[i], Uri.parse(mediaUris[i]), "video/mp4"));
    }

    // Scan local external storage directory for media files.
    File externalDir = Environment.getExternalStorageDirectory();
    if (externalDir != null) {
        File list[] = externalDir.listFiles();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                String filename = list[i].getName();
                if (filename.matches(".*\\.(m4v|mp4)")) {
                    mLibraryItems.add(new MediaItem("[local] " + filename, Uri.fromFile(list[i]), "video/mp4"));
                }
            }
        }
    }

    mPlayListItems = new PlaylistAdapter();

    // Initialize the layout.
    setContentView(R.layout.sample_media_router);

    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();
    String tabName = getResources().getString(R.string.library_tab_text);
    TabSpec spec1 = tabHost.newTabSpec(tabName);
    spec1.setContent(R.id.tab1);
    spec1.setIndicator(tabName);

    tabName = getResources().getString(R.string.playlist_tab_text);
    TabSpec spec2 = tabHost.newTabSpec(tabName);
    spec2.setIndicator(tabName);
    spec2.setContent(R.id.tab2);

    tabName = getResources().getString(R.string.statistics_tab_text);
    TabSpec spec3 = tabHost.newTabSpec(tabName);
    spec3.setIndicator(tabName);
    spec3.setContent(R.id.tab3);

    tabHost.addTab(spec1);
    tabHost.addTab(spec2);
    tabHost.addTab(spec3);
    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String arg0) {
            updateUi();
        }
    });

    mLibraryView = (ListView) findViewById(R.id.media);
    mLibraryView.setAdapter(mLibraryItems);
    mLibraryView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mLibraryView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateButtons();
        }
    });

    mPlayListView = (ListView) findViewById(R.id.playlist);
    mPlayListView.setAdapter(mPlayListItems);
    mPlayListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mPlayListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateButtons();
        }
    });

    mInfoTextView = (TextView) findViewById(R.id.info);

    mPauseResumeButton = (ImageButton) findViewById(R.id.pause_resume_button);
    mPauseResumeButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPaused = !mPaused;
            if (mPaused) {
                mSessionManager.pause();
            } else {
                mSessionManager.resume();
            }
        }
    });

    mStopButton = (ImageButton) findViewById(R.id.stop_button);
    mStopButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPaused = false;
            mSessionManager.stop();
        }
    });

    mSeekBar = (SeekBar) findViewById(R.id.seekbar);
    mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            PlaylistItem item = getCheckedPlaylistItem();
            if (fromUser && item != null && item.getDuration() > 0) {
                long pos = progress * item.getDuration() / 100;
                mSessionManager.seek(item.getItemId(), pos);
                item.setPosition(pos);
                item.setTimestamp(SystemClock.elapsedRealtime());
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mSeeking = true;
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mSeeking = false;
            updateUi();
        }
    });

    // Schedule Ui update
    mHandler.postDelayed(mUpdateSeekRunnable, 1000);

    // Build the PendingIntent for the remote control client
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mEventReceiver = new ComponentName(getPackageName(), SampleMediaButtonReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    // Create and register the remote control client
    registerRemoteControlClient();

    // Set up playback manager and player
    mPlayer = Player.create(MainActivity.this, mMediaRouter.getSelectedRoute());
    mSessionManager.setPlayer(mPlayer);
    mSessionManager.setCallback(new SessionManager.Callback() {
        @Override
        public void onStatusChanged() {
            updateUi();
        }

        @Override
        public void onItemChanged(PlaylistItem item) {
        }
    });

    updateUi();
}

From source file:net.kidlogger.kidlogger.KLService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //List file synchronizer
    listFileSync = new ListFileSync(this);

    // Check a previous file and send the file if exist
    checkPrevFiles();//w w w  .java 2s . c om

    // Handle outgoing call delay 
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            String message = (String) msg.obj;
            if (message == null)
                return;
            //Log.i("KLS", "message: " + message);
            if (message.equals("start")) {
                delayNewCallEvent = new CountDownTimer(15000L, 1000L) {
                    public void onTick(long millisUntilFinish) {
                    }

                    public void onFinish() {
                        new Thread(new Runnable() {
                            public void run() {
                                //Log.i("KLS", "doAfterDelay");
                                doAfterDelay();
                            }
                        }).start();
                    }
                }.start();
            } else if (message.equals("stop")) {
                //Log.i("KLS", "Stop delay");
                if (delayNewCallEvent != null) {
                    delayNewCallEvent.cancel();
                    delayNewCallEvent = null;
                }
            }
        }
    };

    // Define a BroadcastReceiver to detect if date is changed
    /*dateChanged = new BroadcastReceiver(){
       public void onReceive(Context context, Intent intent){
    String action = intent.getAction();
                  
    if(action != null && action.equals(Intent.ACTION_DATE_CHANGED)){
       new Thread(new Runnable(){
          public void run(){
             checkPrevFiles();
             app.logError(CN, "Date is changed");
          }
       }).start();
    }            
       }
    };
    IntentFilter filter = new IntentFilter(Intent.ACTION_DATE_CHANGED);      
    registerReceiver(dateChanged, filter);*/

    // Stub of remote service
    remoteServiceStub = new IRemoteService.Stub() {
        public void sendString(String string) throws RemoteException {
            runKeyEvent(string);
        }
    };

    // Setup things to log
    setupLogging();

    // Uploading files      
    if (Settings.uploadLogs(this)) {
        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        if (mAlarmManager == null) {
            app.logError(CN + "onStartCommand", "Couldn't get AlarmManager");
            uploadOn = false;
        } else {
            //Intent i = new Intent(this, AlarmReceiver.class);
            Intent i = new Intent(KLService.ALARM_ACTION);
            mPI = PendingIntent.getBroadcast(this, 0, i, 0);
            mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
                    postSendingFreq, mPI);
        }

        //---------------------------------------------------------------------------------
        /*mUploadData = new Runnable(){
           public void run(){
              new Thread(new Runnable(){
          public void run(){
             //doSendingFile();
             doSendHtml();
             checkDate();
             if(!mIsRoaming)
                doSendMedia();
          }
              }).start();
              handlering.postDelayed(mUploadData, postSendingFreq);
           }            
        };
        handlering.postDelayed(mUploadData, postSendingFreq);*/
        //---------------------------------------------------------------------------------
        uploadOn = true;
    }

    // Log power
    boolean powerOn = getBoolPref("powerOff");
    if (powerOn) {
        new Thread(new Runnable() {
            public void run() {
                sync.writeLog(".htm", Templates.getPowerLog(false));
            }
        }).start();
        //WriteThread wpl = new WriteThread(sync, ".htm", Templates.getPowerLog(false));

        saveToPref("powerOff", false);
    }

    // Log start service
    logServiceState(true);

    app.mService = this;
    app.mServiceOnCreate = false;

    //Log.i(CN + "onStartCommand", "onStartCommand");

    return START_STICKY;
}

From source file:com.example.android.mediarouter.player.RadioActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Be sure to call the super class.
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        mPlayer = (RadioPlayer) savedInstanceState.getSerializable("mPlayer");
    }/*from w  w  w . j  av  a  2 s .c  o  m*/

    // Get the media router service.
    mMediaRouter = MediaRouter.getInstance(this);

    // Create a route selector for the type of routes that we care about.
    mSelector = new MediaRouteSelector.Builder().addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
            .addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
            .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
            .addControlCategory(SampleMediaRouteProvider.CATEGORY_SAMPLE_ROUTE).build();

    // Add a fragment to take care of media route discovery.
    // This fragment automatically adds or removes a callback whenever the activity
    // is started or stopped.
    FragmentManager fm = getSupportFragmentManager();
    DiscoveryFragment fragment = (DiscoveryFragment) fm.findFragmentByTag(DISCOVERY_FRAGMENT_TAG);
    if (fragment == null) {
        fragment = new DiscoveryFragment(mMediaRouterCB);
        fragment.setRouteSelector(mSelector);
        fm.beginTransaction().add(fragment, DISCOVERY_FRAGMENT_TAG).commit();
    } else {
        fragment.setCallback(mMediaRouterCB);
        fragment.setRouteSelector(mSelector);
    }

    // Populate an array adapter with streaming media items.
    String[] mediaNames = getResources().getStringArray(R.array.media_names);
    String[] mediaUris = getResources().getStringArray(R.array.media_uris);
    mLibraryItems = new LibraryAdapter();
    for (int i = 0; i < mediaNames.length; i++) {
        mLibraryItems.add(new MediaItem("[streaming] " + mediaNames[i], Uri.parse(mediaUris[i]), "video/mp4"));
    }

    // Scan local external storage directory for media files.
    File externalDir = Environment.getExternalStorageDirectory();
    if (externalDir != null) {
        File list[] = externalDir.listFiles();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                String filename = list[i].getName();
                if (filename.matches(".*\\.(m4v|mp4)")) {
                    mLibraryItems.add(new MediaItem("[local] " + filename, Uri.fromFile(list[i]), "video/mp4"));
                }
            }
        }
    }

    mPlayListItems = new PlaylistAdapter();

    // Initialize the layout.
    setContentView(R.layout.sample_radio_router);

    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();
    String tabName = getResources().getString(R.string.library_tab_text);
    TabSpec spec1 = tabHost.newTabSpec(tabName);
    spec1.setContent(R.id.tab1);
    spec1.setIndicator(tabName);

    tabName = getResources().getString(R.string.playlist_tab_text);
    TabSpec spec2 = tabHost.newTabSpec(tabName);
    spec2.setIndicator(tabName);
    spec2.setContent(R.id.tab2);

    tabName = getResources().getString(R.string.statistics_tab_text);
    TabSpec spec3 = tabHost.newTabSpec(tabName);
    spec3.setIndicator(tabName);
    spec3.setContent(R.id.tab3);

    tabHost.addTab(spec1);
    tabHost.addTab(spec2);
    tabHost.addTab(spec3);
    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String arg0) {
            updateUi();
        }
    });

    mLibraryView = (ListView) findViewById(R.id.media);
    mLibraryView.setAdapter(mLibraryItems);
    mLibraryView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mLibraryView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateButtons();
        }
    });

    mPlayListView = (ListView) findViewById(R.id.playlist);
    mPlayListView.setAdapter(mPlayListItems);
    mPlayListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mPlayListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateButtons();
        }
    });

    mInfoTextView = (TextView) findViewById(R.id.info);

    mPauseResumeButton = (ImageButton) findViewById(R.id.pause_resume_button);
    mPauseResumeButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPaused = !mPaused;
            if (mPaused) {
                mSessionManager.pause();
            } else {
                mSessionManager.resume();
            }
        }
    });

    mStopButton = (ImageButton) findViewById(R.id.stop_button);
    mStopButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPaused = false;
            mSessionManager.stop();
        }
    });

    mSeekBar = (SeekBar) findViewById(R.id.seekbar);
    mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            PlaylistItem item = getCheckedPlaylistItem();
            if (fromUser && item != null && item.getDuration() > 0) {
                long pos = progress * item.getDuration() / 100;
                mSessionManager.seek(item.getItemId(), pos);
                item.setPosition(pos);
                item.setTimestamp(SystemClock.elapsedRealtime());
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mSeeking = true;
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mSeeking = false;
            updateUi();
        }
    });

    // Schedule Ui update
    mHandler.postDelayed(mUpdateSeekRunnable, 1000);

    // Build the PendingIntent for the remote control client
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mEventReceiver = new ComponentName(getPackageName(), SampleMediaButtonReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    // Create and register the remote control client
    registerRemoteControlClient();

    // Set up playback manager and player
    mPlayer = RadioPlayer.create(RadioActivity.this, mMediaRouter.getSelectedRoute());
    mSessionManager.setPlayer(mPlayer);
    mSessionManager.setCallback(new RadioSessionManager.Callback() {
        @Override
        public void onStatusChanged() {
            updateUi();
        }

        @Override
        public void onItemChanged(PlaylistItem item) {
        }
    });

    updateUi();
}

From source file:com.mobicage.rpc.newxmpp.XMPPConfigurationFactory.java

public ConnectionConfiguration getSafeXmppConnectionConfiguration(final String xmppServiceName,
        final String email, final boolean hasFailed) throws XMPPConfigurationException {

    debuglog("Creating new XMPP connection");

    if (!mConnectivityManager.isConnected()) {
        debuglog("No network.");
        throw new XMPPConfigurationException("No network.");
    }//from   w w  w.j a v a2 s.c  om

    final ConnectionConfiguration xmppConfig;
    if (hasFailed) {
        debuglog("Getting config from cloud because previous connection attempt failed.");
        xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email);
    } else {
        debuglog("Getting config from config provider.");
        ConnectionConfiguration tmpXmppConfig = getBasicXMPPConfigurationFromConfigProvider(xmppServiceName);
        if (tmpXmppConfig == null) {
            debuglog("Getting config from cloud because config provider is empty.");
            xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email);
        } else
            xmppConfig = tmpXmppConfig;
    }

    if (xmppConfig == null) {
        debuglog("No xmpp configuration found.");
        throw new XMPPConfigurationException("No xmpp configuration found.");
    }

    final HostAddress[] hostAddresses = xmppConfig.getHosts();
    if (hostAddresses.length == 0) {
        debuglog("Error: did not receive any XMPP DNS SRV record");
        throw new XMPPConfigurationException("Did not find any XMPP DNS SRV record");
    } else if (hostAddresses.length == 1 && xmppServiceName.equals(hostAddresses[0].getHost())
            && XMPP_DEFAULT_PORT == hostAddresses[0].getPort()) {
        buglog("Using fallback value for DNS SRV (but network is up): " + hostAddresses[0]);
    }

    debuglog("Found XMPP DNS SRV records:");
    for (int i = hostAddresses.length - 1; i >= 0; i--) {
        debuglog("- host = " + hostAddresses[i]);
    }

    final int preferredXMPPPort = hostAddresses[hostAddresses.length - 1].getPort();
    debuglog("Preferred XMPP port is " + preferredXMPPPort);

    // Do non-blocking TCP connect attempts
    Map<HostAddress, SocketChannel> allChannels = new HashMap<HostAddress, SocketChannel>();
    Map<HostAddress, SocketChannel> remainingChannels = new HashMap<HostAddress, SocketChannel>();
    for (int i = hostAddresses.length - 1; i >= 0; i--) {
        final HostAddress ha = hostAddresses[i];
        try {
            SocketChannel sChannel = SocketChannel.open();
            allChannels.put(ha, sChannel);
            sChannel.configureBlocking(false);
            sChannel.connect(new InetSocketAddress(ha.getHost(), ha.getPort()));
            remainingChannels.put(ha, sChannel);
        } catch (IOException e) {
            // Cannot connect to one socket ; let's not drop others
            debuglog("Ignoring socket due to connection error: " + ha);
        }
    }

    if (remainingChannels.size() == 0) {
        debuglog("Error: could not connect to any of the XMPP DNS SRV records");
        debuglog("Closing attempted TCP sockets");
        for (SocketChannel sc : allChannels.values()) {
            try {
                sc.close();
            } catch (IOException e) {
            }
        }
        debuglog("All attempted TCP sockets are closed now");
        throw new XMPPConfigurationException("Error: could not connect to any of the XMPP DNS SRV records");
    }

    final long starttime = SystemClock.elapsedRealtime();

    HostAddress goodHostAddress = null;
    while (true) {

        Iterator<Entry<HostAddress, SocketChannel>> iter = remainingChannels.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<HostAddress, SocketChannel> e = iter.next();
            final HostAddress ha = e.getKey();
            final SocketChannel sc = e.getValue();
            try {
                if (sc.finishConnect()) {
                    if (sc.isConnected()) {
                        debuglog("Successful TCP connection to " + ha);
                        iter.remove();
                        if (goodHostAddress != null) {
                            // We already found a host
                            // Pick this better one only if the one we found already was not using the
                            // preferred XMPP port, and the new one does have the preferred XMPP port
                            if (goodHostAddress.getPort() != preferredXMPPPort
                                    && ha.getPort() == preferredXMPPPort) {
                                goodHostAddress = ha;
                                debuglog("Found better host " + goodHostAddress);
                            } else {
                                debuglog("Old host was better: " + goodHostAddress);
                            }
                        } else {
                            goodHostAddress = ha;
                            debuglog("Selecting host " + goodHostAddress);
                        }
                    } else {
                        debuglog("Failed TCP connection to " + ha);
                        iter.remove();
                    }
                }
            } catch (IOException ex) {
                // Error during finishConnect()
                debuglog("TCP connection timeout to " + ha);
                iter.remove();
            }
        }

        final long now = SystemClock.elapsedRealtime();
        if (goodHostAddress != null && goodHostAddress.getPort() == preferredXMPPPort) {
            debuglog("Found responsive XMPP host with preferred port " + preferredXMPPPort);
            break;
        }
        if (remainingChannels.size() == 0) {
            debuglog("No more XMPP hosts to check");
            break;
        }
        if (now > starttime + XMPP_MAX_CONNECT_MILLIS) {
            debuglog("Timeout trying to find responsive XMPP host");
            break;
        }
        if (goodHostAddress != null) {
            if (now > starttime + XMPP_MAX_TRY_PREFERRED_PORT_MILLIS) {
                // XXX: would be better to wait at most N seconds (e.g. 2) AFTER the first successful connection
                // happened (to a non preferred port)
                debuglog("Give up looking for responsive XMPP host with preferred port.");
                break;
            }
            boolean stillWaitingForConnectionWithPreferredPort = false;
            for (HostAddress ha : remainingChannels.keySet()) {
                if (ha.getPort() == preferredXMPPPort) {
                    stillWaitingForConnectionWithPreferredPort = true;
                    break;
                }
            }
            if (!stillWaitingForConnectionWithPreferredPort) {
                debuglog("No more responsive XMPP hosts with preferred port to wait for.");
                break;
            }
        }

        debuglog("Sleeping " + XMPP_POLLING_INTERVAL_MILLIS + "ms while trying to connect to XMPP");
        try {
            Thread.sleep(XMPP_POLLING_INTERVAL_MILLIS);
        } catch (InterruptedException ex) {
            throw new XMPPConfigurationException("Interrupt during Thread.sleep()");
        }
    }

    debuglog("Closing attempted TCP sockets");
    for (SocketChannel sc : allChannels.values()) {
        try {
            sc.close();
        } catch (IOException e) {
        }
    }
    debuglog("All attempted TCP sockets are closed now");

    if (goodHostAddress == null) {
        debuglog("Did not find a good host address and hasfailed: " + hasFailed);
        clearSRVConfig();
        if (hasFailed)
            throw new XMPPConfigurationException("Could not connect to any of the XMPP targets");
        else
            return getSafeXmppConnectionConfiguration(xmppServiceName, email, true);
    }

    debuglog("Using XMPP host " + goodHostAddress);
    xmppConfig.setHosts(new HostAddress[] { goodHostAddress });
    return xmppConfig;
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

private float showElapsedTime() {
    float SECOND = 1000;
    float MINUTE = 60 * SECOND;
    float elapsedMillis = SystemClock.elapsedRealtime() - mTimer.getBase();
    elapsedMillis = elapsedMillis / MINUTE;
    return elapsedMillis;
}