android - communication between activity and broadcast receiver -
i have broad cast receiver needs access data stored in shared preferences of mainactivity.java activity of same package.
is code valid if written in onreceive() method of broadcast receiver?
string s ; mainactivity g =new mainactivity(); s = g.getsharedpreferences(context.mode_private).getstring("key","no key");
no, trying instantiate activity via constructor. never - activities have special initialization steps allow them become proper activities (and result contexts).
the context class (which broadcastreceiver receives instance of via onreceive() method) the class contains methods such getsharedpreferences().
use instead.
public class myreceiver extends broadcastreceiver { @override public void onreceive (context context, intent intent){ string s = context.getsharedpreferences("shared_prefs_name",context.mode_private).getstring("key","def_value"); } }
Comments
Post a Comment