Android调用原生文件管理器来选择文件

在activity即可:

public class UploadActivity  extends Activity {

    public final static int REQUEST_CODE = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*"); //设置类型,任意类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        this.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //if (requestCode == REQUEST_CODE && resultCode == 200) {
        if (data == null) {
            // 用户未选择任何文件,直接返回
            return;
        }

        Uri uri = data.getData(); // 获取用户选择文件的URI

        String path =  uri.getPath();
        Toast.makeText(this, "path="+path, Toast.LENGTH_SHORT).show();
        
        String truePath = this.getPath(this,uri);
        Toast.makeText(this, "truePath="+truePath, Toast.LENGTH_SHORT).show();

        File file = new File(truePath);
        Toast.makeText(this, "file.exists()="+file.exists(), Toast.LENGTH_SHORT).show();

        Intent intent = new Intent();
        intent.putExtra("truePath", truePath);
        setResult(Activity.RESULT_OK, intent);
        finish();

    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else if ("document".equals(type)) {
                    contentUri = MediaStore.Files.getContentUri("external");
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

}

 

注意:请记得开启文件读写权限,否则获取到的文件路径为null:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

使用okhttp3时忽略所有证书

1、新建一个SSLSocketClient.java类:

import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLSocketClient {

    //获取这个SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    //获取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

}

 

2、使用以下代码来构建okhttp3即可:

OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
mBuilder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
mBuilder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
OkHttpClient client = mBuilder.build();

 

12306火车购票优先选下铺的方法

1、先在页面空白地方右击“审查元素”

2、在页面代码编辑区域搜索“优先席别”

3、在网页页面出现席别选择,此时选择硬卧,然后右键“硬卧”选项并审查元素

4、在硬卧的span标签后增加以下代码即可:

<select name="passsenger_1_seat-detail_select" id="passenger_1_seat_detail_select" onchange="setseatDetail('1')">
    <option value="0">随机</option>
    <option value="3">上铺</option>
    <option value="2">中铺</option>
    <option value="1">下铺</option>
</select>

 

uni-app使用H5+调起安卓原生Activity

方式一,无需回调结果:

let platform = uni.getSystemInfoSync().platform;
if (platform == 'android') {

	//获取宿主上下文
	var main = plus.android.runtimeMainActivity();

	var openUrl = "sway://openapi:8848/oauthLogin?appKey=" + this.appKey + "&pkgName=" + this
		.pkgName;
	console.log(openUrl);

	//通过反射获取Android的Uri对象
	var Uri = plus.android.importClass("android.net.Uri");
	var uri = Uri.parse(openUrl);

	//通过反射获取Android的Intent对象
	var Intent = plus.android.importClass("android.content.Intent");
	var intent = plus.android.newObject("android.content.Intent", Intent.ACTION_VIEW, uri);

	main.startActivity(intent);

} else {
	uni.showToast({
		title: "仅支持安卓客户端",
		icon: 'none',
		duration: 2000
	});
}

 

方式二,需要回调结果:

let platform = uni.getSystemInfoSync().platform;
if (platform == 'android') {

	//获取宿主上下文
	var main = plus.android.runtimeMainActivity();

	var openUrl = "sway://openapi:8848/oauthLogin?appKey=" + this.appKey + "&pkgName=" + this
		.pkgName;
	console.log(openUrl);

	//通过反射获取Android的Uri对象
	var Uri = plus.android.importClass("android.net.Uri");
	var uri = Uri.parse(openUrl);

	//通过反射获取Android的Intent对象
	var Intent = plus.android.importClass("android.content.Intent");
	var intent = plus.android.newObject("android.content.Intent", Intent.ACTION_VIEW, uri);

	//请求码保证了,开始的新界面和返回的是同一个操作
	var CODE_REQUEST = 1000

	main.startActivityForResult(intent, CODE_REQUEST);

	//设置原生界面返回后的回调操作
	main.onActivityResult = function(requestCode, resultCode, data) {
		if (requestCode == CODE_REQUEST) {
			//alert(requestCode); //这个是正确的 1000  
			//alert(resultCode); //始终都是0  
			//alert(data); //弹出 undefined
			plus.android.importClass(data);
			var bundle = data.getExtras();
			plus.android.importClass(bundle);
			let result = eval('(' + bundle.getString("data") + ')');
		}
	}
} else {
	uni.showToast({
		title: "仅支持安卓客户端",
		icon: 'none',
		duration: 2000
	});
}

 

uni-app使用H5+调用原生的安卓方法

uni-app代码:

//获取当前Activity,使用H5的方式调用android原生方法,从而启动activity
var main = plus.android.runtimeMainActivity();
//invoke: 调用对象(类对象/实例对象)的方法,调用Android原生方法        
let result = plus.android.invoke('cn.com.sway.test.TestActivity', 'test', main);
//弹窗显示返回结果
uni.showToast({
	title: "调用原生activity返回的结果为:\n" + result,
	icon: 'none',
	duration: 2000
});

安卓代码:

package cn.com.sway.test;

import android.app.Activity;
import android.widget.Toast;

import java.util.Random;

public class TestActivity extends Activity {

    public static String test(Activity activity, String text){
        Toast.makeText(activity, "来自uni-app的消息:"+text, Toast.LENGTH_SHORT).show();
        return "来自android的消息:"+(new Random()).nextInt();
    }

}

注意,被调用的安卓方法必须为static静态方法,否则无法被调起。

uniapp自定义入口Activity并进行交互

第一步:首先新建自己的MainActivity

package cn.com.sway.app

import android.os.Bundle;

import io.dcloud.WebAppActivity;

public class MainActivity extends WebAppActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    public boolean isStreamAppMode() {
        return false;
    }

}

注意:

1、务必集成io.dcloud.WebAppActivity这个类

2、必须要有isStreamAppMode方法,如果没有这个方法,会无法正常加载页面

第二部:在AndroidManifest.xml里修改入口Activity

    <activity
            android:name="cn.com.sway.app.MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|navigation"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:hardwareAccelerated="true"
            android:theme="@style/TranslucentTheme"
            android:screenOrientation="user"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

其他:在前端与MainActivity进行交互

前端这么写:

var main = plus.android.runtimeMainActivity();//获取当前的Activity
var res = main.getResData();//直接调用自定义Activity中的getResData方法
console.log(res);

在MainActivity补充getResData方法:

public String getResData(){
    return data;
}

 

Javascript:Json对象与Json字符串的转化

1.jQuery插件支持的转换方式

$.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象

 

2.浏览器支持的转换方式(Firefox,chrome,opera,safari,ie9,ie8)等浏览器:

JSON.stringify(obj)将JSON转为字符串。JSON.parse(string)将字符串转为JSON格式;

var a={“name”:”tom”,”sex”:”男”,”age”:”24″}; 
var b='{“name”:”Mike”,”sex”:”女”,”age”:”29″}’; 
var aToStr=JSON.stringify(a); 
var bToObj=JSON.parse(b); 
alert(typeof(aToStr));  //string 
alert(typeof(bToObj));//object

 

3.Javascript支持的转换方式: 
eval(‘(‘ + jsonstr + ‘)’); //可以将json字符串转换成json对象,注意需要在json字符外包裹一对小括号 
注:ie8(兼容模式),ie7和ie6也可以使用eval()将字符串转为JSON对象,但不推荐这些方式,这种方式不安全eval会执行json串中的表达式。

 

4.JSON官方的转换方式: 
http://www.json.org/提供了一个json.js,这样ie8(兼容模式),ie7和ie6就可以支持JSON对象以及其stringify()和parse()方法; 
可以在https://github.com/douglascrockford/JSON-js上获取到这个js,一般现在用json2.js。

uni-app离线android打包使用scheme

hbuilder版本:3.1.12

在AndroidManifest.xml中对io.dcloud.PandoraEntry添加scheme内容(注意不是io.dcloud.PandoraEntryActivity)

        <activity
            android:name="io.dcloud.PandoraEntry"
            android:configChanges="orientation|keyboardHidden|keyboard|navigation"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:hardwareAccelerated="true"
            android:theme="@style/TranslucentTheme"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="xxxxx" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.oppopush" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

记得把scheme换成正确的。

android studio使用发布者证书调试

修改app.gradle文件:

android {
    ....................................................

    //配置keystore签名
    signingConfigs {
        release {
            storeFile file("./cert/android.keystore")
            storePassword "123456"
            keyAlias "android"
            keyPassword "123456"
        }
    }

    buildTypes {
        debug {
            debuggable true
            signingConfig signingConfigs.release
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }
}

 

Android开发-禁止截图、录屏

只需要在 Activity 的onCreate() 方法中添加一行代码即可:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

添加这行代码后,当截屏的时候,系统会弹出一个Toast提示“禁止屏幕抓取”;当录屏的时候,看似能够正常录制,但是保存后的视频,都是一片黑色,并没有APP的相关界面。

如果开启禁止录屏后需要在某些场景取消的话,则使用以下语句即可:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);

 

close