와이파이 연결 변경을 처리하는 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
변경).
감사합니다! 이것은 나의 해결책의 기초였다. NetWatcher 클래스는 필자가 필요로하는 것이 었습니다. 그러나이 솔루션은 모바일 데이터 연결이 켜져 있으면 true를 반환합니다 (Wi-Fi가 활성 상태 일 때만 모바일 데이터가 실행되어야합니다). 솔루션 : WifiManager wifiManager = (WifiManager) this.getSystemService (Context.WIFI_SERVICE); if (wifiManager.{ // 서비스 시작 } else { // 중지 서비스 } –
'Intent intent = new 인 텐트 (context, MyService.class);''this'를 인 텐트의 인자로 사용하기 생성자가'BroadcastReceiver' 내부에서 유효하지 않습니다. 또한'context.startService (intent)'여야합니다. – faizal
클린업 제안에 대해 @faizal에게 감사드립니다. 이 게시물을 편집하여 포함했습니다. – Phil