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

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -