0
我遇到了与我的应用程序有关的问题。我想要的是:Android应用程序结构:预定线程
MainActivity启动&创建一个调度线程,定期检查是否启用了WiFi服务。如果是,请转到新的活动。如果不是,则发起警告&将用户带到WiFi设置页面。
当用户回到主要活动时,MainActivity代码现在会感知WiFi服务已启用&将它们发送到第二个活动。
我有这个工作。这里是代码:
@Override
protected void onResume()
{
super.onResume();
ScheduledExecutorService oScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
try
{
oScheduledExecutor.scheduleAtFixedRate({RUNNABLE HERE}, 0, 5, TimeUnit.SECONDS);
}
catch (Exception e)
{
System.out.println("(MainActivity) Caught Exception here. #1");
System.out.println("(MainActivity) Error: " + e.getMessage() + " Cause: " + e.getCause());
e.printStackTrace();
}
}
@Override
protected void onStart()
{
super.onStart();
// Assign WifiManager to System service
oWiFiManager = (WifiManager) getSystemService(WIFI_SERVICE);
// Create Runnable
oWiFiUpdater = new Runnable() {
@Override
public void run()
{
// If we should show WiFi Disabled
if (shouldShowWiFiAlert())
{
runOnUiThread(new Runnable() {
@Override
public void run() {
launchWiFiDisabledAlert();
}
});
}
Intent oAPListIntent = new Intent(getApplicationContext(), APList.class);
startActivity(oAPListIntent);
}
}
};
但是,当我们在第二个活动,第一个线程仍在运行。我认为当Activity从View中移除时,所有线程都停止运行?
我希望执行程序只在活动可见时运行!有任何想法吗!?
编辑:回答感谢的灵感来自njzk2
@Override
protected void onResume()
{
super.onResume();
createWiFiAlertDialog();
boolean bWiFiEnabling = wifiEnabling();
while (bWiFiEnabling)
{
try
{
doSyncedWait(500);
}
catch (Exception e)
{
System.out.println("(MainActivity) Exception caught waiting. " + e.getMessage());
}
bWiFiEnabling = wifiEnabling();
}
boolean bWiFiEnabled = wifiReady();
if (!bWiFiEnabled)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog oAlertDialog = m_oAlertDialog;
oAlertDialog.show();
}
});
}
else
{
Intent oIntent = new Intent(this,APList.class);
startActivity(oIntent);
}
}
private boolean wifiEnabling()
{
WifiManager oWiFiManager = m_oWiFiManager;
if (oWiFiManager == null) return false;
if (oWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) return true;
return false;
}
private boolean wifiReady()
{
WifiManager oWiFiManager = m_oWiFiManager;
if (oWiFiManager == null) return false;
// If the WiFi state is anything other than enabled, then wait.
if (oWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) return true;
return false;
}
因此它会定期将用户发送到wifi设置页面?我不太明白这一点。为什么不简单地测试您的活动的onResume中的WiFi状态,并提供用户离开或根据需要转到wifi设置? – njzk2
啊辉煌!它令人惊叹的事物可以有什么不同的东西!这个事实,我是一个完整的Android新手。干杯! – user2808151