2011-08-17 4 views
20

내가 디자인하고있는 안드로이드 응용 프로그램에서 장치가 라우터에 연결되면 (WiFi를 통해) 내 서비스 만 실행 중이어야합니다. 저는 정말 안드로이드를 처음 접했고, 지금까지 얻은 바는 저를 영원히 성취하게 만들었습니다. 그래서 나는 어떤 조언을 원합니다.Android : WiFi 상태에 따라 서비스 중지/시작 하시겠습니까?

전화가 시작되면 내 서비스가 시작되도록 설정됩니다. 또한 활동이 시작될 때 서비스가 실행 중인지 확인하고 그렇지 않으면 시작합니다. WiFi 상태가 없어지면 서비스를 끌 수있는 코드를 궁금합니다. WiFi 연결이 활성화되면 서비스를 시작하는 데 필요한 코드는 무엇입니까?

감사합니다. :)

답변

26

와이파이 연결 변경을 처리하는 BroadcastReceiver을 만들 수 있습니다.

public class NetWatcher extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     //here, check that the network connection is available. If yes, start your service. If not, stop your service. 
     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo info = cm.getActiveNetworkInfo(); 
     if (info != null) { 
      if (info.isConnected()) { 
       //start service 
       Intent intent = new Intent(context, MyService.class); 
       context.startService(intent); 
      } 
      else { 
       //stop service 
       Intent intent = new Intent(context, MyService.class); 
       context.stopService(intent); 
      } 
     } 
    } 
} 

(서비스의 이름 MyService 변경) : -

더 정확히 말하면, 당신은 클래스를 만들 것이다 NetWatcher 말. 당신의 AndroidManifest에서 또한

는 다음과 같은 줄을 추가해야합니다

<receiver android:name="com.example.android.NetWatcher"> 
    <intent-filter> 
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> 
    </intent-filter> 
</receiver> 

(패키지의 이름으로 com.example.android 변경).

+2

감사합니다! 이것은 나의 해결책의 기초였다. NetWatcher 클래스는 필자가 필요로하는 것이 었습니다. 그러나이 솔루션은 모바일 데이터 연결이 켜져 있으면 true를 반환합니다 (Wi-Fi가 활성 상태 일 때만 모바일 데이터가 실행되어야합니다). 솔루션 : WifiManager wifiManager = (WifiManager) this.getSystemService (Context.WIFI_SERVICE); if (wifiManager.{ // 서비스 시작 } else { // 중지 서비스 } –

+0

'Intent intent = new 인 텐트 (context, MyService.class);''this'를 인 텐트의 인자로 사용하기 생성자가'BroadcastReceiver' 내부에서 유효하지 않습니다. 또한'context.startService (intent)'여야합니다. – faizal

+0

클린업 제안에 대해 @faizal에게 감사드립니다. 이 게시물을 편집하여 포함했습니다. – Phil

7

@Phil은 BroadcastReceiver를 확장하고 onReceive 메서드에서 서비스를 시작하거나 중지해야한다고 명시했습니다. 다음과 같이하십시오 :

활동의 비공개 클래스로 만들고 활동 작성자에 수신자를 등록하고 활동 삭제시 등록을 등록 해제 할 수 있습니다.

1

시작하려면/요청자 와이파이 상태 확인/NOK 경우 서비스를 중지

  • 당신의 브로드 캐스트 리시버 내부
  • 는 다음 서비스를 시작 의도 유효성을 검사 WIFI 상태 변경 방송 의도를받을 수있는 브로드 캐스트 리시버를 등록

방송 수신기를 등록하여 WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION을 수신하십시오. 허가 android.permission.CHANGE_WIFI_STATE 또는 android.permission.ACCESS_NETWORK_STATE을 추가하십시오. 필요한지 아닌지 잘 모르겠습니다.

그런 다음 샘플 방송 수신기 코드 수 :

public class MyWifiStatereceiver extends BroadcastReceiver { 
    //Other stuff here 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent srvIntent = new Intent(); 
     srvIntent.setClass(MyService.class); 
     boolean bWifiStateOk = false; 

     if (WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION.equals(intent.getAction()) { 
      //check intents and service to know if all is ok then set bWifiStateOk accordingly 
      bWifiStateOk = ... 
     } else { 
      return ; // do nothing ... we're not in good intent context doh ! 
     } 

     if (bWifiStateOk) { 
      context.startService(srvIntent); 
     } else { 
      context.stopService(srvIntent); 
     } 
    } 

} 
관련 문제