List of usage examples for android.os PowerManager newWakeLock
public WakeLock newWakeLock(int levelAndFlags, String tag)
From source file:com.wl.android.downloadwithprogressbutton.downloads.DownloadThread.java
/** * Executes the download in a separate thread *//* www . j a v a 2s .co m*/ public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo); AndroidHttpClient client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = Downloads.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mUri); } client = AndroidHttpClient.newInstance(userAgent(), mContext); boolean finished = false; while (!finished) { Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId); HttpGet request = new HttpGet(state.mRequestUri); try { executeDownload(state, client, request); finished = true; } catch (RetryDownload exc) { // fall through } finally { request.abort(); request = null; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = Downloads.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage()); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex); finalStatus = Downloads.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.close(); client = null; } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData, state.mFilename, state.mNewUri, state.mMimeType); mInfo.mHasActiveThread = false; } }
From source file:org.awesomeapp.messenger.service.RemoteImService.java
@Override public void onCreate() { debug("ImService started"); final String prev = Debug.getTrail(this, SERVICE_CREATE_TRAIL_KEY); if (prev != null) Debug.recordTrail(this, PREV_SERVICE_CREATE_TRAIL_TAG, prev); Debug.recordTrail(this, SERVICE_CREATE_TRAIL_KEY, new Date()); final String prevConnections = Debug.getTrail(this, CONNECTIONS_TRAIL_TAG); if (prevConnections != null) Debug.recordTrail(this, PREV_CONNECTIONS_TRAIL_TAG, prevConnections); Debug.recordTrail(this, CONNECTIONS_TRAIL_TAG, "0"); mConnections = new Hashtable<Long, ImConnectionAdapter>(); mConnectionsByUser = new Hashtable<String, ImConnectionAdapter>(); mHandler = new Handler(); Debug.onServiceStart();/*from www.j a v a2 s . c om*/ //startForegroundCompat(); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "IM_WAKELOCK"); // Clear all account statii to logged-out, since we just got started and we don't want // leftovers from any previous crash. clearConnectionStatii(); mStatusBarNotifier = new StatusBarNotifier(this); mServiceHandler = new ServiceHandler(); mPluginHelper = ImPluginHelper.getInstance(this); mPluginHelper.loadAvailablePlugins(); // Have the heartbeat start autoLogin, unless onStart turns this off mNeedCheckAutoLogin = true; HeartbeatService.startBeating(getApplicationContext()); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); startForeground(notifyId, getForegroundNotification()); }
From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.DownloadThread.java
/** * Executes the download in a separate thread *///from w w w. j a v a 2s . c o m public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo, mService); AndroidHttpClient client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } client = AndroidHttpClient.newInstance(userAgent(), mContext); boolean finished = false; while (!finished) { if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } // Set or unset proxy, which may have changed since last GET // request. // setDefaultProxy() supports null as proxy parameter. ConnRouteParams.setDefaultProxy(client.getParams(), getPreferredHttpHost(mContext, state.mRequestUri)); HttpGet request = new HttpGet(state.mRequestUri); try { executeDownload(state, client, request); finished = true; } catch (RetryDownload exc) { // fall through } finally { request.abort(); request = null; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = DownloaderService.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage()); error.printStackTrace(); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex); finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.close(); client = null; } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount, state.mGotData, state.mFilename); } }
From source file:net.olejon.spotcommander.WebViewActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Google API client mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build(); // Allow landscape? if (!mTools.allowLandscape()) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Hide status bar? if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR")) getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Power manager final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); //noinspection deprecation mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock"); // Settings// w w w . ja v a 2 s .c o m mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false); // Current network mCurrentNetwork = mTools.getCurrentNetwork(); // Computer final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID"); final String[] computer = mTools.getComputer(computerId); final String uri = computer[0]; final String username = computer[1]; final String password = computer[2]; // Layout setContentView(R.layout.activity_webview); // Status bar color if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mStatusBarPrimaryColor = getWindow().getStatusBarColor(); mStatusBarCoverArtColor = mStatusBarPrimaryColor; } // Notification mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN); if (mPersistentNotificationIsSupported) { final Intent launchActivityIntent = new Intent(mContext, MainActivity.class); launchActivityIntent.setAction("android.intent.action.MAIN"); launchActivityIntent.addCategory("android.intent.category.LAUNCHER"); mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class); hideIntent.setAction("hide_notification"); hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class); previousIntent.setAction("previous"); previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class); playPauseIntent.setAction("play_pause"); playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class); nextIntent.setAction("next"); nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class); volumeDownIntent.setAction("adjust_spotify_volume_down"); volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class); volumeUpIntent.setAction("adjust_spotify_volume_up"); volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent, PendingIntent.FLAG_CANCEL_CURRENT); mNotificationManager = NotificationManagerCompat.from(mContext); mNotificationBuilder = new NotificationCompat.Builder(mContext); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mNotificationBuilder.setPriority(Notification.PRIORITY_MAX); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT); } } // Web view mWebView = (WebView) findViewById(R.id.webview_webview); mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background)); mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); mWebView.setWebViewClient(new WebViewClient() { @SuppressWarnings("deprecation") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && !url.contains(uri) && !url.contains("olejon.net/code/spotcommander/api/1/spotify/") && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } return false; } @Override public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host, String realm) { if (handler.useHttpAuthUsernamePassword()) { handler.proceed(username, password); } else { handler.cancel(); mWebView.stopLoading(); mTools.showToast(getString(R.string.webview_authentication_failed), 1); mTools.navigateUp(mActivity); } } @Override public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) { mWebView.stopLoading(); mTools.showToast(getString(R.string.webview_error), 1); mTools.navigateUp(mActivity); } @Override public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) { handler.cancel(); mWebView.stopLoading(); new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title) .content(getString(R.string.webview_dialog_ssl_error_message)) .positiveText(R.string.webview_dialog_ssl_error_positive_button) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { finish(); } }).contentColorRes(R.color.black).show(); } }); // User agent mProjectVersionName = mTools.getProjectVersionName(); final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : ""; final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : ""; final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS")) ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D " : ""; // Web settings final WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(), mProjectVersionName, uaAppend1, uaAppend2, uaAppend3)); // Load app if (savedInstanceState != null) { mWebView.restoreState(savedInstanceState); } else { mWebView.loadUrl(uri); } // JavaScript interface mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android"); }
From source file:cc.mintcoin.wallet.service.BlockchainServiceImpl.java
private void startBlockChain() { if (blockChain != null) return;/* w w w . j av a 2s.c om*/ final Wallet wallet = application.getWallet(); final String lockName = getPackageName() + " blockchain sync"; final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName); peerConnectivityListener = new PeerConnectivityListener(); sendBroadcastPeerState(0); final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW); intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); registerReceiver(connectivityReceiver, intentFilter); boolean blockChainFileExists = blockChainFile.exists(); if (!blockChainFileExists) { log.info("blockchain does not exist, resetting wallet"); wallet.clearTransactions(0); wallet.setLastBlockSeenHeight(-1); // magic value wallet.setLastBlockSeenHash(null); } try { blockStore = new TxTrackingBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile); blockStore.getChainHead(); // detect corruptions as early as possible final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime(); } catch (final BlockStoreException x) { deleteBlockChainFile(); final String msg = "blockstore cannot be created"; log.error(msg, x); throw new Error(msg, x); } log.info("using " + blockStore.getClass().getName()); try { blockChain = new TxTrackingBlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore); } catch (final BlockStoreException x) { throw new Error("blockchain cannot be created", x); } application.getWallet().addEventListener(walletEventListener, Threading.SAME_THREAD); registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK)); maybeRotateKeys(); return; }
From source file:com.mine.psf.PsfPlaybackService.java
@Override public void onCreate() { super.onCreate(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName()); mWakeLock.setReferenceCounted(false); Log.d(LOGTAG, "onCreate, Acquire Wake Lock"); PsfAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); PsfControlResponder = new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()); PsfAudioManager.registerMediaButtonEventReceiver(PsfControlResponder); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); reloadQueue();//from w w w. j a v a2s . co m // If the service was idle, but got killed before it stopped itself, the // system will relaunch it. Make sure it gets stopped again in that case. Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); // Register sd card mount/unmount listener registerExternalStorageListener(); // Register noisy listener, it should // 1) Playing with headset, unplug headset, sound should be paused; // 2) Playing with speaker, plug headset, sound should keep playing. registerNoisyListener(); }
From source file:com.google.android.vending.expansion.downloader.impl.DownloadThread.java
/** * Executes the download in a separate thread *///from www .ja v a 2 s. c o m public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo, mService); AndroidHttpClient client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } client = AndroidHttpClient.newInstance(userAgent(), mContext); boolean finished = false; while (!finished) { if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } // Set or unset proxy, which may have changed since last GET // request. // setDefaultProxy() supports null as proxy parameter. ConnRouteParams.setDefaultProxy(client.getParams(), getPreferredHttpHost(mContext, state.mRequestUri)); HttpGet request = new HttpGet(state.mRequestUri); try { executeDownload(state, client, request); finished = true; } catch (RetryDownload exc) { // fall through } finally { request.abort(); request = null; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = DownloaderService.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage()); error.printStackTrace(); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex); finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.close(); client = null; } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount, state.mGotData, state.mFilename); } }
From source file:info.guardianproject.otr.app.im.service.RemoteImService.java
@Override public void onCreate() { debug("ImService started"); final String prev = Debug.getTrail(this, SERVICE_CREATE_TRAIL_KEY); if (prev != null) Debug.recordTrail(this, PREV_SERVICE_CREATE_TRAIL_TAG, prev); Debug.recordTrail(this, SERVICE_CREATE_TRAIL_KEY, new Date()); final String prevConnections = Debug.getTrail(this, CONNECTIONS_TRAIL_TAG); if (prevConnections != null) Debug.recordTrail(this, PREV_CONNECTIONS_TRAIL_TAG, prevConnections); Debug.recordTrail(this, CONNECTIONS_TRAIL_TAG, "0"); mConnections = new Hashtable<String, ImConnectionAdapter>(); mHandler = new Handler(); Debug.onServiceStart();/*from ww w .ja v a 2 s . c o m*/ PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "IM_WAKELOCK"); // Clear all account statii to logged-out, since we just got started and we don't want // leftovers from any previous crash. clearConnectionStatii(); mStatusBarNotifier = new StatusBarNotifier(this); mServiceHandler = new ServiceHandler(); //mSettingsMonitor = new SettingsMonitor(); /* IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED); registerReceiver(mSettingsMonitor, intentFilter); */ // setBackgroundData(ImApp.getApplication().isNetworkAvailableAndConnected()); mPluginHelper = ImPluginHelper.getInstance(this); mPluginHelper.loadAvailablePlugins(); // Have the heartbeat start autoLogin, unless onStart turns this off mNeedCheckAutoLogin = true; HeartbeatService.startBeating(getApplicationContext()); }
From source file:de.schildbach.wallet.service.BlockchainService.java
@Override public void onCreate() { serviceCreatedAt = System.currentTimeMillis(); log.debug(".onCreate()"); super.onCreate(); nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); application = (WalletApplication) getApplication(); config = application.getConfiguration(); blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME); peerConnectivityListener = new PeerConnectivityListener(); broadcastPeerState(0);/* ww w .j a v a 2 s .co m*/ final WalletBalanceLiveData walletBalance = new WalletBalanceLiveData(application); final ExchangeRateLiveData exchangeRate = new ExchangeRateLiveData(application); walletBalance.observe(this, new Observer<Coin>() { @Override public void onChanged(final Coin walletBalance) { WalletBalanceWidgetProvider.updateWidgets(BlockchainService.this, walletBalance, exchangeRate.getValue()); } }); if (Constants.ENABLE_EXCHANGE_RATES) { exchangeRate.observe(this, new Observer<ExchangeRate>() { @Override public void onChanged(final ExchangeRate exchangeRate) { final Coin balance = walletBalance.getValue(); if (balance != null) WalletBalanceWidgetProvider.updateWidgets(BlockchainService.this, balance, exchangeRate); } }); } wallet = new WalletLiveData(application); wallet.observe(this, new Observer<Wallet>() { @Override public void onChanged(final Wallet wallet) { BlockchainService.this.wallet.removeObserver(this); final boolean blockChainFileExists = blockChainFile.exists(); if (!blockChainFileExists) { log.info("blockchain does not exist, resetting wallet"); wallet.reset(); } try { blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile); blockStore.getChainHead(); // detect corruptions as early as possible final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime(); if (!blockChainFileExists && earliestKeyCreationTime > 0) { try { final Stopwatch watch = Stopwatch.createStarted(); final InputStream checkpointsInputStream = getAssets() .open(Constants.Files.CHECKPOINTS_FILENAME); CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore, earliestKeyCreationTime); watch.stop(); log.info("checkpoints loaded from '{}', took {}", Constants.Files.CHECKPOINTS_FILENAME, watch); } catch (final IOException x) { log.error("problem reading checkpoints, continuing without", x); } } } catch (final BlockStoreException x) { blockChainFile.delete(); final String msg = "blockstore cannot be created"; log.error(msg, x); throw new Error(msg, x); } try { blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore); } catch (final BlockStoreException x) { throw new Error("blockchain cannot be created", x); } observeLiveDatasThatAreDependentOnWalletAndBlockchain(); } }); }
From source file:com.snda.mymarket.providers.downloads.DownloadTask.java
/** * Executes the download in a separate thread *//* w w w .j ava 2 s .c o m*/ public void run() { if (mInfo.mStatus != Downloads.STATUS_RUNNING) { mInfo.mStatus = Downloads.STATUS_RUNNING; ContentValues values = new ContentValues(); values.put(Downloads.COLUMN_STATUS, mInfo.mStatus); mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null); } else { if (Constants.LOGV) { Log.v(Constants.TAG, "download status is: " + mInfo.mStatus); } } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo); HttpStack client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = Downloads.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mUri); } if (Build.VERSION.SDK_INT >= 9) { client = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html client = new HttpClientStack(AndroidHttpClient.newInstance(userAgent())); } boolean finished = false; while (!finished) { Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId); HttpGet request = new HttpGet(state.mRequestUri); try { executeDownload(state, client, request); finished = true; } catch (RetryDownload exc) { // fall through } finally { request.abort(); request = null; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = Downloads.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage()); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex); finalStatus = Downloads.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { mNotifer.notifyDownloadSpeed(mInfo.mId, 0); if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { try { client.close(); client = null; } catch (IOException e) { e.printStackTrace(); finalStatus = Downloads.STATUS_UNKNOWN_ERROR; } } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData, state.mFilename, state.mNewUri, state.mMimeType); mInfo.cancelTask(); } }