简体   繁体   中英

Android: Passing a variable to a non-activity class

I am trying to pass a String from my MainActivity to a non-activity class (A Notification Service) So that I can customise the notification message. I have tried using Intent however it won't work because it is a non-activity based class. What is the best why to do this?

I am currently trying to use a global variable but its not working.

MainActivity.java

private String var;
private String a = "Pumpkin";

public String getVar(){
    return var;
}
public void setVar(String a){
    var = a;
}

NotificationService.java

  MainActivity b = ((MainActivity)getApplicationContext());
  String var = b.getVar();

This crashes the app when even I call the variable var in NotificationService.java

1.You can try by making static variable, and call with Class refenrence in any where.

 public static  String a = "Pumpkin";//Declare in MainActivity
 Use it: String var = MainActivity.a;

2. Pass in Intent as extras and then get extras in where intent recived.

  startActivity(new Intent(MainActivity.this, PropertyListviewActivity.class).putExtra("Key", "Value"));

Recive :

 if (intent != null)
        if (intent.getExtras() != null)
            if (intent.getExtras().getString("Key") != null) {
                String recivedString= intent.getExtras().getString("Key");

3.Keep in Shared Preferences and retrive where ever you want(not good practise).

4.If Not an Android Component class try pass in Contractor.

尝试活动巴士绿色机器人奥托活动巴士都是很好的选择。

You are trying to cast app Context to Activity. It crashes, cause app context is not an activity. You should use handleIntent or binder in your service to transport data. http://developer.android.com/guide/components/bound-services.html#Basics

you can do this task by saving data to application level variable or save it in sharedpreference.

To save data in application level make a static variable like

public static DatatypeYouDesire(String/int) cachedData;

now when you want to store data jst initialize this varaible with the data you want to store like

YourApplictionClass.cachedData = "your data to be stored";

similarly you can use this data by accesing YourApplicationClass.cacheData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM