Reputation: 477
I have BroadcastReceiver with BATTERY_CHANGED IntentFilter. When I try send broadcast, onReceive doesn't call. What's wrong? Here is my receiver description in manifest
<receiver android:name=".receivers.BatteryReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED"/>
</intent-filter>
</receiver>
My BroadcastReceiver
public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("tag", "onRecv");
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level != -1 && scale != -1) {
float batteryPct = level / (float) scale;
if (batteryPct < 30) {
NotificationBuilder.notifyWithActions(context, R.drawable.ic_info_black_24dp,
context.getResources().getString(R.string.app_name),
context.getResources().getString(R.string.battery),
context.getResources().getInteger(R.integer.battery));
}
}
}`}
I try
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Intent.ACTION_BATTERY_CHANGED));
Upvotes: 0
Views: 1282
Reputation: 462
I am trying this one of broadcast for battery level detect and it doesnt work. Then for this task i use to create broadcast in MainActivity and register it with action Intent.ACTION_BATTERY_CHANGED and there is no need to register receiver in manifest.xml and it works better.
Here whenever Battery level changed then the Broadcast call and task in block of onReceive(Context c, Intent i) is executed.
public class MainActivity extends Activity {
private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {
public void onReceive(Context c, Intent i) {
// Getting level of Battery
int level = i.getIntExtra("level", 0);
Toast.makeText(MainActivity.this,"Battery Level:" +Integer.toString(level) + "%",
Toast.LENGTH_SHORT).show();
// For any Level you have to check here.
if (level == 100) {
Toast.makeText(MainActivity.this, "Battery Full",
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Register receiver with Action and no need to define Broadcast in manifest.xml
registerReceiver(BatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
Upvotes: 3
Reputation: 11028
You can send the fake system broadcast via adb:
adb shell am broadcast "intent:#Intent;action=android.intent.action.BATTERY_CHANGED;i.status=5;i.voltage=4155;i.level=100;end"
Upvotes: 0