android - access to activity from a broadcast receiver class -
i want protect features behind device password. if users try use feature, have confirm password again.
this code in activity class.
context appcontext = activity.getapplicationcontext(); restrictionsmanager rmanager = (restrictionsmanager) appcontext.getsystemservice(appcontext.restrictions_service); rmanager.requestpermission(restrictionsmanager.action_request_permission, "someid", new persistablebundle());
this code handle response password-confirmation dialog in permissionresponsereceiver class.
public class permissionresponsereceiver extends broadcastreceiver { @override public void onreceive(final context context, intent intent) { ...... } }
is there simple way reference original activity in permissionresponsereceiver.onreceive(...). have keep track of activity instance , provide public static method it, seems hacky , i'm looking alternative. have suggestions? thanks.
use local broadcast communicate between permissionresponsereceiver
, activity
.
in permissionresponsereceiver
:
public class permissionresponsereceiver extends broadcastreceiver { @override public void onreceive(final context context, intent intent) { ...... // create intent broadcast intent intent = new intent("my-permission-response-action"); // add data want put in intent here.. // broadcast registered receivers localbroadcastmanager.getinstance(context).sendbroadcast(intent); } }
in activity
:
@override public void onresume() { super.onresume(); final localbroadcastmanager localbroadcastmanager = localbroadcastmanager.getinstance(this); // intentfilter define actions mlocalbroadcastreceiver respond intentfilter intentfilter = new intentfilter(); intentfilter.addaction("my-permission-response-action"); // register desired broadcasts localbroadcastmanager.registerreceiver(mlocalbroadcastreceiver, intentfilter); } @override public void onpause() { // unregister our mlocalbroadcastreceiver localbroadcastmanager.getinstance(this).unregisterreceiver(mlocalbroadcastreceiver); super.onpause(); } /** * local broadcast receiver */ private broadcastreceiver mlocalbroadcastreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(my-permission-response-action)) { // our activity has received broadcast permissionresponsereceiver. // if added extras intent can extract them here // use in activity } } };
Comments
Post a Comment