在Android中,getSystemService()
方法本身并不支持超時處理。但是,您可以通過以下幾種方法來處理超時:
Handler
和Runnable
:public void getSystemServiceWithTimeout(final String serviceName, final int timeoutMillis, final SystemServiceCallback callback) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
callback.onTimeout();
}
}, timeoutMillis);
try {
Object service = getSystemService(serviceName);
callback.onSuccess(service);
} catch (Exception e) {
callback.onError(e);
}
}
public interface SystemServiceCallback {
void onSuccess(Object service);
void onTimeout();
void onError(Exception e);
}
使用示例:
getSystemServiceWithTimeout("your_service_name", 5000, new SystemServiceCallback() {
@Override
public void onSuccess(Object service) {
// 處理服務獲取成功的情況
}
@Override
public void onTimeout() {
// 處理超時的情況
}
@Override
public void onError(Exception e) {
// 處理錯誤的情況
}
});
CountDownLatch
:public void getSystemServiceWithTimeout(final String serviceName, final int timeoutMillis, final CountDownLatch latch, final SystemServiceCallback callback) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Object service = getSystemService(serviceName);
latch.countDown();
callback.onSuccess(service);
} catch (Exception e) {
latch.countDown();
callback.onError(e);
}
}
}).start();
try {
latch.await(timeoutMillis);
} catch (InterruptedException e) {
callback.onError(e);
}
}
public interface SystemServiceCallback {
void onSuccess(Object service);
void onError(Exception e);
}
使用示例:
CountDownLatch latch = new CountDownLatch(1);
getSystemServiceWithTimeout("your_service_name", 5000, latch, new SystemServiceCallback() {
@Override
public void onSuccess(Object service) {
// 處理服務獲取成功的情況
}
@Override
public void onError(Exception e) {
// 處理錯誤的情況
}
});
請注意,這些方法都是在后臺線程中執行的,因此您需要確保在主線程中更新UI。如果需要更新UI,請使用runOnUiThread()
方法。