Thursday, 31 January 2013

Kiểm tra kết nối mạng của Android

- Trong android có 2 kiểu kết nối mạng là wifi và 3g or 4g...
- Tôi sẽ viết 1 class để bắt sự kiện on/off mạng...( khi mạng thay đổi trạng thái thì sẽ tự bắt được. bla bla..)
- Bài viết được tham khảo từ http://stackoverflow.com/questions/7094606/android-stop-start-service-depending-on-wifi-state

- Tạo class như sau:

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(this, MyService.class);
               startService(intent);
           }
           else {
               //stop service
               Intent intent = new Intent(this, MyService.class);
               stopService(intent);
           }
       }
    }
}
-Trong AndroidManifest bạn thêm mấy dòng sau vào 
 
<receiver android:name="com.example.android.NetWatcher">
     <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
     </intent-filter>
</receiver>
// chú ý đổi tên package trong android:name phù hợp với project của bạn



0 comments:

Post a Comment