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