Получить состояние датчиков устройства методом ловушки - PullRequest
0 голосов
/ 30 мая 2018

В моем приложении я пытаюсь изменить функциональность некоторых классов в зависимости от информации, получаемой от различных аппаратных частей устройства (например, уровень заряда батареи или если батарея заряжается прямо сейчас, местоположение пользователя и т. Д.).Я пытаюсь это сделать, но я получаю NullPointerException, когда создаю свой IntentFilter.Мой код (пытается прочитать состояние батареи):

Context context = (Context) AndroidAppHelper.currentApplication();
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || 
        status == BatteryManager.BATTERY_STATUS_FULL;

Есть ли способ сделать это?

Ответы [ 2 ]

0 голосов
/ 30 мая 2018

Попробуйте использовать приведенный ниже код.Надеюсь, это поможет вам.

Вот ссылка !

 findAndHookMethod("com.android.systemui.statusbar.policy.BatteryController", lpParam.classLoader, "onReceive", Context.class, Intent.class, new XC_MethodHook() { 
        @Override 
        protected void afterHookedMethod(MethodHookParam param) throws Throwable { 
         try { 
          Intent pi = (Intent) param.args[1]; 
          int status = pi.getIntExtra("status", 1); 
          int blevel = pi.getIntExtra("level", 0); 
          @SuppressWarnings("unchecked") 
          int j = ((ArrayList<ImageView>) getObjectField(param.thisObject, "mIconViews")).size(); 
          for (int k = 0; k < j; k++) { 
           @SuppressWarnings("unchecked") 
           ImageView iv = ((ArrayList<ImageView>) getObjectField(param.thisObject, "mIconViews")).get(k); 
           if (status == 2 && blevel < 100) { 
            AnimationDrawable animation = new AnimationDrawable(); 
            for (int i = 0; i < filearray.size(); i++) { 
             String cbimg = "battery/charge/" + filearray.get(i); 
    //         Log.d("XSBM", "Req charge img: " + cbimg); 
             final Bitmap cb = ZipStuff.getBitmap(path, cbimg, 240); 
             Drawable cd = new BitmapDrawable(null, cb); 
             animation.addFrame(cd, paramPrefs.getInt("charge_delay", 350)); 
            } 
            if (paramPrefs.getBoolean("altcharge", false)) { 
             String bimg = "battery/" + battarray[blevel]; 
             final Bitmap b = ZipStuff.getBitmap(path, bimg, 240); 
             Drawable bd = new BitmapDrawable(null, b); 
             animation.addFrame(bd, 500); 
            }  
            animation.setOneShot(false); 
            iv.setImageDrawable(animation); 
            animation.start(); 
           } else if (status == 2 && blevel >= 100) { 
            String bimg = "battery/" + battarray[100]; 
            final Bitmap b = ZipStuff.getBitmap(path, bimg, 240); 
            Drawable d = new BitmapDrawable(null, b); 
            iv.setImageDrawable(d); 
           } else {  
            String bimg = "battery/" + battarray[blevel]; 
            final Bitmap b = ZipStuff.getBitmap(path, bimg, 240); 
            Drawable d = new BitmapDrawable(null, b); 
            iv.setImageDrawable(d); 
           } 
          } 
         } catch (Throwable t) { XposedBridge.log(t); } 
        } 

       });  
      } 
0 голосов
/ 30 мая 2018

Попробуйте следующий код, чтобы получить состояние батареи

public class Main extends Activity {
  private TextView batteryTxt;
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
      batteryTxt.setText(String.valueOf(level) + "%");
    }
  };

  @Override
  public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);
    batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...