3分 |
点击下载的时候判断当前的手机网络状态。另外,监听一个网络变换广播。在WIFI切换成3G的时候自动暂停下载。3G切换成WIFI的时候继续下载。
|
3分 |
简单的就是不断判断网络状态就可以了:
1.点击下载的时候判断当前的手机网络状态。 2.注册网络变换广播,或者callback。只有在wifi下才允许下载。 |
14分 |
写了一个小Demo,包括获取当前网络类型,以及网络状态变化监听,你参考下:
MainActivity.java: package com.zms.netstate; import android.app.Activity; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView textShow; private Button btnGet; public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerDateTransReceiver(); textShow = (TextView) findViewById(R.id.textShow); btnGet = (Button) findViewById(R.id.btnGet); btnGet.setOnClickListener(new MyOnClickListener()); } private void registerDateTransReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(CONNECTIVITY_CHANGE_ACTION); filter.setPriority(1000); registerReceiver(new NetChangeReceiver(), filter); } private int getNetworkType() { ConnectivityManager connectMgr = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connectMgr.getActiveNetworkInfo(); if (info != null) { return info.getType(); } else { return -1; } } private class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGet: int netType = getNetworkType(); if (netType == ConnectivityManager.TYPE_WIFI) { textShow.setText("Wi-Fi"); } else if (netType == ConnectivityManager.TYPE_MOBILE) { textShow.setText("Mobile"); } else { textShow.setText("None"); } break; } } } } NetChangeReceiver.java: package com.zms.netstate; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.widget.Toast; /** * Created by AlexZhou on 2015/4/20. * 15:58 */ public class NetChangeReceiver extends BroadcastReceiver { public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)) { Toast.makeText(context, "网络状态变化", Toast.LENGTH_SHORT).show(); } } } AndroidManifest中要添加网络状态权限: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |