我想在连接WiFi时自行复制状态栏的行为。
我已经注册了接收器,但是我不知道我想听什么确切的动作才能检测到我是否已连接到WiFi AP,但是它没有Internet连接(热点断开)。 / p>
我正在尝试:
typealias IdResponseBlock = (_ swiftObj: Any?, _ error: Error?) -> Void
class RestClient: NSObject {
static let shared = RestClient()
// Additional class where sending and receiving information from the server occurs
private var http = HttpService()
let baseUrl = ApiSettings.shared.kServerBaseURL
override init() {
super.init()
}
func parseData<P: BaseMappable>(object: Any, modelCls: P.Type, response: (IdResponseBlock)) {
if object is NSArray {
let result = Mapper<P>().mapArray(JSONObject: object)
return response(result, nil)
}
if object is NSDictionary {
let model: P = Mapper<P>().map(JSONObject: object)!
return response(model, nil)
}
}
//MARK: - API
//MARK: - User
func getUserProfile(resp: @escaping IdResponseBlock) {
let url = baseUrl + Requests.profile
http.queryBy(url, method: .get, queue: .background, resp: { (response, error) in
if let err = error {
return resp(nil, err)
}
guard let data = response else {
return resp(nil, error)
}
let jsonData = JSON(data)["data"]
self.parseData(object: jsonData.rawValue,
modelCls: UserProfile.self,
response: resp)
})
}
}
但是当我连接到与网络断开连接的热点时,并没有获得任何有价值的信息。
我希望能够在连接到WiFi AP但没有互联网连接时自行检测并显示感叹号。
我有使用#include <stdio.h>
#include <string.h>
char* split( char* s, char* delim ) {
char* needle = strstr(s, delim);
if (!needle)
return NULL;
needle[0] = 0;
return needle + strlen(delim);
}
int main() {
char s[] = "Fluffy furry Bunnies!";
char* res = split(s, "furry ");
printf("%s%s\n", s, res );
}
操作向接收者注册的特定操作吗?
答案 0 :(得分:0)
我可能会在这里使用这种方法!
public boolean isOnline() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) { return false; }
}
答案 1 :(得分:-1)
首先,您必须创建BroadcastReceiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
isInternetAvailable();
}
private boolean isInternetAvailable() {
try {
return (Runtime.getRuntime().exec("ping -c 1 google.com").waitFor() == 0);
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
}
然后您必须在Manifest中注册:
<receiver android:name=".NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
最后,您必须在主应用程序中注册:
public class MainApplication extends MultiDexApplication {
@Override
public void onCreate() {
NetworkChangeReceiver myReceiver = new NetworkChangeReceiver();
registerReceiver(myReceiver, filter);
}
}
因此,现在每次您连接到WIFI时,您都将收到广播,而从isInternetAvailable()您将知道是否连接到互联网。
别忘了权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />