Java lang securityexception ошибка как исправить на андроид

I have a library (jar) on build path of my project. The project accesses the MainActivity in the jar, using the following intent:

final Intent it = new Intent();
it.setClassName("com.example.lib", "com.example.lib.MainActivity");
startActivity(it);

It used to work for sometime, but suddenly started getting ‘ActivityNotFoundException: No Activity found to handle Intent’ which I was able to resolve. But now I am stuck with a ‘java.lang.SecurityException: Permission Denial: starting Intent’.

I have tried all suggestions made on stackoverflow (check for duplicates in manifest file; add android:exported=»true» to lib manifest; Eclipse> Project> Clean; adding/ modifying ‘intent-filter’ tags; etc.). I even tried re-writing the manifest of the project but not going anywhere with it.

Here’s the logcat output:

11-07 06:20:52.176: E/AndroidRuntime(4626): FATAL EXCEPTION: main
11-07 06:20:52.176: E/AndroidRuntime(4626): java.lang.SecurityException: Permission     Denial: starting Intent { cmp=com.example.lib/.MainActivity } from ProcessRecord{40dd3778     4626:com.example.project/u0a10046} (pid=4626, uid=10046) not exported from uid 10047
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.os.Parcel.readException(Parcel.java:1425)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.os.Parcel.readException(Parcel.java:1379)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1885)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1412)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.Activity.startActivityForResult(Activity.java:3370)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.Activity.startActivityForResult(Activity.java:3331)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:824)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.Activity.startActivity(Activity.java:3566)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.Activity.startActivity(Activity.java:3534)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.example.project.MainActivity.onOptionsItemSelected(MainActivity.java:93)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.Activity.onMenuItemSelected(Activity.java:2548)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:366)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:980)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:547)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:115)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.view.View.performClick(View.java:4204)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.view.View$PerformClick.run(View.java:17355)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.os.Handler.handleCallback(Handler.java:725)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.os.Looper.loop(Looper.java:137)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at android.app.ActivityThread.main(ActivityThread.java:5041)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at java.lang.reflect.Method.invokeNative(Native Method)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at java.lang.reflect.Method.invoke(Method.java:511)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
11-07 06:20:52.176: E/AndroidRuntime(4626):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-07 06:20:52.176: E/AndroidRuntime(4626):     at dalvik.system.NativeStart.main(Native Method)

Manifest XML of Project:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.project"
android:versionCode="4"
android:versionName="4.0" >

<!-- Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<supports-screens android:anyDensity="true" />

<!-- SDK Settings -->
<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="18" />

<!-- APP Start -->
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

<!-- App Activity -->
    <activity
        android:name="com.example.project.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

<!-- Library Activity -->
    <activity android:name="com.example.lib.MainActivity" android:label="LibMain">
         <intent-filter>
        <action android:name="android.intent.action.MAIN"></action>
     </intent-filter>
    </activity>

</application>
<!-- END - APP -->

</manifest>

What am I overlooking? Any suggestions?

EDIT

I updated the manifest.xml with all other activities & somehow, that resolved the problem. The intent activity starts up without any errors. BUT, this is only on AVD. On actual device, it is still throwing same error. I have uninstalled the app from device completely and reinstalled, yet the same error.

В этом руководстве мы покажем вам, как исправить ошибку «Операция не разрешена: java.lang.SecurityException» при выполнении команды ADB Shell. Возможности безграничны, когда дело доходит до входа в домены ADB и Fastboot. В то время как команды Fastboot в основном пригодятся, когда загрузчик вашего устройства разблокирован или имеет root-права, это не относится к ADB, поскольку вы также можете извлечь максимальный потенциал этих команд в стандартной среде.

Более того, с добавлением команд оболочки adb вы даже можете выполнять некоторые задачи административного уровня на своем устройстве без рута. Однако в последнее время использование этих команд оказалось крепким орешком. Многие пользователи выразили обеспокоенность тем, что всякий раз, когда они выполняют команду оболочки ADB, вместо этого они получают сообщение «Операция не разрешена: ошибка java.lang.SecurityException».

Операция оболочки ADB не разрешена java.lang.SecurityException

Интересно отметить тот факт, что ПК может идентифицировать устройство в режиме ADB, так как при выполнении команды adb devices CMD перечисляет серийный номер устройства. Более того, даже команда оболочки adb работает хорошо и хорошо, так как она выводит кодовое имя устройства. Однако любая команда, которую вы выполните после этого, приведет к вышеупомянутой ошибке. С учетом сказанного существует несколько отличных обходных путей, которые помогут вам устранить эту ошибку. Итак, без лишних слов, давайте проверим их.

Операция оболочки ADB не разрешена java.lang.SecurityException

Прежде чем приступить к исправлениям, мы рекомендуем вам сначала отметить следующие предварительные условия. [if not done already]:

Предпосылки

Если ваше устройство соответствует всем этим требованиям, выполните следующие действия, чтобы исправить ошибку «Операция ADB Shell не разрешена: ошибка java.lang.SecurityException».

Исправление для устройств Xiaomi

  1. Перейдите в «Настройки»> «Дополнительные настройки»> «Параметры разработчика».
  2. Затем включите переключатель рядом со следующими тремя параметрами: Отладка по USB Отладка по USB (параметры безопасности) Установить через USB

    Операция оболочки ADB не разрешена java.lang.SecurityException

  3. Теперь повторите попытку выполнения команды оболочки adb, вы больше не получите никаких ошибок.

Исправление для OnePlus, Oppo, Realme

  1. Перейдите в «Настройки»> «Системные настройки»> «Параметры разработчика».
  2. Затем отключите отладку по USB. После этого включите переключатель рядом с «Отключить мониторинг разрешений».Операция оболочки ADB не разрешена java.lang.SecurityException
  3. Теперь снова включите отладку по USB и выполните команду оболочки adb, ошибок быть не должно.

Вот и все. Это были шаги по исправлению операции, которая не разрешена: ошибка java.lang.SecurityException при выполнении команды ADB Shell. Если у вас есть какие-либо вопросы относительно вышеупомянутых шагов, сообщите нам об этом в комментариях. Мы вернемся к вам с решением в ближайшее время.

In this guide, we will show you the steps to fix the Operation not allowed: java.lang.SecurityException error while executing the ADB Shell command. The possibilities stand endless when it comes to stepping into the ADB and Fastboot domains. While Fastboot commands mostly come in handy when your device’s bootloader is unlocked or is rooted, that isn’t the case with ADB as you could extract the maximum potential of these commands in a stock environment as well.

Moreover, with the addition of adb shell commands, you could even carry out some administrative-level tasks on your non-rooted device. However, as of late, using these commands is proving to be a tough nut to crack. Numerous users have voiced their concern that whenever they execute an ADB shell command, they instead get greeted with the Operation not allowed: java.lang.SecurityException error.

ADB Shell Operation not allowed java.lang.SecurityException

What is interesting to note is the fact that the PC could identify the device in the ADB Mode, as upon executing the adb devices command, the CMD list out the serial number of the device. Moreover, even the adb shell command works well and good, as it will list out the device codename. However, any command that you execute after that will result in the aforementioned error. With that said, there does exist a couple of nifty workarounds that shall help you resolve this bug. So without further ado, let’s check them out.

ADB Shell Operation not allowed java.lang.SecurityException

Before starting with the fixes, we would recommend you checkmark the following prerequisites first [if not done already]:

The Prerequisites

If your device qualify all these requirements, then proceed ahead with the below methods to fix the ADB Shell Operation not allowed: java.lang.SecurityException error.

Fix for Xiaomi Devices

  1. Head over to Settings > Additional Settings > Developer Options.
  2. Then enable the toggle next to the following three options:
    USB Debugging
    USB Debugging (Security Settings)
    Install via USB

    ADB Shell Operation not allowed java.lang.SecurityException

  3. Now retry executing the adb shell command, you will no longer get any errors.

Fix for OnePlus, Oppo, Realme

  1. Head over to Settings > System Settings > Developer Options
  2. Then disable USB Debugging. After that, enable the toggle next to “Disable Permission Monitoring”.ADB Shell Operation not allowed java.lang.SecurityException
  3. Now re-enable USB Debugging and execute the adb shell command, there should be no errors.

That’s it. These were the steps to fix the Operation not allowed: java.lang.SecurityException error while executing the ADB Shell command. If you have any queries concerning the aforementioned steps, do let us know in the comments. We will get back to you with a solution at the earliest.


  • ADB is not recognized as the name of a cmdlet: How to Fix
  • AdbWinApi.dll is Missing Error on Windows 10/11: How to Fix
  • How to Downgrade a System/User App on Android
  • How to Change Refresh Rate in Android via ADB Commands

About Chief Editor

Sadique Hassan

administrator

A technical geek by birth, he always has a keen interest in the Android platform right since the birth of the HTC Dream. The open-source environment always seems to intrigue him with the plethora of options available at his fingertips. “MBA by profession, blogger by choice!”

I have an android application that i need to receive sms and I found a certain tutorial that teaches how to do that but when I run it & I get android permission exception

FATAL EXCEPTION: main
Process: androidreceivesms.javapapers.com.smsbroadcastreceiver, PID:
12206
java.lang.RuntimeException: Unable to start activity
ComponentInfo{androidreceivesms.javapapers.com.smsbroadcastreceiver/androidreceivesms.javapapers.com.smsbroadcastreceiver.SmsActivity}:
java.lang.SecurityException: Permission Denial: reading
com.android.providers.telephony.SmsProvider uri content://sms/inbox
from pid=12206, uid=10061 requires android.permission.READ_SMS, or
grantUriPermission()
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.SecurityException: Permission Denial: reading
com.android.providers.telephony.SmsProvider uri content://sms/inbox
from pid=12206, uid=10061 requires android.permission.READ_SMS, or
grantUriPermission()
at android.os.Parcel.readException(Parcel.java:1599)
at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at
android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
at android.content.ContentResolver.query(ContentResolver.java:491)
at android.content.ContentResolver.query(ContentResolver.java:434)
at
androidreceivesms.javapapers.com.smsbroadcastreceiver.SmsActivity.refreshSmsInbox(SmsActivity.java:52)
at
androidreceivesms.javapapers.com.smsbroadcastreceiver.SmsActivity.onCreate(SmsActivity.java:47)
at android.app.Activity.performCreate(Activity.java:6237)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Here is my AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SmsActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".SmsBroadcastReceiver" android:exported="true" >
        <intent-filter android:priority="999" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>

Here is my SmsActivity.java

public class SmsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

private static SmsActivity inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;

public static SmsActivity instance() {
    return inst;
}

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sms);
    smsListView = (ListView) findViewById(R.id.SMSList);
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
    smsListView.setAdapter(arrayAdapter);
    smsListView.setOnItemClickListener(this);

    refreshSmsInbox();
}

public void refreshSmsInbox() {
    ContentResolver contentResolver = getContentResolver();
    Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
    int indexBody = smsInboxCursor.getColumnIndex("body");
    int indexAddress = smsInboxCursor.getColumnIndex("address");
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
    arrayAdapter.clear();
    do {
        String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                "n" + smsInboxCursor.getString(indexBody) + "n";
        arrayAdapter.add(str);
    } while (smsInboxCursor.moveToNext());
}

public void updateList(final String smsMessage) {
    arrayAdapter.insert(smsMessage, 0);
    arrayAdapter.notifyDataSetChanged();
}

public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
    try {
        String[] smsMessages = smsMessagesList.get(pos).split("n");
        String address = smsMessages[0];
        String smsMessage = "";
        for (int i = 1; i < smsMessages.length; ++i) {
            smsMessage += smsMessages[i];
        }

        String smsMessageStr = address + "n";
        smsMessageStr += smsMessage;
        Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Here is my SmsBroadcastReceiver.java

public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";

public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

            String smsBody = smsMessage.getMessageBody().toString();
            String address = smsMessage.getOriginatingAddress();

            smsMessageStr += "SMS From: " + address + "n";
            smsMessageStr += smsBody + "n";
        }
        Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

        //this will update the UI with message
        SmsActivity inst = SmsActivity.instance();
        inst.updateList(smsMessageStr);
    }
}

}

Can anyone please help me because i have been stack here for a long time now? Any help will be appreciated thanks

Solution 1

The issue was with Launcher selection in Android Studio. To improve testing speed of application module there was selected other Activity as Launcher(in run properties) than specified in manifest.xml. Strange that it worked even on emulator..

The solution is simply to change the Launcher to the one set in AndroidManifest.xml

Solution 2

Simply add:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

on AndroidManifest.xml into the tag:

<activity>

Hope it helps

Comments

  • There is an error launching activity, unfortunately I assume it is not connected strictly with the project due to the fact the app launches on genymotion emulator, but does not on physical device.

    When I run adb devices with the real one connected i get:

    List of devices attached 
    0009215b1eef4f  device
    

    AndroidManifest.xml has not any permissions required set and device has sufficient api version.

    Regards

Recents

Возможно, вам также будет интересно:

  • Java lang numberformatexception ошибка
  • Java lang nullpointerexception ошибка как исправить на телефоне
  • Jinn client ошибка создания com объекта общиймодуль электроннаяподписьjinnклиентсервер модуль 50
  • Jinn client ошибка создания com объекта общий модуль электронная подпись
  • Jinn client ошибка проверки лицензионного ключа

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии