当前位置: 首页 > 知识库问答 >
问题:

如何使用JNI实现对otg的文件操作?

司徒运锋
2023-03-14

我需要对连接到Android手机的 USB 设备执行文件操作。权限应由 android java 代码授予,文件操作应使用 JNI 执行。目前我无法授予执行文件操作的权限 - 我收到 EACCESS:权限被拒绝错误

我在这里附上了我的代码:

public class MainActivity extends AppCompatActivity {

private UsbAccessory accessory;
private String TAG = "TAG";
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private PendingIntent mPermissionIntent;
private UsbManager manager;
private UsbDeviceConnection connection;
private HashMap<Integer, Integer> connectedDevices;
TextView tv;



// Used to load the 'native-lib' library on application startup.
static {
    System.loadLibrary("native-lib");
}

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

    // Example of a call to a native method
    tv = (TextView) findViewById(R.id.sample_text);
   // tv.setText(stringFromJNI());

    connectedDevices = new HashMap<Integer, Integer>();

    manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(ACTION_USB_PERMISSION));

    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    /*String str = ndkopenfile();
    tv.setText(str);*/

    final Handler handler = new Handler();

    handler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            checkForDevices();
        }
    }, 1000);
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */

//public native String stringFromJNI();

@Override
public void onDestroy()
{
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
}

// private static native void notifyDeviceAttached(int fd);
 //private static native void notifyDeviceDetached(int fd);

public  native String ndkopenfile();

private final BroadcastReceiver usbManagerBroadcastReceiver = new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent)
    {
        try
        {
            String action = intent.getAction();

            Log.d(TAG, "INTENT ACTION: " + action);

            if (ACTION_USB_PERMISSION.equals(action))
            {
                Log.d(TAG, "onUsbPermission");

                synchronized (this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                    {
                        if(device != null)
                        {


                          /*  int fd = connectToDevice(device);
                            Log.d(TAG,"device file descriptor: " + fd);
                           // notifyDeviceAttached(fd);
                            String str = ndkopenfile();
                            tv.setText(str);*/

                          writetofile();
                        }
                    }
                    else
                    {
                        Log.d(TAG, "permission denied for device " + device);
                    }
                }
            }

            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action))
            {
                Log.d(TAG, "onDeviceConnected");

                synchronized(this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (device != null)
                    {
                        manager.requestPermission(device, mPermissionIntent);
                    }
                }
            }

            if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {
                Log.d(TAG, "onDeviceDisconnected");

                synchronized(this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    int fd = connectedDevices.get(device.getDeviceId());

                    Log.d(TAG, "device: " + device.getDeviceId() + " disconnected. fd: " + fd);

                   // notifyDeviceDetached(fd);

                    connectedDevices.remove(device.getDeviceId());
                }
            }
        }
        catch(Exception e)
        {
            Log.d(TAG, "Exception: " + e);
        }
    }


};

private void writetofile() {

   // File file = new File("/storage/9E6D-8A07/COMMWR");

    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("/storage/9E6D-8A07/COMMWR", Context.MODE_PRIVATE));
        outputStreamWriter.write("Hello");
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

}

private int connectToDevice(UsbDevice device)
{
    connection = manager.openDevice(device);
    // if we make this, kernel driver will be disconnected
    connection.claimInterface(device.getInterface(0), true);

    Log.d(TAG, "inserting device with id: " + device.getDeviceId() + " and file descriptor: " + connection.getFileDescriptor());
    connectedDevices.put(device.getDeviceId(), connection.getFileDescriptor());

    return connection.getFileDescriptor();
}

private void checkForDevices()
{
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

    while(deviceIterator.hasNext())
    {
        UsbDevice device = deviceIterator.next();

           /* if (device.getVendorId()==VID && device.getProductId()==PID)
            {
                Log.d(TAG, "Found a device: " + device);

                manager.requestPermission(device, mPermissionIntent);
            }*/

        Log.d(TAG, "Found a device: " + device);

        manager.requestPermission(device, mPermissionIntent);
    }
}

}

JNI代码:

#include <jni.h>
#include <string.h>
#include <stdio.h>

extern "C"
JNIEXPORT jstring JNICALL
Java_nrrsmdm_com_myapplication_MainActivity_ndkopenfile
        (JNIEnv *env, jobject obj)
{
    int errno = 0;
    char myStr[20];
    FILE* fp = fopen("/storage/9E6D-8A07/COMMWR","w+");
    if(fp!=NULL)
    {
        fputs("HELLO WORLD!\n", fp);
        fflush(fp);
        fclose(fp);
        return env->NewStringUTF(myStr);
    }
    else
    { sprintf("error","errno = %d",errno);
        fclose(fp);
        return env->NewStringUTF("Error opening file!");
    }

   /* std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());*/


}

共有1个答案

丰智
2023-03-14

尝试将权限添加到清单:

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

要支持marshm

public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

权限结果回调:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}
 类似资料:
  • 问题内容: 我需要使用NDK以及JNI将一些功能实现到Android应用程序中。 这是我所写的C代码: 我的问题或多或少在代码内得到了解释。也许还可以:函数(jobject)的返回类型可以吗? 现在,NDKTest.java: 当我尝试运行代码时,它不起作用。 问题答案: 既然是内部类,那么获得它的方法就是 内部类的约定在权威规范中并未真正明确记录,但是根深蒂固地存在于如此多的工作代码中,因此不太

  • 本文向大家介绍python实现操作文件(文件夹),包括了python实现操作文件(文件夹)的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了pyhton操作文件的具体代码,供大家参考,具体内容如下 copy_file 功能:将某个文件夹下的所有文件(文件夹)复制到另一个文件夹 zip_file 功能:将某个文件夹下面的所有文件(文件夹)压缩 del_file 功能:将某个文件夹下面的所

  • 从API 21(Lollipop)开始,应用程序可以获得修改真实SD卡的特殊权限,如我写的历史发文所示(这里和这里)。 我可以删除文件,也可以创建文件,但我找不到执行其他基本文件操作的方法: 读,写,使用InputStream和OutputStream 移动文件。 创建一个文件夹而不仅仅是一个文件 重命名文件 获取文件信息(最近更新等) 通过其他应用程序共享/打开文件。 其他行动我可能已经忘记了。

  • 如何使用php实现fusionstorage 对象存储文件上传? php实现fusionstorage 对象存储文件上传

  • 本文向大家介绍Vim如何使用相对行号实现一切操作详解,包括了Vim如何使用相对行号实现一切操作详解的使用技巧和注意事项,需要的朋友参考一下 前言 大家都知道,我们使用Vim的一点好处就是,可定制性非常高,如果遇到任何让自己感到不适的痛点,都可以通过配置甚至开发一款插件来解决。开始使用Vim一段时间之后,我发现一个非常“反人类”的地方:Vim的很多命令都是需要查行数的。比如“删除一个函数体”,你就要

  • 本文向大家介绍C#实现的Excel文件操作类实例,包括了C#实现的Excel文件操作类实例的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了C#实现的Excel文件操作类。分享给大家供大家参考,具体如下: 更多关于C#相关内容感兴趣的读者可查看本站专题:《C#操作Excel技巧总结》、《C#程序设计之线程使用技巧总结》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构