[英]What is the Context in this matter?
我正在努力在調用此函數中找到“上下文”值,例如
SetFile("Name", ???, 1, "Some text here")
我在這里查看過https://developer.android.com/reference/android/content/Context,但似乎有很多可能性,但我不清楚我應該使用哪種方法以及如何使用。 我不知道該填寫什么? 地方,有人可以幫我嗎?
public void SetFile(string BroadCastName, Context Context, long? DirectoryId, string BaseContent)
{
if (!BroadCastName.Contains(".enc"))
BroadCastName = BroadCastName + ".enc";
if (DirectoryId == null)
DirectoryId = 2;
var File = Directories.Where(x => x.Id == DirectoryId).FirstOrDefault().File;
var Path = Directories.Where(x => x.Id == DirectoryId).FirstOrDefault().Path;
File FilesDir = new File(Path, "SDDnode");
FilesDir.Mkdir();
if (bool.Equals(FilesDir.CanWrite(), true)) {
File newFile = new File(FilesDir, BroadCastName);
try
{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Context.OpenFileOutput(BroadCastName, FileCreationMode.Private));
outputStreamWriter.Write(BaseContent);
outputStreamWriter.Flush();
outputStreamWriter.Close();
}
catch (IOException e)
{
#region
ledger._base.Errors.Add(new Error {
Message = "Something went wrong in generate file in Android",
Process = "sddnode_android.Base._system",
Sys_Message = e.Message,
Line = 115,
Priority = 1
});
#endregion
}
OutputStream os;
try
{
os = new FileOutputStream(newFile);
//target.compress(CompressFormat.PNG, 100, os);
os.Flush();
os.Close();
}
catch (FileNotFoundException e)
{
e.PrintStackTrace();
}
catch (IOException e)
{
e.PrintStackTrace();
}
}
對於那段代碼,實際上沒有辦法找出Context的來源,因為我們不知道它叫什么。
但是,由於它是方法的類型,盡管服務也是可能的,但最高的可能性是活動上下文。
但是,這並不重要,因為在該方法中唯一使用Context的是Context.OpenFileOutput(BroadCastName, FileCreationMode.Private)
並且可以通過任何位置的上下文安全地完成此操作。
編輯:
要獲取上下文,您可以簡單地在Activity或Service中使用this
關鍵字。
因此,無論您想在哪里運行該方法,都只需調用SetFile("test", MainActivity.this, 2, "");
將MainActivity替換為您在其中使用的Activity或Service的類名。
如果要在活動或服務之外的其他地方使用它,請檢查該組件是否具有getContext()
方法。
您可以使用獲取應用程序上下文
var currentContext = Android.App.Application.Context;
然后使用它傳遞setFile
方法。 喜歡,
SetFile("Name",currentContext, 1, "Some text here")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.