1
我的目標是建立一個Android應用程序,記錄設備WiFi適配器正在進行的一切。例如,WiFi開啓/關閉,設備連接/移出WiFi路由器的範圍等。 我的應用應該能夠在設備開啓後立即記錄這些事件。從RECENTS清除應用程序不應該影響應用程序記錄這些事件的能力。 我已經通過BroadcastReceiver。它被綁定到應用程序的生命週期,因此一旦從RECENTS中清除應用程序就不會記錄事件。獲取有關Android設備上WiFi狀態更改的通知?
public class MainActivity extends Activity {
BroadcastReceiver mybroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mybroadcastReceiver = new WifiBroadcastReceiver(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(mybroadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mybroadcastReceiver);
}
}
public class WifiBroadcastReceiver extends BroadcastReceiver {
final String TAG = "WifiBroadcastReceiver";
final String desiredMacAddress = "02:17:1c:96:42:fa";
Activity activity;
WifiBroadcastReceiver(Activity activity) {
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state) && state == SupplicantState.COMPLETED)
checkConnectedToDesiredWifi();
}
}
/** Detect you are connected to a specific network. */
private void checkConnectedToDesiredWifi() {
WifiManager myWifiManager = (WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = myWifiManager.getConnectionInfo();
if (wifiInfo != null) {
// get current router MAC address
String bssid = wifiInfo.getBSSID();
if (desiredMacAddress.equals(bssid))
Log.d(TAG, "Connected to " + bssid + " i.e., desiredMacAddress");
else
Log.d(TAG, "Connected to " + bssid + " not " + desiredMacAddress);
}
}
}
即使我在網絡狀態更改期間強制關閉或終止應用程序,這是否會喚醒應用程序? @charlie – Sp4Rx
這應該允許您的應用程序在BroadcastReceiver中的Intent()的onReceive()被喚醒,即使所有活動都關閉了。例如,如果你選擇了,你可以開始一個活動onReceive ..因此模仿應用程序「醒來」 – Charlie