解决Android5.0及以上启动Service时,java.lang.IllegalArgumentException: Service Intent must be explicit

文章详细介绍了在Android5.0及以上版本中,Service服务必须采用显示方式启动的原因,并提供了通过设置包名来解决该问题的方法。解决方案包括直接设置包名或使用链式调用方式实现。

报错原因:

(摘自:http://blog.youkuaiyun.com/vrix/article/details/45289207)

有些时候我们使用Service的时需要采用隐私启动的方式,但是Android 5.0一出来后,其中有个特性就是Service Intent  must be explitict,也就是说从Lollipop开始,service服务必须采用显示方式启动。
而android源码是这样写的(源码位置:sdk/sources/android-21/android/app/ContextImpl.java):

private void validateServiceIntent(Intent service) {
        if (service.getComponent() == null && service.getPackage() == null) {
            if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
                IllegalArgumentException ex = new IllegalArgumentException(
                        "Service Intent must be explicit: " + service);
                throw ex;
            } else {
                Log.w(TAG, "Implicit intents with startService are not safe: " + service
                        + " " + Debug.getCallers(2, 3));
            }
        }
    }


解决方案:

(From:http://stackoverflow.com/questions/24480069/google-in-app-billing-illegalargumentexception-service-intent-must-be-explicit/26318757#26318757)

Intent intent = new Intent("com.a.b.cservice");
// This is the key line that fixed everything for me
intent.setPackage("com.a.b");

或者更优雅地链式调用:

Intent intent = new Intent("com.a.b.cservice").setPackage("com.a.b");





这个异常信息 `java.lang.IllegalArgumentException: Invalid data length: 115. Must be multiple of 16 bytes.` 通常出现在使用对称加密算法(如 AES),输入数据的长度不符合加密算法的要求。 ### 原因分析: - AES 等块加密算法要求数据长度必须是 **16 字节(bytes)的倍数**。 - 你传入的数据长度是 **115 字节**,不是 16 的整数倍,因此抛出异常。 ### 解决方法: 1. **使用填充机制(Padding)**: - 在加密前对数据进行填充,使其长度为 16 的倍数。常用的填充方式有: - PKCS5Padding - PKCS7Padding - ZeroBytePadding 等 2. **使用合适的加密模式**: - 使用支持填充的加密模式,例如 `AES/CBC/PKCS5Padding` 或 `AES/ECB/PKCS5Padding`。 3. **代码示例(Java)**: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AESExample { public static void main(String[] args) throws Exception { String plainText = "This is a test message that is not 16 bytes aligned."; String key = "1234567890123456"; // 16 bytes key Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES"); // 加密 cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] encrypted = cipher.doFinal(plainText.getBytes()); System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(encrypted)); } } ``` ### 说明: - 使用了 `AES/ECB/PKCS5Padding` 模式,自动对数据进行填充,确保长度是 16 的倍数。 - 加密后的数据可以使用 Base64 编码进行存储或传输。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值