List of usage examples for android.content Context POWER_SERVICE
String POWER_SERVICE
To view the source code for android.content Context POWER_SERVICE.
Click Source Link
From source file:com.fanxin.app.main.fragment.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { String packageName = getPackageName(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (!pm.isIgnoringBatteryOptimizations(packageName)) { Intent intent = new Intent(); intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent);/*from ww w. j av a2 s. co m*/ } } //make sure activity will not in background if user is logged into another device or removed if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) { DemoHelper.getInstance().logout(false, null); finish(); startActivity(new Intent(this, LoginActivity.class)); return; } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) { finish(); startActivity(new Intent(this, LoginActivity.class)); return; } setContentView(R.layout.fx_activity_main); // runtime permission for android 6.0, just require all permissions here for simple requestPermissions(); initView(); //umeng api MobclickAgent.updateOnlineConfig(this); UmengUpdateAgent.setUpdateOnlyWifi(false); UmengUpdateAgent.update(this); if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) { showConflictDialog(); } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) { showAccountRemovedDialog(); } inviteMessgeDao = new InviteMessgeDao(this); userDao = new UserDao(this); // conversationListFragment=(ConversationListFragment)getSupportFragmentManager().findFragmentByTag(TAG_COVERSATION); // contactListFragment=(ContactListFragment)getSupportFragmentManager().findFragmentByTag(TAG_CONTACTS); // fragmentFind=(FragmentFind)getSupportFragmentManager().findFragmentByTag(TAG_FIND); // fragmentProfile=(FragmentProfile)getSupportFragmentManager().findFragmentByTag(TAG_PROFILE); // FragmentTransaction manager = getSupportFragmentManager().beginTransaction(); // if(conversationListFragment==null){ // conversationListFragment = new ConversationListFragment(); // manager.add(R.id.fragment_container, conversationListFragment, TAG_COVERSATION); // } // if(contactListFragment==null){ // contactListFragment = new ContactListFragment(); // manager.add(R.id.fragment_container, contactListFragment, TAG_CONTACTS); // } // if(fragmentFind==null){ // fragmentFind = new FragmentFind(); // manager.add(R.id.fragment_container, fragmentFind, TAG_FIND).hide(fragmentFind); // } // if(fragmentProfile==null){ // fragmentProfile = new FragmentProfile(); // manager.add(R.id.fragment_container, fragmentProfile, TAG_PROFILE).hide(fragmentProfile); // } // manager.show(conversationListFragment).hide(contactListFragment).hide(fragmentFind).hide(fragmentProfile).commit(); conversationListFragment = new ConversationListFragment(); contactListFragment = new ContactListFragment(); fragmentFind = new FragmentFind(); fragmentProfile = new FragmentProfile(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, conversationListFragment) .add(R.id.fragment_container, contactListFragment).hide(contactListFragment) .show(conversationListFragment).commit(); fragments = new Fragment[] { conversationListFragment, contactListFragment, fragmentFind, fragmentProfile }; //register broadcast receiver to receive the change of group from DemoHelper registerBroadcastReceiver(); EMClient.getInstance().contactManager().setContactListener(new MyContactListener()); //debug purpose only registerInternalDebugReceiver(); }
From source file:org.secu3.android.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { setTheme(PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(getString(R.string.pref_night_mode_key), false) ? R.style.AppBaseTheme : R.style.AppBaseTheme_Light); setContentView(R.layout.activity_main); packetUtils = new PacketUtils(this); sensorsFormat = getString(R.string.sensors_format); speedFormat = getString(R.string.speed_format); sensorsRawFormat = getString(R.string.sensors_raw_format); textViewData = (TextView) findViewById(R.id.textViewData); textViewDataExt = (TextView) findViewById(R.id.textViewDataExt); textViewStatus = (TextView) findViewById(R.id.mainTextViewStatus); textFWInfo = (TextView) findViewById(R.id.mainTextFWInfo); receiver = new ReceiveMessages(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Secu3Droid wakelock"); if (savedInstanceState != null) { textViewData.setText(savedInstanceState.getString(DATA)); textViewStatus.setText(savedInstanceState.getString(STATUS)); rawSensors = savedInstanceState.getBoolean(RAW_SENSORS); }//from w w w .ja va2 s . c o m setRawMode(rawSensors); logButtonLayout = (LinearLayout) findViewById(R.id.mainLogButtonLayout); View.OnClickListener logButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.mainLogButton1: startService(new Intent(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK, Uri.EMPTY, v.getContext(), Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM, SECU3_TASK.SECU3_SET_LOG_MARKER_1.ordinal())); break; case R.id.mainLogButton2: startService(new Intent(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK, Uri.EMPTY, v.getContext(), Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM, SECU3_TASK.SECU3_SET_LOG_MARKER_2.ordinal())); break; case R.id.mainLogButton3: startService(new Intent(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK, Uri.EMPTY, v.getContext(), Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM, SECU3_TASK.SECU3_SET_LOG_MARKER_3.ordinal())); break; default: break; } } }; Button b = (Button) findViewById(R.id.mainLogButton1); b.setOnClickListener(logButtonListener); b = (Button) findViewById(R.id.mainLogButton2); b.setOnClickListener(logButtonListener); b = (Button) findViewById(R.id.mainLogButton3); b.setOnClickListener(logButtonListener); super.onCreate(savedInstanceState); }
From source file:com.endiansoftware.echo.remotewatch.GcmIntentService.java
private void sendNotification(Bundle msg) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_gcm).setContentTitle(msg.get("key1").toString()) .setContentText(msg.get("key2").toString()).setTicker(msg.get("key1").toString()); mBuilder.setContentIntent(contentIntent); Notification notification = mBuilder.build(); if (msg.get("collapse_key").toString().equals("Emergency")) { notification.flags |= notification.FLAG_INSISTENT | notification.FLAG_AUTO_CANCEL; notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS; notification.vibrate = new long[] { 100L, 100L, 200L, 500L }; } else {//w w w . j av a 2 s .c om notification.flags |= notification.FLAG_AUTO_CANCEL; notification.defaults |= Notification.DEFAULT_LIGHTS; notification.vibrate = new long[] { 100L }; } mNotificationManager.notify(NOTIFICATION_ID, notification); PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG"); wl.acquire(); }
From source file:org.durka.hallmonitor.CoreStateManager.java
CoreStateManager(Context context) { mAppContext = context;/* w w w . j a v a2 s . c o m*/ mPowerManager = (PowerManager) mAppContext.getSystemService(Context.POWER_SERVICE); daPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreStateManager"); daPartialWakeLock.setReferenceCounted(false); globalPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreReceiver"); globalPartialWakeLock.setReferenceCounted(true); preference_all = PreferenceManager.getDefaultSharedPreferences(mAppContext); // Enable access to sleep mode systemApp = (mAppContext.getApplicationInfo().flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; if (systemApp) { Log.d(LOG_TAG, "We are a system app."); } else { Log.d(LOG_TAG, "We are not a system app."); preference_all.edit().putBoolean("pref_internal_power_management", false).commit(); } refreshAdminApp(); refreshRootApp(); refreshLockMode(); refreshOsPowerManagement(); refreshInternalPowerManagement(); refreshInternalService(); if (preference_all.getBoolean("pref_proximity", false)) { forceCheckCoverState = true; } hmAppWidgetManager = new HMAppWidgetManager(this); if (preference_all.getBoolean("pref_default_widget", false)) { int widgetId = preference_all.getInt("default_widget_id", -1); if (widgetId == -1) { registerWidget("default"); } else { createWidget("default"); } } if (preference_all.getBoolean("pref_media_widget", false)) { audioManager = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE); int widgetId = preference_all.getInt("media_widget_id", -1); if (widgetId == -1) { registerWidget("media"); } else { createWidget("media"); } } this.hardwareAccelerated = preference_all.getBoolean("pref_hardwareAccelerated", false); // we might have missed a phone-state revelation phone_ringing = ((TelephonyManager) mAppContext.getSystemService(Context.TELEPHONY_SERVICE)) .getCallState() == TelephonyManager.CALL_STATE_RINGING; // we might have missed an alarm alert // TODO: find a way // alarm_firing = // ((TelephonyManager) // mAppContext.getSystemService(Context.TELEPHONY_SERVICE)).getCallState() // == TelephonyManager.CALL_STATE_RINGING; Intent stateIntent = mAppContext.registerReceiver(null, new IntentFilter(CoreReceiver.TORCH_STATE_CHANGED)); torch_on = stateIntent != null && stateIntent.getIntExtra("state", 0) != 0; init = true; }
From source file:com.wifi.brainbreaker.mydemo.spydroid.ui.SpydroidActivity.java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApplication = (SpydroidApplication) getApplication(); setContentView(R.layout.spydroid);// w ww.ja va 2s . c om if (findViewById(R.id.handset_pager) != null) { // Handset detected ! mAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.handset_pager); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mSurfaceView = (SurfaceView) findViewById(R.id.handset_camera_view); SessionBuilder.getInstance().setSurfaceView(mSurfaceView); SessionBuilder.getInstance().setPreviewOrientation(90); } else { // Tablet detected ! device = TABLET; mAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.tablet_pager); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); SessionBuilder.getInstance().setPreviewOrientation(0); } mViewPager.setAdapter(mAdapter); // Remove the ads if this is the donate version of the app. // if (mApplication.DONATE_VERSION) { // ((LinearLayout)findViewById(R.id.adcontainer)).removeAllViews(); // } // Prevents the phone from going to sleep mode PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "net.majorkernelpanic.spydroid.wakelock"); // Starts the service of the HTTP server this.startService(new Intent(this, CustomHttpServer.class)); // Starts the service of the RTSP server this.startService(new Intent(this, CustomRtspServer.class)); }
From source file:com.cellbots.local.EyesView.java
public EyesView(CellDroidActivity ct, String url, boolean torch) { Log.e("remote eyes", "started " + url); mParent = ct;// w ww .ja va 2 s.c o m putUrl = url; PowerManager pm = (PowerManager) ct.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock( PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Cellbot Eyes"); mWakeLock.acquire(); out = new ByteArrayOutputStream(); if (putUrl != null) { isLocalUrl = putUrl.contains("127.0.0.1") || putUrl.contains("localhost"); server = putUrl.replace("http://", ""); server = server.substring(0, server.indexOf("/")); mTorchMode = torch; resetConnection(); mHttpState = new HttpState(); } ct.setContentView(R.layout.eyes_main); mPreview = (SurfaceView) ct.findViewById(R.id.eyes_preview); mHolder = mPreview.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mPreview.setOnClickListener(new OnClickListener() { public void onClick(View v) { setTorchMode(!mTorchMode); } }); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean useTorch = intent.getBooleanExtra("TORCH", false); boolean shouldTakePicture = intent.getBooleanExtra("PICTURE", false); setTorchMode(useTorch); setTakePicture(shouldTakePicture); } }; ct.registerReceiver(mReceiver, new IntentFilter(EyesView.EYES_COMMAND)); mFrame = (FrameLayout) ct.findViewById(R.id.eyes_frame); mImageView = new ImageView(ct); mImageView.setScaleType(ScaleType.FIT_CENTER); mImageView.setBackgroundColor(Color.BLACK); setPersona(PERSONA_READY); mFrame.addView(mImageView); }
From source file:net.majorkernelpanic.spydroid.ui.SpydroidActivity.java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApplication = (SpydroidApplication) getApplication(); setContentView(R.layout.spydroid);// w w w .ja v a 2 s.com if (findViewById(R.id.handset_pager) != null) { // Handset detected ! mAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.handset_pager); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mSurfaceView = (SurfaceView) findViewById(R.id.handset_camera_view); SessionBuilder.getInstance().setSurfaceView(mSurfaceView); SessionBuilder.getInstance().setPreviewOrientation(90); } else { // Tablet detected ! device = TABLET; mAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.tablet_pager); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); SessionBuilder.getInstance().setPreviewOrientation(0); } mViewPager.setAdapter(mAdapter); // Remove the ads if this is the donate version of the app. if (mApplication.DONATE_VERSION) { ((LinearLayout) findViewById(R.id.adcontainer)).removeAllViews(); } // Prevents the phone from going to sleep mode PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "net.majorkernelpanic.spydroid.wakelock"); // Starts the service of the HTTP server this.startService(new Intent(this, CustomHttpServer.class)); // Starts the service of the RTSP server this.startService(new Intent(this, CustomRtspServer.class)); }
From source file:com.lchtime.safetyexpress.ui.chat.hx.activity.HXMainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { String packageName = getPackageName(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (!pm.isIgnoringBatteryOptimizations(packageName)) { Intent intent = new Intent(); intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent);//w w w .j a va2s . c o m } } //make sure activity will not in background if user is logged into another device or removed if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) { DemoHelper.getInstance().logout(false, null); finish(); startActivity(new Intent(this, LoginUI.class)); return; } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) { finish(); startActivity(new Intent(this, LoginUI.class)); return; } setContentView(R.layout.em_activity_main); // runtime permission for android 6.0, just require all permissions here for simple ub_id = SpTools.getUserId(this); requestPermissions(); initView(); showExceptionDialogFromIntent(getIntent()); inviteMessgeDao = new InviteMessgeDao(this); UserDao userDao = new UserDao(this); conversationListFragment = new ConversationListFragment(); contactListFragment = new ContactListFragment(); // SettingsFragment settingFragment = new SettingsFragment(); fragments = new Fragment[] { conversationListFragment, contactListFragment }; getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, conversationListFragment) .show(conversationListFragment).commit(); //register broadcast receiver to receive the change of group from DemoHelper registerBroadcastReceiver(); EMClient.getInstance().contactManager().setContactListener(new MyContactListener()); //debug purpose only registerInternalDebugReceiver(); }
From source file:com.tgx.tina.android.plugin.downloader.DownloadThread.java
/** * Executes the download in a separate thread *///from w w w . j a va 2 s.com public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); int finalStatus = GlobalDownload.STATUS_UNKNOWN_ERROR; boolean countRetry = false; int retryAfter = 0; int redirectCount = mInfo.mRedirectCount; String newUri = null; boolean gotData = false; String filename = null; String mimeType = sanitizeMimeType(mInfo.mMimeType); FileOutputStream stream = null; DefaultHttpClient client = null; PowerManager.WakeLock wakeLock = null; Uri contentUri = Uri.parse(GlobalDownload.CONTENT_URI + "/" + mInfo.mId); try { boolean continuingDownload = false; String headerAcceptRanges = null; String headerContentDisposition = null; String headerContentLength = null; String headerContentLocation = null; String headerETag = null; String headerTransferEncoding = null; byte data[] = new byte[Constants.BUFFER_SIZE]; int bytesSoFar = 0; PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); filename = mInfo.mFileName; if (filename != null) { if (!Helpers.isFilenameValid(filename)) { finalStatus = GlobalDownload.STATUS_FILE_ERROR; notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType); return; } // We're resuming a download that got interrupted File f = new File(filename); if (f.exists()) { long fileLength = f.length(); if (fileLength == 0) { // The download hadn't actually started, we can restart from scratch f.delete(); filename = null; } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) { // Tough luck, that's not a resumable download //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "can't resume interrupted non-resumable download"); f.delete(); finalStatus = GlobalDownload.STATUS_PRECONDITION_FAILED; notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType); return; } else { // All right, we'll be able to resume this download stream = new FileOutputStream(filename, true); bytesSoFar = (int) fileLength; if (mInfo.mTotalBytes != -1) { headerContentLength = Integer.toString(mInfo.mTotalBytes); } headerETag = mInfo.mETag; continuingDownload = true; } } } int bytesNotified = bytesSoFar; // starting with MIN_VALUE means that the first write will commit // progress to the database long timeLastNotification = 0; client = newHttpClient(userAgent()); /* * This loop is run once for every individual HTTP request that gets * sent. The very first HTTP request is a "virgin" request, while * every subsequent request is done with the original ETag and a * byte-range. */ http_request_loop: while (true) { // Prepares the request and fires it. HttpGet request = new HttpGet(mInfo.mUri); //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "initiating download for " + mInfo.mUri); if (mInfo.mCookies != null) { request.addHeader("Cookie", mInfo.mCookies); } if (mInfo.mReferer != null) { request.addHeader("Referer", mInfo.mReferer); } if (continuingDownload) { if (headerETag != null) { request.addHeader("If-Match", headerETag); } request.addHeader("Range", "bytes=" + bytesSoFar + "-"); } HttpResponse response; try { response = client.execute(request); } catch (IllegalArgumentException ex) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "Arg exception trying to execute request for " + mInfo.mId + " : " + ex); finalStatus = GlobalDownload.STATUS_BAD_REQUEST; request.abort(); break http_request_loop; } catch (IOException ex) { //#ifdef debug //#if debug<=2 if (Helpers.isNetworkAvailable(mContext)) { base.tina.core.log.LogPrinter.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Up"); } else { base.tina.core.log.LogPrinter.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Down"); } //#endif //#endif if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; countRetry = true; } else { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "IOException trying to execute request for " + mInfo.mId + " : " + ex); finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR; } request.abort(); break http_request_loop; } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) { //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "got HTTP response code 503"); finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; countRetry = true; Header header = response.getFirstHeader("Retry-After"); if (header != null) { try { //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "Retry-After :" + header.getValue()); retryAfter = Integer.parseInt(header.getValue()); if (retryAfter < 0) { retryAfter = 0; } else { if (retryAfter < Constants.MIN_RETRY_AFTER) { retryAfter = Constants.MIN_RETRY_AFTER; } else if (retryAfter > Constants.MAX_RETRY_AFTER) { retryAfter = Constants.MAX_RETRY_AFTER; } retryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1); retryAfter *= 1000; } } catch (NumberFormatException ex) { // ignored - retryAfter stays 0 in this case. } } request.abort(); break http_request_loop; } if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) { //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "got HTTP redirect " + statusCode); if (redirectCount >= Constants.MAX_REDIRECTS) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "too many redirects for download " + mInfo.mId); finalStatus = GlobalDownload.STATUS_TOO_MANY_REDIRECTS; request.abort(); break http_request_loop; } Header header = response.getFirstHeader("Location"); if (header != null) { //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "Location :" + header.getValue()); try { newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString(); } catch (URISyntaxException ex) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "Couldn't resolve redirect URI for download " + mInfo.mId); finalStatus = GlobalDownload.STATUS_BAD_REQUEST; request.abort(); break http_request_loop; } ++redirectCount; finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; request.abort(); break http_request_loop; } } if ((!continuingDownload && statusCode != GlobalDownload.STATUS_SUCCESS) || (continuingDownload && statusCode != 206)) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "http error " + statusCode + " for download " + mInfo.mId); if (GlobalDownload.isStatusError(statusCode)) { finalStatus = statusCode; } else if (statusCode >= 300 && statusCode < 400) { finalStatus = GlobalDownload.STATUS_UNHANDLED_REDIRECT; } else if (continuingDownload && statusCode == GlobalDownload.STATUS_SUCCESS) { finalStatus = GlobalDownload.STATUS_PRECONDITION_FAILED; } else { finalStatus = GlobalDownload.STATUS_UNHANDLED_HTTP_CODE; } request.abort(); break http_request_loop; } else { // Handles the response, saves the file //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "received response for " + mInfo.mUri); if (!continuingDownload) { Header header = response.getFirstHeader("Accept-Ranges"); if (header != null) { headerAcceptRanges = header.getValue(); } header = response.getFirstHeader("Content-Disposition"); if (header != null) { headerContentDisposition = header.getValue(); } header = response.getFirstHeader("Content-Location"); if (header != null) { headerContentLocation = header.getValue(); } if (mimeType == null) { header = response.getFirstHeader("Content-Type"); if (header != null) { mimeType = sanitizeMimeType(header.getValue()); } } header = response.getFirstHeader("ETag"); if (header != null) { headerETag = header.getValue(); } header = response.getFirstHeader("Transfer-Encoding"); if (header != null) { headerTransferEncoding = header.getValue(); } if (headerTransferEncoding == null) { header = response.getFirstHeader("Content-Length"); if (header != null) { headerContentLength = header.getValue(); } } else { // Ignore content-length with transfer-encoding - 2616 4.4 3 //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "ignoring content-length because of xfer-encoding"); } //#ifdef debug //#if debug<=2 base.tina.core.log.LogPrinter.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges); base.tina.core.log.LogPrinter.v(Constants.TAG, "Content-Disposition: " + headerContentDisposition); base.tina.core.log.LogPrinter.v(Constants.TAG, "Content-Length: " + headerContentLength); base.tina.core.log.LogPrinter.v(Constants.TAG, "Content-Location: " + headerContentLocation); base.tina.core.log.LogPrinter.v(Constants.TAG, "Content-Type: " + mimeType); base.tina.core.log.LogPrinter.v(Constants.TAG, "ETag: " + headerETag); base.tina.core.log.LogPrinter.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding); //#endif //#endif if (!mInfo.mNoIntegrity && headerContentLength == null && (headerTransferEncoding == null || !headerTransferEncoding.equalsIgnoreCase("chunked"))) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "can't know size of download, giving up"); finalStatus = GlobalDownload.STATUS_LENGTH_REQUIRED; request.abort(); break http_request_loop; } DownloadFileInfo fileInfo = Helpers.generateSaveFile(mContext, mInfo.mUri, mInfo.mHint, headerContentDisposition, headerContentLocation, mimeType, mInfo.mDestination, (headerContentLength != null) ? Integer.parseInt(headerContentLength) : 0); if (fileInfo.mFileName == null) { finalStatus = fileInfo.mStatus; request.abort(); break http_request_loop; } filename = fileInfo.mFileName; stream = fileInfo.mStream; //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "writing " + mInfo.mUri + " to " + filename); ContentValues values = new ContentValues(); values.put(GlobalDownload._DATA, filename); if (headerETag != null) { values.put(Constants.ETAG, headerETag); } if (mimeType != null) { values.put(GlobalDownload.COLUMN_MIME_TYPE, mimeType); } int contentLength = -1; if (headerContentLength != null) { contentLength = Integer.parseInt(headerContentLength); } values.put(GlobalDownload.COLUMN_TOTAL_BYTES, contentLength); mContext.getContentResolver().update(contentUri, values, null, null); } InputStream entityStream; try { entityStream = response.getEntity().getContent(); } catch (IOException ex) { //#ifdef debug //#if debug<=2 if (Helpers.isNetworkAvailable(mContext)) { base.tina.core.log.LogPrinter.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Up"); } else { base.tina.core.log.LogPrinter.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Down"); } //#endif //#endif if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; countRetry = true; } else { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "IOException getting entity for download " + mInfo.mId + " : " + ex); finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR; } request.abort(); break http_request_loop; } for (;;) { int bytesRead; try { bytesRead = entityStream.read(data); } catch (IOException ex) { //#ifdef debug //#if debug<=2 if (Helpers.isNetworkAvailable(mContext)) { base.tina.core.log.LogPrinter.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Up"); } else { base.tina.core.log.LogPrinter.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Down"); } //#endif //#endif ContentValues values = new ContentValues(); values.put(GlobalDownload.COLUMN_CURRENT_BYTES, bytesSoFar); mContext.getContentResolver().update(contentUri, values, null, null); if (!mInfo.mNoIntegrity && headerETag == null) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "download IOException for download " + mInfo.mId + " : " + ex); finalStatus = GlobalDownload.STATUS_PRECONDITION_FAILED; } else if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; countRetry = true; } else { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "download IOException for download " + mInfo.mId + " : " + ex); finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR; } request.abort(); break http_request_loop; } if (bytesRead == -1) { // success ContentValues values = new ContentValues(); values.put(GlobalDownload.COLUMN_CURRENT_BYTES, bytesSoFar); if (headerContentLength == null) { values.put(GlobalDownload.COLUMN_TOTAL_BYTES, bytesSoFar); } mContext.getContentResolver().update(contentUri, values, null, null); if ((headerContentLength != null) && (bytesSoFar != Integer.parseInt(headerContentLength))) { if (!mInfo.mNoIntegrity && headerETag == null) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "mismatched content length for " + mInfo.mId); finalStatus = GlobalDownload.STATUS_LENGTH_REQUIRED; } else if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; countRetry = true; } else { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "closed socket for download " + mInfo.mId); finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR; } break http_request_loop; } break; } gotData = true; for (;;) { try { if (stream == null) { stream = new FileOutputStream(filename, true); } stream.write(data, 0, bytesRead); break; } catch (IOException ex) { finalStatus = GlobalDownload.STATUS_FILE_ERROR; break http_request_loop; } } bytesSoFar += bytesRead; long now = System.currentTimeMillis(); if (bytesSoFar - bytesNotified > Constants.MIN_PROGRESS_STEP && now - timeLastNotification > Constants.MIN_PROGRESS_TIME) { ContentValues values = new ContentValues(); values.put(GlobalDownload.COLUMN_CURRENT_BYTES, bytesSoFar); mContext.getContentResolver().update(contentUri, values, null, null); bytesNotified = bytesSoFar; timeLastNotification = now; } //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "downloaded " + bytesSoFar + " for " + mInfo.mUri); synchronized (mInfo) { if (mInfo.mControl == GlobalDownload.CONTROL_PAUSED) { //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "paused " + mInfo.mUri); finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED; request.abort(); break http_request_loop; } } if (mInfo.mStatus == GlobalDownload.STATUS_CANCELED) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "canceled id " + mInfo.mId); finalStatus = GlobalDownload.STATUS_CANCELED; break http_request_loop; } } //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "download completed for " + mInfo.mUri); finalStatus = GlobalDownload.STATUS_SUCCESS; } break; } } catch (FileNotFoundException ex) { //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex); finalStatus = GlobalDownload.STATUS_FILE_ERROR; // falls through to the code that reports an error } catch (RuntimeException ex) { //sometimes the socket code throws unchecked exceptions //#debug base.tina.core.log.LogPrinter.d(Constants.TAG, "Exception for id " + mInfo.mId, ex); finalStatus = GlobalDownload.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { mInfo.mHasActiveThread = false; if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.getConnectionManager().shutdown();//??? client = null; } try { // close the file if (stream != null) { stream.close(); } } catch (IOException ex) { //#debug verbose base.tina.core.log.LogPrinter.v(Constants.TAG, "exception when closing the file after download : " + ex); // nothing can really be done if the file can't be closed } if (filename != null) { // if the download wasn't successful, delete the file if (GlobalDownload.isStatusError(finalStatus)) { new File(filename).delete(); filename = null; } else if (GlobalDownload.isStatusSuccess(finalStatus)) { // make sure the file is readable // FileUtils.setPermissions(filename, 0644, -1, -1);// // Sync to storage after completion try { new FileOutputStream(filename, true).getFD().sync(); } catch (FileNotFoundException ex) { //#debug warn base.tina.core.log.LogPrinter.w(Constants.TAG, "file " + filename + " not found: " + ex); } catch (SyncFailedException ex) { //#debug warn base.tina.core.log.LogPrinter.w(Constants.TAG, "file " + filename + " sync failed: " + ex); } catch (IOException ex) { //#debug warn base.tina.core.log.LogPrinter.w(Constants.TAG, "IOException trying to sync " + filename + ": " + ex); } catch (RuntimeException ex) { //#debug warn base.tina.core.log.LogPrinter.w(Constants.TAG, "exception while syncing file: ", ex); } } } notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, gotData, filename, newUri, mimeType); } }
From source file:com.z3r0byte.magistify.Services.BackgroundService.java
@SuppressLint("InvalidWakeLockTag") @Override//from w w w . j a v a 2 s . c o m public void onReceive(final Context context, Intent intent) { PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(15 * 1000); //Bundle extras = intent.getExtras(); mGson = new Gson(); calendarDB = new CalendarDB(context); scheduleChangeDB = new ScheduleChangeDB(context); gradesdb = new NewGradesDB(context); homeworkDB = new HomeworkDB(context); this.context = context; configUtil = new ConfigUtil(context); final User user = mGson.fromJson(configUtil.getString("User"), User.class); final School school = mGson.fromJson(configUtil.getString("School"), School.class); new Thread(new Runnable() { @Override public void run() { try { manageSession(user, school); if (configUtil.getBoolean("silent_enabled") || configUtil.getBoolean("appointment_enabled") || configUtil.getBoolean("new_homework_notification")) { getAppointments(); } if (configUtil.getBoolean("appointment_enabled")) { appointmentNotification(); } if (configUtil.getBoolean("silent_enabled")) { autoSilent(); } if (configUtil.getBoolean("new_grade_enabled")) { newGradeNotification(); } if (configUtil.getBoolean("notificationOnNewChanges")) { newScheduleChangeNotification(); } if (configUtil.getBoolean("notificationOnChangedLesson")) { nextAppointmentChangedNotification(); } if (configUtil.getBoolean("unfinished_homework_notification")) { unFinishedHomeworkNotification(); } if (configUtil.getBoolean("new_homework_notification")) { newHomeworkNotification(); } } catch (Exception e) { e.printStackTrace(); } finally { Log.d(TAG, "onReceive: Cleaning up and releasing wakelock!"); if (wakeLock.isHeld()) wakeLock.release(); calendarDB.close(); scheduleChangeDB.close(); gradesdb.close(); } } }).start(); }