GVKun编程网logo

Java SecurityException:签名者信息不匹配(签名信息不正确)

2

针对JavaSecurityException:签名者信息不匹配和签名信息不正确这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展Android9.0自动更新安装包解析错误java.lang.

针对Java SecurityException:签名者信息不匹配签名信息不正确这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展Android 9.0 自动更新 安装包解析错误 java.lang.SecurityException: Permission Denial、Android lollipop java.lang.SecurityException:用户和当前进程都没有android.permission.BLUETOOTH_PRIVILEGED、android sdk 23检测权限问题(java.lang.SecurityException)、android – java.lang.SecurityException“gps”位置提供程序需要ACCESS_FINE_LOCATION权限等相关知识,希望可以帮助到你。

本文目录一览:

Java SecurityException:签名者信息不匹配(签名信息不正确)

Java SecurityException:签名者信息不匹配(签名信息不正确)

如何解决Java SecurityException:签名者信息不匹配?

当从不同的JAR文件加载属于同一个程序包的类,并且这些JAR文件具有使用不同证书签名的签名时,就会发生这种情况-或更常见的是,至少有一个签​​名,而另一个或多个未签名(包括已加载的类)目录中,因为这些AFAIK无法签名)。

因此,请确保使用相同的证书对所有JAR(或至少包含相同包中的类的JAR)进行签名,或者从具有重叠包的JAR文件清单中删除签名。

解决方法

我像往常一样重新编译了我的课程,并突然收到以下错误消息。为什么?我该如何解决?

java.lang.SecurityException: class "Chinese_English_Dictionary"''s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:776)

Android 9.0 自动更新 安装包解析错误 java.lang.SecurityException: Permission Denial

Android 9.0 自动更新 安装包解析错误 java.lang.SecurityException: Permission Denial

在 android 9.0 自动下载更新时 遇到 安装包解析错误
在这里插入图片描述
在 android 7.0 使用的是同一套框架却没有问题?
然后通过 adb 命令抓取一下异常发现


12-18 19:21:32.665  4804  5604 W InstallStaging: java.lang.SecurityException: Permission Denial: reading android.support.v4.content.FileProvider uri content://com.***.***.update_app.file_provider/download/update/***.apk from pid=4804, uid=1000 requires the provider be exported, or grantUriPermission()
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.os.Parcel.createException(Parcel.java:1950)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.os.Parcel.readException(Parcel.java:1918)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:698)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1459)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1296)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.content.ContentResolver.openInputStream(ContentResolver.java:1016)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at com.android.packageinstaller.InstallStaging$StagingAsyncTask.doInBackground(InstallStaging.java:167)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at com.android.packageinstaller.InstallStaging$StagingAsyncTask.doInBackground(InstallStaging.java:160)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.os.AsyncTask$2.call(AsyncTask.java:333)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
12-18 19:21:32.665  4804  5604 W InstallStaging: 	at java.lang.Thread.run(Thread.java:764)

发现 Android9.0 是需要权限读取 fileProvider 和 uri 的
于是我看了一下三方框架的源码,确实没有加权限

private Intent installIntent(Context context, String path) {
   
   
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        String fileProviderAuthority = getFileProviderAuthority(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && null!= fileProviderAuthority) {
   
   
            Uri fileUri = FileProvider.getUriForFile(context, fileProviderAuthority, new File(path));
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
   
   
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        }
        return intent;
    }

于是我就扒了一下源码对其进行修改

private Intent installIntent(Context context, String path) {
   
   
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        String fileProviderAuthority = getFileProviderAuthority(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && null!= fileProviderAuthority) {
   
   
            Uri fileUri = FileProvider.getUriForFile(context, fileProviderAuthority, new File(path));
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            grantUriPermission(getPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        } else {
   
   
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        }
        return intent;
    }

测试通过,完美安装,没有出现解析失败问题

代码:

		<!--AndroidManifest.xml-->
		<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
		<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   	    <uses-permission android:name="android.permission.INTERNET"/>
		
		<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="包名.file_provider"
            android:exported="false"
            android:grantUriPermissions="true">

            <!-- 元数据 -->
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"
                tools:replace="android:resource" />
        </provider> 
        
		<service android:name=".UpdateService"/>//从源码下载的升级下载安装apk的服务
 <!-- file_paths.xml -->
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="." name="download" />
    <external-cache-path
        name="storage/emulated/0"
        path="." />
</paths>
/**
 * Created by Sun on 2020/12/19.
 */
public class UpdateService extends Service {
   
   
    public static final String TAG = "UpdateService";
    public static final String ACTION = "me.shenfan.UPDATE_APP";
    public static final String STATUS = "status";
    public static final String PROGRESS = "progress";
    public static boolean DEBUG = false;

    //下载大小通知频率
    public static final int UPDATE_NUMBER_SIZE = 1;
    public static final int DEFAULT_RES_ID = -1;

    public static final int UPDATE_PROGRESS_STATUS = 0;
    public static final int UPDATE_ERROR_STATUS = -1;
    public static final int UPDATE_SUCCESS_STATUS = 1;

    //params
    private static final String URL = "downloadUrl";
    private static final String ICO_RES_ID = "icoResId";
    private static final String ICO_SMALL_RES_ID = "icoSmallResId";
    private static final String UPDATE_PROGRESS = "updateProgress";
    private static final String STORE_DIR = "storeDir";
    private static final String DOWNLOAD_NOTIFICATION_FLAG = "downloadNotificationFlag";
    private static final String DOWNLOAD_SUCCESS_NOTIFICATION_FLAG = "downloadSuccessNotificationFlag";
    private static final String DOWNLOAD_ERROR_NOTIFICATION_FLAG = "downloadErrorNotificationFlag";
    private static final String IS_SEND_BROADCAST = "isSendBroadcast";


    private String downloadUrl;
    private int icoResId;             //default app ico
    private int icoSmallResId;
    private int updateProgress;   //update notification progress when it add number
    private String storeDir;          //default sdcard/Android/package/update
    private int downloadNotificationFlag;
    private int downloadSuccessNotificationFlag;
    private int downloadErrorNotificationFlag;
    private boolean isSendBroadcast;

    private UpdateProgressListener updateProgressListener;
    private LocalBinder localBinder = new LocalBinder();

    /**
     * Class used for the client Binder.
     */
    public class LocalBinder extends Binder {
   
   
        /**
         * set update progress call back
         *
         * @param listener
         */
        public void setUpdateProgressListener(UpdateProgressListener listener) {
   
   
            UpdateService.this.setUpdateProgressListener(listener);
        }
    }


    private boolean startDownload;//开始下载
    private int lastProgressNumber;
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private int notifyId;
    private String appName;
    private LocalBroadcastManager localBroadcastManager;
    private Intent localIntent;
    private DownloadApk downloadApkTask;

    /**
     * whether debug
     */
    public static void debug() {
   
   
        DEBUG = true;
    }

    private Intent installIntent(Context context, String path) {
   
   
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        String fileProviderAuthority = getFileProviderAuthority(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && null!= fileProviderAuthority) {
   
   
            Uri fileUri = FileProvider.getUriForFile(context, fileProviderAuthority, new File(path));
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            grantUriPermission(getPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        } else {
   
   
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        }
        return intent;
    }

    /**
     * 获取FileProvider的auth
     */
    private static String getFileProviderAuthority(Context context) {
   
   
        try {
   
   
            for (ProviderInfo provider : context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS).providers) {
   
   
                if (FileProvider.class.getName().equals(provider.name) && provider.authority.endsWith(".update_app.file_provider")) {
   
   
                    return provider.authority;
                }
            }
        } catch (PackageManager.NameNotFoundException ignore) {
   
   
        }
        return null;
    }

    private static Intent webLauncher(String downloadUrl) {
   
   
        Uri download = Uri.parse(downloadUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, download);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    private static String getSaveFileName(String downloadUrl) {
   
   
        if (downloadUrl == null || TextUtils.isEmpty(downloadUrl)) {
   
   
            return System.currentTimeMillis() + ".apk";
        }
        return downloadUrl.substring(downloadUrl.lastIndexOf("/"));
    }

    private static File getDownloadDir(UpdateService service) {
   
   
        File downloadDir = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
   
   
            if (service.storeDir != null) {
   
   
                downloadDir = new File(Environment.getExternalStorageDirectory(), service.storeDir);
            } else {
   
   
                downloadDir = new File(service.getExternalCacheDir(), "update");
            }
        } else {
   
   
            downloadDir = new File(service.getCacheDir(), "update");
        }
        if (!downloadDir.exists()) {
   
   
            downloadDir.mkdirs();
        }
        return downloadDir;
    }


    @Override
    public void onCreate() {
   
   
        super.onCreate();
        appName = getApplicationName();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
   
   
        if (!startDownload && intent != null) {
   
   
            startDownload = true;
            downloadUrl = intent.getStringExtra(URL);
            icoResId = intent.getIntExtra(ICO_RES_ID, DEFAULT_RES_ID);
            icoSmallResId = intent.getIntExtra(ICO_SMALL_RES_ID, DEFAULT_RES_ID);
            storeDir = intent.getStringExtra(STORE_DIR);
            updateProgress = intent.getIntExtra(UPDATE_PROGRESS, UPDATE_NUMBER_SIZE);
            downloadNotificationFlag = intent.getIntExtra(DOWNLOAD_NOTIFICATION_FLAG, 0);
            downloadErrorNotificationFlag = intent.getIntExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, 0);
            downloadSuccessNotificationFlag = intent.getIntExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, 0);
            isSendBroadcast = intent.getBooleanExtra(IS_SEND_BROADCAST, false);


            if (DEBUG) {
   
   
                Log.d(TAG, "downloadUrl: " + downloadUrl);
                Log.d(TAG, "icoResId: " + icoResId);
                Log.d(TAG, "icoSmallResId: " + icoSmallResId);
                Log.d(TAG, "storeDir: " + storeDir);
                Log.d(TAG, "updateProgress: " + updateProgress);
                Log.d(TAG, "downloadNotificationFlag: " + downloadNotificationFlag);
                Log.d(TAG, "downloadErrorNotificationFlag: " + downloadErrorNotificationFlag);
                Log.d(TAG, "downloadSuccessNotificationFlag: " + downloadSuccessNotificationFlag);
                Log.d(TAG, "isSendBroadcast: " + isSendBroadcast);
            }

            notifyId = startId;
            buildNotification();
            buildBroadcast();
            downloadApkTask = new DownloadApk(this);
            downloadApkTask.execute(downloadUrl);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
   
   
        return localBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
   
   
        return true;
    }

    public void setUpdateProgressListener(UpdateProgressListener updateProgressListener) {
   
   
        this.updateProgressListener = updateProgressListener;
    }

    @Override
    public void onDestroy() {
   
   
        if (downloadApkTask != null) {
   
   
            downloadApkTask.cancel(true);
        }

        if (updateProgressListener != null) {
   
   
            updateProgressListener = null;
        }
        localIntent = null;
        builder = null;

        super.onDestroy();
    }

    public String getApplicationName() {
   
   
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
   
   
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
   
   
            applicationInfo = null;
        }
        String applicationName =
                (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    private void buildBroadcast() {
   
   
        if (!isSendBroadcast) {
   
   
            return;
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localIntent = new Intent(ACTION);
    }

    private void sendLocalBroadcast(int status, int progress) {
   
   
        if (!isSendBroadcast || localIntent == null) {
   
   
            return;
        }
        localIntent.putExtra(STATUS, status);
        localIntent.putExtra(PROGRESS, progress);
        localBroadcastManager.sendBroadcast(localIntent);
    }

    private void buildNotification() {
   
   
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(getString(R.string.update_app_model_prepare, appName))
                .setWhen(System.currentTimeMillis())
                .setProgress(100, 1, false)
                .setSmallIcon(icoSmallResId)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(), icoResId))
                .setDefaults(downloadNotificationFlag);

        manager.notify(notifyId, builder.build());
    }

    private void start() {
   
   
        builder.setContentTitle(appName);
        builder.setContentText(getString(R.string.update_app_model_progress, 1, "%"));
        //setChannelId 必须添加否则不能在通知栏显示(Android 8.0)
        builder.setChannelId(getPackageName());
        manager.notify(notifyId, builder.build());
        sendLocalBroadcast(UPDATE_PROGRESS_STATUS, 1);
        if (updateProgressListener != null) {
   
   
            updateProgressListener.start();
        }
    }

    /**
     * @param progress download percent , max 100
     */
    private void update(int progress) {
   
   
        if (progress - lastProgressNumber > updateProgress) {
   
   
            lastProgressNumber = progress;
            builder.setProgress(100, progress, false);
            builder.setContentText(getString(R.string.update_app_model_progress, progress, "%"));
            manager.notify(notifyId, builder.build());
            sendLocalBroadcast(UPDATE_PROGRESS_STATUS, progress);
            if (updateProgressListener != null) {
   
   
                updateProgressListener.update(progress);
            }
        }
    }

    private void success(String path) {
   
   
        builder.setProgress(0, 0, false);
        builder.setContentText(getString(R.string.update_app_model_success));
        Intent i = installIntent(this, path);
        PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(intent);
        builder.setDefaults(downloadSuccessNotificationFlag);
        Notification n = builder.build();
        n.contentIntent = intent;
        manager.notify(notifyId, n);
        sendLocalBroadcast(UPDATE_SUCCESS_STATUS, 100);
        if (updateProgressListener != null) {
   
   
            updateProgressListener.success();
        }
        startActivity(i);
        stopSelf();
    }

    private void error() {
   
   
        Intent i = webLauncher(downloadUrl);
        PendingIntent intent = PendingIntent.getActivity(this, 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentText(getString(R.string.update_app_model_error));
        builder.setContentIntent(intent);
        builder.setProgress(0, 0, false);
        builder.setDefaults(downloadErrorNotificationFlag);
        Notification n = builder.build();
        n.contentIntent = intent;
        manager.notify(notifyId, n);
        sendLocalBroadcast(UPDATE_ERROR_STATUS, -1);
        if (updateProgressListener != null) {
   
   
            updateProgressListener.error();
        }
        stopSelf();
    }

    private static class DownloadApk extends AsyncTask<String, Integer, String> {
   
   

        private WeakReference<UpdateService> updateServiceWeakReference;

        public DownloadApk(UpdateService service) {
   
   
            updateServiceWeakReference = new WeakReference<>(service);
        }

        @Override
        protected void onPreExecute() {
   
   
            super.onPreExecute();
            UpdateService service = updateServiceWeakReference.get();
            if (service != null) {
   
   
                service.start();
            }
        }

        @Override
        protected String doInBackground(String... params) {
   
   

            final String downloadUrl = params[0];

            final File file = new File(UpdateService.getDownloadDir(updateServiceWeakReference.get()),
                    UpdateService.getSaveFileName(downloadUrl));
            if (DEBUG) {
   
   
                Log.d(TAG, "download url is " + downloadUrl);
                Log.d(TAG, "download apk cache at " + file.getAbsolutePath());
            }
            File dir = file.getParentFile();
            if (!dir.exists()) {
   
   
                dir.mkdirs();
            }

            HttpURLConnection httpConnection = null;
            InputStream is = null;
            FileOutputStream fos = null;
            int updateTotalSize = 0;
            URL url;
            try {
   
   
                url = new URL(downloadUrl);
                httpConnection = (HttpURLConnection) url.openConnection();
                httpConnection.setConnectTimeout(20000);
                httpConnection.setReadTimeout(20000);

                if (DEBUG) {
   
   
                    Log.d(TAG, "download status code: " + httpConnection.getResponseCode());
                }

                if (httpConnection.getResponseCode() != 200) {
   
   
                    return null;
                }

                updateTotalSize = httpConnection.getContentLength();

                if (file.exists()) {
   
   
                    if (updateTotalSize == file.length()) {
   
   
                        // 下载完成
                        return file.getAbsolutePath();
                    } else {
   
   
                        file.delete();
                    }
                }
                file.createNewFile();
                is = httpConnection.getInputStream();
                fos = new FileOutputStream(file, false);
                byte buffer[] = new byte[4096];

                int readSize = 0;
                int currentSize = 0;

                while ((readSize = is.read(buffer)) > 0) {
   
   
                    fos.write(buffer, 0, readSize);
                    currentSize += readSize;
                    publishProgress((currentSize * 100 / updateTotalSize));
                }
                // download success
            } catch (Exception e) {
   
   
                e.printStackTrace();
                return null;
            } finally {
   
   
                if (httpConnection != null) {
   
   
                    httpConnection.disconnect();
                }
                if (is != null) {
   
   
                    try {
   
   
                        is.close();
                    } catch (IOException e) {
   
   
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
   
   
                    try {
   
   
                        fos.close();
                    } catch (IOException e) {
   
   
                        e.printStackTrace();
                    }
                }
            }
            return file.getAbsolutePath();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
   
   
            super.onProgressUpdate(values);
            if (DEBUG) {
   
   
                Log.d(TAG, "current progress is " + values[0]);
            }
            UpdateService service = updateServiceWeakReference.get();
            if (service != null) {
   
   
                service.update(values[0]);
            }
        }

        @Override
        protected void onPostExecute(String s) {
   
   
            super.onPostExecute(s);
            UpdateService service = updateServiceWeakReference.get();
            if (service != null) {
   
   
                if (s != null) {
   
   
                    service.success(s);
                } else {
   
   
                    service.error();
                }
            }
        }
    }


    /**
     * a builder class helper use UpdateService
     */
    public static class Builder {
   
   

        private String downloadUrl;
        private int icoResId = DEFAULT_RES_ID;             //default app ico
        private int icoSmallResId = DEFAULT_RES_ID;
        private int updateProgress = UPDATE_NUMBER_SIZE;   //update notification progress when it add number
        private String storeDir;          //default sdcard/Android/package/update
        private int downloadNotificationFlag;
        private int downloadSuccessNotificationFlag;
        private int downloadErrorNotificationFlag;
        private boolean isSendBroadcast;

        protected Builder(String downloadUrl) {
   
   
            this.downloadUrl = downloadUrl;
        }

        public static Builder create(String downloadUrl) {
   
   
            if (downloadUrl == null) {
   
   
                throw new NullPointerException("downloadUrl == null");
            }
            return new Builder(downloadUrl);
        }

        public String getDownloadUrl() {
   
   
            return downloadUrl;
        }

        public int getIcoResId() {
   
   
            return icoResId;
        }

        public Builder setIcoResId(int icoResId) {
   
   
            this.icoResId = icoResId;
            return this;
        }

        public int getIcoSmallResId() {
   
   
            return icoSmallResId;
        }

        public Builder setIcoSmallResId(int icoSmallResId) {
   
   
            this.icoSmallResId = icoSmallResId;
            return this;
        }

        public int getUpdateProgress() {
   
   
            return updateProgress;
        }

        public Builder setUpdateProgress(int updateProgress) {
   
   
            if (updateProgress < 1) {
   
   
                throw new IllegalArgumentException("updateProgress < 1");
            }
            this.updateProgress = updateProgress;
            return this;
        }

        public String getStoreDir() {
   
   
            return storeDir;
        }

        public Builder setStoreDir(String storeDir) {
   
   
            this.storeDir = storeDir;
            return this;
        }

        public int getDownloadNotificationFlag() {
   
   
            return downloadNotificationFlag;
        }

        public Builder setDownloadNotificationFlag(int downloadNotificationFlag) {
   
   
            this.downloadNotificationFlag = downloadNotificationFlag;
            return this;
        }

        public int getDownloadSuccessNotificationFlag() {
   
   
            return downloadSuccessNotificationFlag;
        }

        public Builder setDownloadSuccessNotificationFlag(int downloadSuccessNotificationFlag) {
   
   
            this.downloadSuccessNotificationFlag = downloadSuccessNotificationFlag;
            return this;
        }

        public int getDownloadErrorNotificationFlag() {
   
   
            return downloadErrorNotificationFlag;
        }

        public Builder setDownloadErrorNotificationFlag(int downloadErrorNotificationFlag) {
   
   
            this.downloadErrorNotificationFlag = downloadErrorNotificationFlag;
            return this;
        }

        public boolean isSendBroadcast() {
   
   
            return isSendBroadcast;
        }

        public Builder setIsSendBroadcast(boolean isSendBroadcast) {
   
   
            this.isSendBroadcast = isSendBroadcast;
            return this;
        }

        public Builder build(Context context) {
   
   
            if (context == null) {
   
   
                throw new NullPointerException("context == null");
            }
            Intent intent = new Intent();
            intent.setClass(context, UpdateService.class);
            intent.putExtra(URL, downloadUrl);

            if (icoResId == DEFAULT_RES_ID) {
   
   
                icoResId = getIcon(context);
            }

            if (icoSmallResId == DEFAULT_RES_ID) {
   
   
                icoSmallResId = icoResId;
            }
            intent.putExtra(ICO_RES_ID, icoResId);
            intent.putExtra(STORE_DIR, storeDir);
            intent.putExtra(ICO_SMALL_RES_ID, icoSmallResId);
            intent.putExtra(UPDATE_PROGRESS, updateProgress);
            intent.putExtra(DOWNLOAD_NOTIFICATION_FLAG, downloadNotificationFlag);
            intent.putExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, downloadSuccessNotificationFlag);
            intent.putExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, downloadErrorNotificationFlag);
            intent.putExtra(IS_SEND_BROADCAST, isSendBroadcast);
            context.startService(intent);

            return this;
        }

        private int getIcon(Context context) {
   
   

            final PackageManager packageManager = context.getPackageManager();
            ApplicationInfo appInfo = null;
            try {
   
   
                appInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
   
   
                e.printStackTrace();
            }
            if (appInfo != null) {
   
   
                return appInfo.icon;
            }
            return 0;
        }
    }

}

/**
 * 下载回调
 */
public interface UpdateProgressListener {
   
   
    /**
     * download start
     */
     void start();

    /**
     * update download progress
     * @param progress
     */
     void update(int progress);

    /**
     * download success
     */
     void success();

    /**
     * download error
     */
     void error();
}

			UpdateService.Builder.create("服务器给的下载路径")
                                 .setStoreDir("下载路径")//default sdcard/Android/package/update
               				     .setIsSendBroadcast(true)
                                 .setIcoResId(android.R.drawable.ic_notification_clear_all)
                                 .setIcoSmallResId(android.R.drawable.ic_notification_overlay)
                                 .build(context);

三方框架源码地址

Android lollipop java.lang.SecurityException:用户和当前进程都没有android.permission.BLUETOOTH_PRIVILEGED

Android lollipop java.lang.SecurityException:用户和当前进程都没有android.permission.BLUETOOTH_PRIVILEGED

我目前正在开发一个 Android应用程序,它使用Eclipse(Java)通过蓝牙连接到设备.目前我在Android 4.4(Kit-Kat)及以下版本上工作,但在Android 5(Lollipop)的新更新之后.发生安全异常.

表现:

<uses-permission android:name="android.permission.BLUetoOTH" />
<uses-permission android:name="android.permission.BLUetoOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUetoOTH_PRIVILEGED" />
<uses-feature android:name="android.hardware.bluetooth_le"
        android:required="false" />

码:

mBleScanner.startScan(filters,scanSettings,mLeScanCallback);

private ScanCallback mLeScanCallback = new ScanCallback()
{
    @Override
    public void onScanResult(int callbackType,ScanResult result)
    {
        BluetoothDevice device = result.getDevice();
        if(device.getName() != null)
        {
            if(device.getName().toupperCase().contains("MyDevice"))
            {

                mBleScanner.stopScan(mLeScanCallback);

                if (device.getBondState() == BluetoothDevice.BOND_BONDED)
                {
                    Connect(device.getAddress().toString()); 
                }
                else
                {
                    // pair device
                    device.setPairingConfirmation(true);
                    device.createBond();
                }
            }
        }
    }
};
...
..
.
private void BondDevice(BluetoothGattCharacteristic bgc,boolean pnEnable)
{
    boolean bool = gatt.setCharacteristicNotification(bgc,true); // this line throw security exception
    BluetoothGattDescriptor bgd=bgc.getDescriptor(UUID.fromString(BLE_DESCRIPTOR_NOTIFY));

    byte[] arrayOfByte = pnEnable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE:
                      BluetoothGattDescriptor.disABLE_NOTIFICATION_VALUE;
    gattDescriptor.setValue(arrayOfByte);
    mBluetoothGatt.writeDescriptor(bgd);
}

堆栈跟踪:

04-27 12:36:24.559: W/BluetoothGatt(17764): Unhandled exception in callback
04-27 12:36:24.559: W/BluetoothGatt(17764): java.lang.SecurityException: Need BLUetoOTH_PRIVILEGED permission: Neither user 10215 nor current process has android.permission.BLUetoOTH_PRIVILEGED.
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.os.Parcel.readException(Parcel.java:1540)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.os.Parcel.readException(Parcel.java:1493)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.bluetooth.IBluetoothGatt$Stub$Proxy.registerForNotification(IBluetoothGatt.java:1163)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.bluetooth.BluetoothGatt.setCharacteristicNotification(BluetoothGatt.java:1239)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at com.vibease.ap3.service.ServiceBLE.BondDevice(ServiceBLE.java:568)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at com.vibease.ap3.service.ServiceBLE.CheckDevice(ServiceBLE.java:518)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at com.vibease.ap3.service.ServiceBLE.access$7(ServiceBLE.java:493)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at com.vibease.ap3.service.ServiceBLE$2.onServicesdiscovered(ServiceBLE.java:373)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.bluetooth.BluetoothGatt$1.onSearchComplete(BluetoothGatt.java:309)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:217)
04-27 12:36:24.559: W/BluetoothGatt(17764):     at android.os.Binder.execTransact(Binder.java:446)

解决方法

04-27 12:36:24.559: W/BluetoothGatt(17764): java.lang.SecurityException: Need BLUetoOTH_PRIVILEGED@H_301_21@ permission: Neither user 10215 nor current process has android.permission.BLUetoOTH_PRIVILEGED@H_301_21@.

只需添加它要求的权限:

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

android sdk 23检测权限问题(java.lang.SecurityException)

android sdk 23检测权限问题(java.lang.SecurityException)

试图做简单的APP将记录插入电话簿.
看起来我没有权限问题,但系统不会让创建记录:

07-28 18:11:44.799  2304 10616 I UpdateIcingCorporaServi: Updating corpora: APPS=com.example.aero.myapplication,CONTACTS=MAYBE
07-28 18:11:45.362  2304 10648 I UpdateIcingCorporaServi: Updating corpora: APPS=com.example.aero.myapplication.test,CONTACTS=MAYBE
07-28 18:11:45.651 10663 10678 I GrantPermissionCallable: Permission: android.permission.WRITE_CONTACTS is already granted!
07-28 18:11:46.255 10663 10678 I OK      : contact Permission to record allowed
07-28 18:11:46.255 10663 10678 D Info    : Creating contact: 123456789
07-28 18:11:46.259  2097  2114 E DatabaseUtils: java.lang.SecurityException: Proxy package com.android.providers.contacts from uid 10001 or calling package com.example.aero.myapplication.test from uid 10097 not allowed to perform WRITE_CONTACTS
07-28 18:11:46.260 10663 10678 E Error   : Exception encountered while inserting contact: java.lang.SecurityException: Proxy package com.android.providers.contacts from uid 10001 or calling package com.example.aero.myapplication.test from uid 10097 not allowed to perform WRITE_CONTACTS

有任何想法吗?为什么那神秘?
一旦我运行app它安装2 apk:

$adb push /Users/aero/AndroidStudioProjects/MyApplication/app/build/outputs/apk/app-debug.apk /data/local/tmp/com.example.aero.myapplication
$adb shell pm install -r "/data/local/tmp/com.example.aero.myapplication"

$adb push /Users/aero/AndroidStudioProjects/MyApplication/app/build/outputs/apk/app-debug-androidTest.apk /data/local/tmp/com.example.aero.myapplication.test
$adb shell pm install -r "/data/local/tmp/com.example.aero.myapplication.test"

并且只有com.example.aero.myapplication在系统中具有权限,com.example.aero.myapplication.test没有任何权限.我失去了一点点.

package com.example.aero.myapplication;


import android.Manifest;
import android.app.Instrumentation;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SdkSuppress;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;

import java.util.ArrayList;

import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertthat;


@RunWith(AndroidJUnit4.class)
public class MainActivity{

    @Rule
    public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_CONTACTS);

    public Instrumentation instrumentation;
    private UiDevice mDevice;
    private static final int RECORD_REQUEST_CODE = 101;


    @Before
    public void before() {
        // Initialize UiDevice instance
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        //instrumentation = InstrumentationRegistry.getInstrumentation();
        assertthat(mDevice,notNullValue());
        // Start from the home screen
        mDevice.pressHome();
    }

    @org.junit.Test
    public void test() throws InterruptedException {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        String NAME = "TEST RECORD";
        String NMBR = "123456789";
        CreatePhoneBookEntry(context,NAME,NMBR);
    }

    public void CreatePhoneBookEntry(Context context,String NAME,String NMBR) {
        //ActivityCompat.requestPermissions(context,//        new String[]{Manifest.permission.WRITE_CONTACTS},//        RECORD_REQUEST_CODE)


        int permission = ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_CONTACTS);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            Log.i("Error","contact Permission to record denied");
        } else {
            Log.i("OK","contact Permission to record allowed");
            };

        /*
     * Gets values from the UI
     */
        // Creates a new array of ContentProviderOperation objects.
        ArrayList<ContentProviderOperation> ops =
                new ArrayList<ContentProviderOperation>();

    /*
     * Creates a new raw contact with its account type (server type) and account name
     * (user''s account). Remember that the display name is not stored in this row,but in a
     * Structuredname data row. No other data is required.
     */
        ContentProviderOperation.Builder op =
                ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,null)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME,null);

        // Builds the operation and adds it to the array of operations
        ops.add(op.build());

        // Creates the display name for the new raw contact,as a Structuredname data row.
        op =
                ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            /*
             * withValueBackReference sets the value of the first argument to the value of
             * the ContentProviderResult indexed by the second argument. In this particular
             * call,the raw contact ID column of the Structuredname data row is set to the
             * value of the result returned by the first operation,which is the one that
             * actually adds the raw contact row.
             */
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,0)

                        // Sets the data row''s MIME type to Structuredname
                        .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Structuredname.CONTENT_ITEM_TYPE)

                        // Sets the data row''s display name to the name in the UI.
                        .withValue(ContactsContract.CommonDataKinds.Structuredname.disPLAY_NAME,NAME);

        // Builds the operation and adds it to the array of operations
        ops.add(op.build());

        // Inserts the specified phone number and type as a Phone data row
        op =
                ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            /*
             * Sets the value of the raw contact id column to the new raw contact ID returned
             * by the first operation in the batch.
             */
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,0)

                        // Sets the data row''s MIME type to Phone
                        .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)

                        // Sets the phone number and type
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,NMBR)
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,"MOBILE");

        // Builds the operation and adds it to the array of operations
        ops.add(op.build());
        // Ask the Contacts Provider to create a new contact
        Log.d("Info","Creating contact: " + NMBR);

    /*
     * Applies the array of ContentProviderOperation objects in batch. The results are
     * discarded.
     */
        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY,ops);
        } catch (Exception e) {
            // Log exception
            Log.e("Error","Exception encountered while inserting contact: " + e);
        }
    }
}

解决方法

陷入同样的​​问题,但获得了不同的许可.

对我的修复很简单,我忘了添加< uses-permission android:name =“android.permission.THE_PERMISSION”/>到AndroidManifest.xml

所以也许你应该确保你有所需的< uses-permission ... />和< uses-feature ... />在那里.

希望能帮助到你..

android – java.lang.SecurityException“gps”位置提供程序需要ACCESS_FINE_LOCATION权限

android – java.lang.SecurityException“gps”位置提供程序需要ACCESS_FINE_LOCATION权限

所以这是我的MyLocationListener类
package com.example.gpslocater;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MyLocationListener implements LocationListener {

        public TextView mLocationTextView;
    Context mContent;
    public MyLocationListener(Context context) {
        mContent = context;
    }
    @Override
    public void onLocationChanged(Location location) {

        location.getLatitude();
        location.getLongitude();

        String Text = "My current location is :" + 
        "Latitude = " + location.getLatitude() +
        " Longitude = " + location.getLongitude();
        //figure out a way to make it display through a text view
        mLocationTextView.setText(Text);
    }

    @Override
    public void onProviderdisabled(String provider) {
        Toast.makeText(mContent,"Gps disabled",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(mContent,"Gps Enabled",Toast.LENGTH_SHORT);


    }

    @Override
    public void onStatusChanged(String provider,int status,Bundle extras) {
        // Todo Auto-generated method stub

    }

}

这是我的GPS活动课程

public class GPSActivity extends Activity {
    private Button mGPSButton;
    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private LocationManager mLocationManager;
    private LocationListener mLocationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);

        mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new MyLocationListener(null);
        mGPSButton = (Button)findViewById(R.id.press_button);
        mGPSButton.setonClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Todo Auto-generated method stub
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,mLocationListener);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.g,menu);
        return true;
    }

}

现在,当我运行它可以工作,但按下按钮后程序停止响应有很多错误消息

有一条错误消息说java.lang.SecurityException“gps”位置提供程序需要ACCESS_FINE_LOCATION权限,我是否必须添加,如果是这样,我在哪里添加它?我认为这是我的程序崩溃的原因.

解决方法

从提供的logcat有意义.
在清单中添加此内容
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

关于Java SecurityException:签名者信息不匹配签名信息不正确的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Android 9.0 自动更新 安装包解析错误 java.lang.SecurityException: Permission Denial、Android lollipop java.lang.SecurityException:用户和当前进程都没有android.permission.BLUETOOTH_PRIVILEGED、android sdk 23检测权限问题(java.lang.SecurityException)、android – java.lang.SecurityException“gps”位置提供程序需要ACCESS_FINE_LOCATION权限等相关内容,可以在本站寻找。

本文标签: