이것은 내 서비스입니다.이 서비스는 WiFi 연결을 확인합니다.
public class WiFiService extends Service {
private final static int INTERVAL = 1000 * 60 * 2;
// public Handler handler = null;
public static Runnable runnable = null;
final Handler handler = new Handler();
final long delay = 2 * 10 * 1000;
@Override
public void onCreate() {
super.onCreate();
executeSomething();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable);
Log.e("destroyed " , " kill ");
}
void executeSomething() {
handler.postDelayed(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "a" , Toast.LENGTH_LONG).show();
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String ssid = info.getSSID();
Toast.makeText(getApplicationContext(), ssid, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext() , "Nie jest właczone" , Toast.LENGTH_LONG).show();
String ssid = "AndroidAP";
String key = "iawu7483";
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
executeSomething();
}
}, delay);
}
}
이 서비스는 App extends Application 클래스에서 시작했습니다.
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, WiFiService.class));
}
}
하지만 내 응용 프로그램을 종료했을 때이 서비스가 항상 작동한다는 것을 알았습니다. 이 서비스를 어떻게 마칠 수 있습니까? 그리고 한 번 더 시작했습니다. 애플리케이션을 실행할 때
파괴 된 액티비티의 인 텐트를 서비스로 보내 종료 할 수 있습니다.
당신의 활동에서 :
@Override
void onDestroy(){
super.onDestroy();
Intent intent = new Intent(this, YourService.class);
intent.setAction("STOP");
startService(intent);
}
귀하의 서비스에서 :
@Override
void onStartCommand(Intent intent, int flag, int id){
if(intent.getAction().equals("STOP")){
stopSelf();
}
// code..
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다