如何在使用Xamarin开发安卓应用时,利用C#的async/await实现回调?与安卓标准Java编程相比,这有何不同?
如何在使用Xamarin开发安卓应用时,利用C#的async/await实现回调?与安卓标准Java编程相比,这有何不同?
public class VoiceSelector extends Activity {
private TextToSpeech myTts;
private int myEngineIndex; // loop counter when initializing TTS engines
// Called from onCreate to colled all languages and voices from all TTS engines, initialize the spinners
private void getEnginesAndLangs() {
myTts = new TextToSpeech(AndyUtil.getAppContext(), null);
List<EngineInfo> engines;
engines = myTts.getEngines(); // at least we can get the list of engines without initializing myTts object…
try { myTts.shutdown(); } catch (Exception e) {};
myTts = null;
myEngineIndex = 0; // Initialize the loop iterating through all TTS engines
if (engines.size() > 0) {
for (EngineInfo ei : engines)
allEngines.add(new EngLang(ei));
myTts = new TextToSpeech(AndyUtil.getAppContext(), ttsInit, allEngines.get(myEngineIndex).name());
// DISRUPTION 1: we can’t continue here, must wait until ttsInit callback returns, see below
}
}
private TextToSpeech.OnInitListener ttsInit = new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (myEngineIndex < allEngines.size()) {
if (status == TextToSpeech.SUCCESS) {
// Ask a TTS engine which voices it currently has installed
EngLang el = allEngines.get(myEngineIndex);
Intent in = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
in = in.setPackage(el.ei.name); // set engine package name
try {
startActivityForResult(in, LANG_REQUEST); // goes to onActivityResult()
// DISRUPTION 2: we can’t continue here, must wait for onActivityResult()…
} catch (Exception e) { // ActivityNotFoundException, also got SecurityException from com.turboled
if (myTts != null) try {
myTts.shutdown();
} catch (Exception ee) {}
if (++myEngineIndex < allEngines.size()) {
// If our loop was not finished and exception happened with one engine,
// we need this call here to continue looping…
myTts = new TextToSpeech(AndyUtil.getAppContext(), ttsInit, allEngines.get(myEngineIndex).name());
} else {
completeSetup();
}
}
}
} else
completeSetup();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == LANG_REQUEST) {
// We return here after sending ACTION_CHECK_TTS_DATA intent to a TTS engine
// Get a list of voices supported by the given TTS engine
if (data != null) {
ArrayList<String> voices = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
// … do something with this list to save it for later use
}
if (myTts != null) try {
myTts.shutdown();
} catch (Exception e) {}
if (++myEngineIndex < allEngines.size()) {
// and now, continue looping through engines list…
myTts = new TextToSpeech(AndyUtil.getAppContext(), ttsInit, allEngines.get(myEngineIndex).name());
} else {
completeSetup();
}
}
}
// Base class for an activity to create an initialized TextToSpeech
// object asynchronously, and starting intents for result asynchronously,
// awaiting their result. Could be used for other purposes too, remove TTS
// stuff if you only need StartActivityForResultAsync(), or add other
// async operations in a similar manner.
public class TtsAsyncActivity : Activity, TextToSpeech.IOnInitListener
{
protected const String TAG = "TtsSetup";
private int _requestWanted = 0;
private TaskCompletionSource<Java.Lang.Object> _tcs;
// Creates TTS object and waits until it's initialized. Returns initialized object,
// or null if error.
protected async Task<TextToSpeech> CreateTtsAsync(Context context, String engName)
{
_tcs = new TaskCompletionSource<Java.Lang.Object>();
var tts = new TextToSpeech(context, this, engName);
if ((int)await _tcs.Task != (int)OperationResult.Success)
{
Log.Debug(TAG, "Engine: " + engName + " failed to initialize.");
tts = null;
}
_tcs = null;
return tts;
}
// Starts activity for results and waits for this result. Calling function may
// inspect _lastData private member to get this result, or null if any error.
// For sure, it could be written better to avoid class-wide _lastData member...
protected async Task<Intent> StartActivityForResultAsync(Intent intent, int requestCode)
{
Intent data = null;
try
{
_tcs = new TaskCompletionSource<Java.Lang.Object>();
_requestWanted = requestCode;
StartActivityForResult(intent, requestCode);
// possible exceptions: ActivityNotFoundException, also got SecurityException from com.turboled
data = (Intent) await _tcs.Task;
}
catch (Exception e)
{
Log.Debug(TAG, "StartActivityForResult() exception: " + e);
}
_tcs = null;
return data;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == _requestWanted)
{
_tcs.SetResult(data);
}
}
void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
{
Log.Debug(TAG, "OnInit() status = " + status);
_tcs.SetResult(new Java.Lang.Integer((int)status));
}
}
// Method of public class TestVoiceAsync : TtsAsyncActivity
private async void GetEnginesAndLangsAsync()
{
_tts = new TextToSpeech(this, null);
IList<TextToSpeech.EngineInfo> engines = _tts.Engines;
try
{
_tts.Shutdown();
}
catch { /* don't care */ }
foreach (TextToSpeech.EngineInfo ei in engines)
{
Log.Debug(TAG, "Trying to create TTS Engine: " + ei.Name);
_tts = await CreateTtsAsync(this, ei.Name);
// DISRUPTION 1 from Java code eliminated, we simply await TTS engine initialization here.
if (_tts != null)
{
var el = new EngLang(ei);
_allEngines.Add(el);
Log.Debug(TAG, "Engine: " + ei.Name + " initialized correctly.");
var intent = new Intent(TextToSpeech.Engine.ActionCheckTtsData);
intent = intent.SetPackage(el.Ei.Name);
Intent data = await StartActivityForResultAsync(intent, LANG_REQUEST);
// DISTRUPTION 2 from Java code eliminated, we simply await until the result returns.
try
{
// don't care if lastData or voices comes out null, just catch exception and continue
IList<String> voices = data.GetStringArrayListExtra(TextToSpeech.Engine.ExtraAvailableVoices);
Log.Debug(TAG, "Listing voices for " + el.Name() + " (" + el.Label() + "):");
foreach (String s in voices)
{
el.AddVoice(s);
Log.Debug(TAG, "- " + s);
}
}
catch (Exception e)
{
Log.Debug(TAG, "Engine " + el.Name() + " listing voices exception: " + e);
}
try
{
_tts.Shutdown();
}
catch { /* don't care */ }
_tts = null;
}
}
// At this point we have all the data needed to initialize our language
// and voice selector spinners, can complete the activity setup.
...
}
https://github.com/gregko/TtsSetup_C_sharp
https://github.com/gregko/TtsSetup_Java
使用Xamarin为Android免费试用版学习这个很有趣,但是购买Xamarin许可证是否值得花费这笔钱,以及每次创建Google Play Store的APK文件时额外增加约5MB的Mono运行时包的负担,这是否值得呢?我希望Google能够提供Mono虚拟机作为标准系统组件,并与Java/Dalvik享有平等的权利。
P.S. 我看到这篇文章的投票结果,发现它也收到了一些反对票。猜想这些反对票可能来自Java爱好者! :) 同时,欢迎提出改进我的Java代码的建议。
P.S. 2 - 在Google+上与另一位开发人员交流了这段代码, 这帮助我更好地理解了async/await的实际情况。
var data = await webClient
.DownloadDataTaskAsync(myImageUrl)
.ConfigureAwait(this);
.configureAwait(this)扩展方法(再加上在activity OnCreate()方法中设置的一行代码),确保当您从await返回时,即使发生配置更改,'this'对象仍然有效,指向当前活动实例。我认为,在开始使用Android UI代码的async/await时,了解这种困难至少是有益的,有关更多信息,请参见Dot42博客上的文章:http://blog.dot42.com/2013/08/how-we-implemented-asyncawait.html?showComment=1377758029972#c6022797613553604525
我经历的async/await崩溃现在已在Dot42中修复,并且它表现出色。实际上,由于Dot42在活动销毁/重建周期之间智能处理'this'对象,因此比Xamarin代码更好。我的所有C#代码都应更新以考虑这样的周期,目前只有Dot42可以做到这一点,而Xamarin则不行。我将根据其他SO成员的要求更新该代码,但目前似乎这篇文章并没有得到太多关注。
SemaphoreSlim ss = new SemaphoreSlim(0);
int result = -1;
public async Task Method() {
MethodWhichResultsInCallBack()
await ss.WaitAsync(10000); // Timeout prevents deadlock on failed cb
lock(ss) {
// do something with result
}
}
public void CallBack(int _result) {
lock(ss) {
result = _result;
ss.Release();
}
}
这非常灵活,可以在活动中使用,在回调对象内等等。
请注意,错误使用会创建死锁等问题。锁定可防止超时后结果更改。
await Task.Run(delegate { Event1.WaitOne(); });
)我认为这真的很丑陋。更好的解决方案是使用TaskCompletionSource
。而且所有那些空的catch
也不是一个好习惯。 - svickawait
等待该任务。与设置自动重置事件不同的是,你只需设置TCS的结果即可。这就是svick建议的方法。这是使用“Task”模型进行信号传递的适当方式。使用自动重置事件是为了非异步阻塞。 - Servy