Problem:
I am trying to write an app that executes some code when the phone is plugged into a power source which is determined to be a PC, as opposed to an AC port. I also want this app to have a gui interface which the user can “force” start that same code.
I have 2 classes so far: one is the main activity and the other one is a class that extends BroadcastReceiver.
Code is below:
MainActivity.java
public class MainActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void func1(View view){ //stuff }
public void func2(View view){ //stuff }
}
ChargingOnReceiver.java
public class ChargingOnReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
CharSequence text = "Plug status = " + isUSBConnected(context);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public static boolean isUSBConnected(Context context){
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return plugged == BatteryManager.BATTERY_PLUGGED_USB;
}
}
AndroidManifest.xml
<receiver android:name=".ChargingOnReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
</intent-filter>
</receiver>
Side Question:
So a quick first question: How can I call methods in MainActivity from ChargingOnReceiver (e.g. func1 or fucn2)? For example, my isUSBConnected() function used to be in MainActivity but I couldn’t find a way to call it from ChargingOnReceiver so I moved it to ChargingOnReceiver.
Main Question:
The code errors out with:
*FATAL EXCEPTION: main:: java.lang.RuntimeException: Unable to start receiver com.example.ChargingOnReceiver: android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents
*
I kind of understand why it is erroring out, as I’m trying to register a receiver within a receiver, but could someone point me in the direction of how I would be able to do this correctly?
Instead of:
use:
This is annoying —
registerReceiver()should be smarter than this — but it’s the workaround for this particular case.