Reputation: 54212
I store the Sender ID of Google Cloud Messaging (GCM) in a properties file stored in asset folder. I want to grab the Sender ID before calling GCMIntentService
's parent constructor ( GCMBaseIntentService
's constructor ). My current solution is:
In my default Activity, named InitActivity
:
public class InitActivity extends Activity {
public static Context appContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appContext = getApplicationContext();
// ...
In my GCMIntentService
:
public GCMIntentService() {
super(GCMIntentService.getSenderID());
Log.d(TAG, "GCMIntentService SenderID : " + GCMIntentService.getSenderID());
}
private static String getSenderID() {
Resources resources = InitActivity.appContext.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("config.properties");
Properties properties = new Properties();
properties.load(inputStream);
return properties.getProperty("SENDER_ID");
} catch (IOException e) {
System.err.println("Failed to open property file");
e.printStackTrace();
return null;
}
}
My questions are :
Is it okay to save Context in static way ( will it consume memory a lot, or will it lead to memory leak ) ? Reference question .
Is there a better way to fetch Sender ID from properties file ?
Is it a wise choice to put the code in Activity ?
Upvotes: 0
Views: 740
Reputation: 10242
I would recommend that you don't save a context somewhere unless you are absolutely sure that you don't save a reference to it somewhere. There's a considerate risk that you might end up leaking a context.
Loading the Sender ID from a properties file is one way to do it, and you seem to do it the right way. You could also put it in a config file in res/values/gcm.xml:
yoursenderid
And retrieve it like any other string:
String senderid = context.getString(R.string.gcm_senderid);
Yes, I guess so, but do you really need to store a context that way? Let me suggest that you try this:
public GCMIntentService() { super(); }
@Override protected String[] getSenderIds(Context context) { AssetManager assetManager = context.getResources().getAssets();
String senderId = null;
try {
InputStream inputStream = assetManager.open("config.properties");
Properties properties = new Properties();
properties.load(inputStream);
senderId = properties.getProperty("SENDER_ID");
}
catch (IOException e) {
System.err.println("Failed to open property file");
e.printStackTrace();
}
return new String[] { senderId };
}
This uses the no argument constructor and the getSenderIds() method to provide a context specific sender id.
Upvotes: 2