Приемник широковещания не регистрируется с помощью onResume (), а onPause () - - PullRequest
1 голос
/ 19 марта 2019

Я пытаюсь отобразить состояние:

заряд аккумулятора (t / f) заряд USB (t / f) заряд аккумулятора переменного тока (t / f) уровень заряда аккумулятора (в процентах)

после изменения подключения зарядного устройства в расширенном управлении.

В onResume () состояния приемника вещания

Не удается разрешить метод 'registerReceiver (android.content.BroadcastReceiver)

Регистрируется в onPause () без проблем.Спасибо за вашу помощь, это кажется сложным вопросом для решения.

MainActivity:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    BroadcastReceiver broadcastReceiver;
    StringBuilder stringBuilder;
    public MyReciever myReciever= new MyReciever();
    Intent intent;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                myReciever.onReceive(MainActivity.this, intent);
                StringBuilder stringBuilder = new StringBuilder();

                IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                intent = registerReceiver(null, ifilter);
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||status == BatteryManager.BATTERY_STATUS_FULL;
                int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
                boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                float batteryPct = level / (float)scale;

                stringBuilder.append(String.valueOf(isCharging));
                stringBuilder.append(String.valueOf(usbCharge));
                stringBuilder.append(String.valueOf(acCharge));
                stringBuilder.append(String.valueOf(batteryPct));

                String str = stringBuilder.toString();
                TextView display = (TextView)findViewById(R.id.results);
                display.setText(str);

            }
        };
    }
///Not Registering here
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver);
    }

    @Override
   protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }
}

MyReceiver:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReciever extends BroadcastReceiver {
    @Override

            public void onReceive(Context context, Intent intent) {

                Intent newintent = new Intent(context.getApplicationContext(), MainActivity.class);
                newintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(newintent);



            }
        }

activity_main.XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/results"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Ответы [ 2 ]

0 голосов
/ 19 марта 2019

попробуйте

@Override
protected void onResume() {
    registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    super.onResume();
}

Для получения дополнительной информации, пожалуйста, обратитесь https://developer.android.com/training/monitoring-device-state/battery-monitoring.html

0 голосов
/ 19 марта 2019

Ваша проблема в том, что метод registerReciever принимает 2 аргумента, а не 1.

Эти аргументы

  1. Приемник широковещания для регистрации
  2. НамерениеФильтр

Поскольку вы предоставляете только первый аргумент, метод не найден, и нет версии метода (перегруженного метода), которая принимает только один аргумент.

Итакчтобы исправить это, вам нужно вызвать метод следующим образом:

protected void onResume() {
    registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    super.onResume();
}

Документация по созданию IntentFilter доступна здесь https://developer.android.com/reference/android/content/IntentFilter.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...