APK下载

1.xutils依赖

compile 'org.xutils:xutils:3.3.36'
2.布局:button按钮

3.代码

NetWorkUtils 工具类:

public class NetWorkUtils {
    //判断网络状态
    public static boolean isNetWorkIsAvailable(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null){
            return true;
        }else{
            return false;
        }
    }
    //判断wifi
    public static boolean isWifi(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.getType() == connectivityManager.TYPE_WIFI){
            return true;
        }else{
            return false;
        }
    }

    //判断流量
    public static boolean isMobile(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info!=null&&info.getType() ==connectivityManager.TYPE_MOBILE){
            return true;
        }else{
            return false;
        }
    }
}
xutils appliction

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true);
    }
}
记得要在清单文件注册

AndroidManifest.xml

android:name=".app.MyApp"
mainactivity
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button xiazai;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        xiazai = (Button) findViewById(R.id.xiazai);
        xiazai.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.xiazai:
                boolean workIsAvailable = NetWorkUtils.isNetWorkIsAvailable(MainActivity.this);
                if (!workIsAvailable) {
                    Toast.makeText(MainActivity.this, "网络未连接,请设置网络", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                    startActivity(intent);
                } else {
                    //连接成功下载
                    Toast.makeText(MainActivity.this, "网络连接成功", Toast.LENGTH_SHORT).show();

                    download();
                }
                break;
        }
    }
    //下载
    private void download() {
        final String[] items = {"wifi", "手机流量"};
        new AlertDialog.Builder(this).setTitle("网络选择").setIcon(R.mipmap.ic_launcher).setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                switch (which) {
                    case 0:
                        //wifi下 下载apk
                        downloadApk();
                        break;
                    case 1:
                        //手机流量下提醒用户
                        boolean mobile = NetWorkUtils.isMobile(MainActivity.this);
                        if (mobile) {
                            Toast.makeText(MainActivity.this, "现在未使用wifi,将耗用手机流量", Toast.LENGTH_SHORT).show();
                            Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                            startActivity(wifiSettingsIntent);

                        }
                        dialog.dismiss();
                        break;
                }
                dialog.dismiss();
            }
        }).show();
    }


    //下载apk
    private void downloadApk() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("版本更新");
        builder.setMessage("现在检测到新版本,是否更新?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                updateApk();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();


    }

    //版本更新
    private void updateApk() {
       //网址可能用不了
       String url = "http://mapp.qzone.qq.com/cgi-bin/mapp/mapp_subcatelist_qq?yyb_cateid=-10&categoryName=%E8%85%BE%E8%AE%AF%E8%BD%AF%E4%BB%B6&pageNo=1&pageSize=20&type=app&platform=touch&network_type=unknown&resolution=412x732";
        RequestParams params =new RequestParams(url);
        params.setCacheMaxAge(1000 * 60 * 10);
        x.http().get(params, new Callback.CacheCallback() {
            private String result = null;

            @Override
            public boolean onCache(String result) {
                this.result = result;
                Toast.makeText(MainActivity.this,"走缓存",Toast.LENGTH_SHORT).show();
                //默认false不走缓存 true 走缓存 过期之后就不走缓存
                getGson(result);
                return true;
            }


            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    this.result = result;
                    Toast.makeText(MainActivity.this,"调用",Toast.LENGTH_SHORT).show();
                    getGson(result);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }
    private void getGson(String result) {
        String substring = result.substring(0, result.length() - 1);
        Gson gson=new Gson();
        Bean bean = gson.fromJson(substring, Bean.class);

        final List app = bean.getApp();
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("点击下载");
        View view=View.inflate(this,R.layout.listview,null);
        ListView listView = (ListView) view.findViewById(R.id.list);
        listView.setAdapter(new Base(this,app));
        builder.setView(view);
        builder.setNegativeButton("后台下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                RequestParams params = new RequestParams(app.get(position).getUrl());
                String s = Environment.getExternalStorageDirectory() + "/bawei/";
                File file=new File(s);
                if (!file.exists()){
                    file.mkdir();
                }
                //保存到sdcard
                params.setSaveFilePath(Environment.getExternalStorageDirectory() + "/bawei/");
                //自动文件命令
                params.setAutoRename(true);
                //下载
                x.http().post(params, new Callback.ProgressCallback() {
                    @Override
                    public void onWaiting() {

                    }

                    @Override
                    public void onStarted() {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isDownloading) {

                    }

                    @Override
                    public void onSuccess(File result) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
                        startActivity(intent);

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        Toast.makeText(MainActivity.this,"取消",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished() {

                    }
                });
                Toast.makeText(MainActivity.this,"正在下载请稍后......",Toast.LENGTH_SHORT).show();

            }
        });


    }

}







你可能感兴趣的:(APK下载)