美文网首页
Android常用代码OkHttp,Intent

Android常用代码OkHttp,Intent

作者: c4a1d989518e | 来源:发表于2017-06-06 18:10 被阅读17次

    使用OkHttp

    添加OKHttp库的依赖。编辑app/build.gradle文件,在dependencies闭包中添加:

    dependencies{
            compile 'com.squareup.okhttp3:okhttp:3.4.1'
    }
    

    库的版本可以用最新的。

    发送get请求:

    OkHttpClient client=new OkHttpClient();
    Request request=new Request.Builder().url("http://www.baidu.com").build();
    

    获得返回数据:

    Response response=client.newCall(request).execute();
    String responseData=response.body().string();
    

    发送post请求:

    RequestBody requestBody=new FormBody.Builder()
        .add("username","admin")
        .add("password","123456")
        .build();
    Request request=new Request.Builder()
        .url("http://www.baidu.com")
        .post(requestBody)
        .build();
    

    try catch

    try{
    }catch(Exception e){
    e.printStackTrace();
    }
    

    在活动中使用Toast

    测试中常用

    Toast.makeText(FirstActivity.this,"you click me",
        Toast.LENGTH_SHORT).show();
    

    Intent的使用

    最简单的:

    Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
    startActivity(intent);
    

    打开网址

    Intent intent=new Intent(Intent.Action_VIEW);
    intent.setData(Uri.parse("http://www.baidu.com");
    startActivity(intent);
    

    打电话:

    ntent intent=new Intent(Intent.Action_DIAL);
    intent.setData(Uri.parse("tel:10086");
    startActivity(intent);
    

    像下传递数据:

    String data="Hello SecondActivity";
    Intent intent=new intent(FirstActivity.this,SecondActivity.class);
    intent.putExtra("extra_data",data);
    startActivity(intent);
    

    其中“extra_data”和data是一对键值对,数据库中的概念,知识点啊。
    接受数据:

    Intent intent=getIntent();
    String data=intent.getStringExtra("extra_data");
    Log.d("SecondActivity",data);
    

    打开其他应用:

    Intent intent=new Intent();
                    PackageManager packageManager=getPackageManager();
                    intent=packageManager.getLaunchIntentForPackage("com.gschinamobile.hestudy");
                    intent.putExtra("param",“链接”);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
    

    相关文章

      网友评论

          本文标题:Android常用代码OkHttp,Intent

          本文链接:https://www.haomeiwen.com/subject/dehnfxtx.html