问题
I want to pass the context of the main activity to another class in order to create a Toast.
My main activity calls a class that will delete a file. The class that deletes files will call a toast if the file does not exist.
Here is my code:
public class MyActivity extends AppCompatActivity
{
public void onCreate(Bundle savedInstanceState)
{
// create a file
Button buttoncreate = (Button)findViewById(R.id.create_button);
Button buttondelete = (Button)findViewById(R.id.delete_button);
...
buttondelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DeleteFile();
}
});
}
public class DeleteFile extends AsyncTask {
@Override
public Object doInBackground(Object[] params) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/mydir");
if (!(dir.exists())) {
CharSequence text = "Files do not exist!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
} else {
File file;
file = new File(dir, "mydata.bmp");
file.delete();
}
return(1);
}
}
回答1:
First thing, you need Static Variable to declare global variable in Application Class,
like this
class GlobalClass extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
second you need set this class in AndroidManifest.xml inside application tag
like this:
<application
android:name=".GlobalClass"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar" >
then whereever you need to access this data, get Application object by:
Toast toast = Toast.makeText(GlobalClass.context, text, duration);
toast.show();
来源:https://stackoverflow.com/questions/40892448/how-to-pass-context