我正在尝试制作一个应用程序,当切换按钮打开时会启动一个广播,检查电池电量是否不足并禁用 wifi。相反,当切换关闭时会启动另一个广播并启动 wifi。问题是当我按下按钮时应用程序崩溃。这是切换和wifi的代码:
public void getToggle(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
PackageManager pm = getPackageManager();
ComponentName compName =
new ComponentName(getApplicationContext(),
LowBatteryReceiver.class);
pm.setComponentEnabledSetting(
compName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
} else {
PackageManager pm = getPackageManager();
ComponentName compName =
new ComponentName(getApplicationContext(),
LowBatteryReceiver.class);
pm.setComponentEnabledSetting(
compName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
//wifi enable/disable
public class LowBatteryReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
public class OkBatteryReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
}
这是清单。接收器在里面<application>
并<activity>
标记:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<application
android:allowBackup="true"
android:icon="@drawable/battery"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".MainActivity"
android:theme="@android:style/Theme.Holo.Light">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".LowBatteryReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW" />
</intent-filter>
</receiver>
<receiver
android:name=".OkBatteryReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_OKAY" />
</intent-filter>
</receiver>
<activity
android:label="@string/app_name"
android:name=".about"
android:theme="@android:style/Theme.Holo.Light">
</activity>
</application>
我该如何解决?我找不到错误.. 用 logcat 编辑: