廣播監聽網路和斷點續傳
阿新 • • 發佈:2019-01-25
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
public class MainActivity extends AppCompatActivity { private MyBroadcaseReceiver receiver; private String path = "http://img4q.duitang.com/uploads/item/201411/23/20141123072535_28aMM"+ ".jpeg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); x.view().inject(this); //動態註冊廣播 IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);receiver = new MyBroadcaseReceiver(); this.registerReceiver(receiver, filter); } private void getData(String path) { RequestParams params = new RequestParams(path); //設定下載路勁 params.setSaveFilePath(Environment.getExternalStorageDirectory().getAbsolutePath() + "/wangluo"); //設定斷點續傳記得和 params.setAutoRename(true);區分 params.setAutoResume(true); //設定執行緒池的個數,預設好像是5個 params.setExecutor(new PriorityExecutor(3, true)); //get請求資料 x.http().get(params, new Callback.ProgressCallback<File>() { @Override public void onSuccess(File result) { Toast.makeText(MainActivity.this, "下載成功onSuccess()", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { Toast.makeText(MainActivity.this, "下載完成onFinished()", Toast.LENGTH_SHORT).show(); } @Override public void onWaiting() { } @Override public void onStarted() { } @Override public void onLoading(long total, long current, boolean isDownloading) { Toast.makeText(MainActivity.this, "下載進度onLoading()" + (current / total * 100) + "%", Toast.LENGTH_SHORT).show(); } }); } class MyBroadcaseReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 判斷當前傳過來的Action是否是哪裡的斷網Actiion if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context .CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); //判斷有網路或無網路 if (info != null && info.isConnected()) { //如果有網,判斷當前是否是WIFI或移動資料或者其他第三方網路(VPN等) if (ConnectivityManager.TYPE_WIFI == info.getType()) { Toast.makeText(context, "WIFI已連結,可以下載資料", Toast.LENGTH_SHORT).show(); //如果是WIFI狀態下載檔案 getData(path); } else if (ConnectivityManager.TYPE_MOBILE == info.getType()) { Toast.makeText(context, "當前使用的是移動資料,請謹慎使用", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "連結的第三方網路,請謹慎使用", Toast.LENGTH_SHORT).show(); } } else {//如果沒有網路彈出吐司,也可以彈出對話方塊 Toast.makeText(context, "當前沒有網路,請連結網路", Toast.LENGTH_SHORT).show(); } } } } //登出廣播 @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } }