Android:如何在BroadcastReceiver

时间:2016-01-27 07:00:26

标签: android broadcastreceiver

当我得到ACTION_BOOT_COMPLETED意图时,我想执行一些任务,我正在使用以下代码来检查设备是否已插入但我得到方法未定义类型BootReceiver at registerReceiver。谁能找到解决方案?这就是我正在做的事。

public class BootReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {

    if(isCharging())
    doSomething();  //something to perform after boot if plugged in

        }



        public boolean isCharging() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, filter); //getting error here

    boolean strState;

    int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

    switch (chargeState) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
        case BatteryManager.BATTERY_STATUS_FULL:
            strState = true;
            break;
        default:
            strState = false;
    }
    return strState;

    }

}

1 个答案:

答案 0 :(得分:3)

致电registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED))。这将返回Intent BatteryManager,其Intent.ACTION_BATTERY_CHANGED上已定义额外内容,以告知您是否已插入。

这是有效的,因为context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));是一个粘性广播。

CommonsWare从Check if device is plugged in选择的答案

<强>更新 请致电01-27 12:35:11.787 2509-2525/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2 Process: com.example.klm.sql, PID: 2509 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection at com.example.klm.sql.Background.doInBackground(Background.java:39) at com.example.klm.sql.Background.doInBackground(Background.java:23) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)  at java.lang.Thread.run(Thread.java:818)  此方法在上下文中定义