Android NDK編程實現終端功能(調用system函數)

來源:互聯網
上載者:User

原文地址::http://leo108.com/pid-597.asp

 

 

本程式能夠實現在android中利用system函數執行命令,並將執行結果輸出到指定的檔案中。
核心代碼:
hello-jni.c複製代碼

  1. #include <jni.h>
  2. #include <string.h>
  3. JNIEXPORT jstring Java_com_example_hellojni_HelloJni_system(JNIEnv* env,jobject thiz, jstring str , jstring path)
  4. {
  5. const jbyte* p1 = (*env)->GetStringUTFChars(env , str, NULL);
  6. const jbyte* p2 = (*env)->GetStringUTFChars(env , path, NULL);
  7. char* str2=(char *)p1;
  8. char* path2=(char *)p2;
  9. strcat(str2," > ");
  10. strcat(str2,path2);
  11. system(str2);
  12. return(*env)->NewStringUTF(env,str2);
  13. }

HelloJni.java 複製代碼

  1. package com.example.hellojni;
  2. import android.app.Activity;
  3. import android.widget.TextView;
  4. import android.os.Bundle;
  5. public class HelloJni extends Activity
  6. {
  7. /** Called when the activity is first created. */
  8. @Override
  9. public void onCreate(Bundle savedInstanceState)
  10. {
  11. super.onCreate(savedInstanceState);
  12. TextView tv = new TextView(this);
  13. tv.setText(system("ls","\"/mnt/sdcard/hello.txt\"") );//這裡的第一個參數是要執行的命令,第二個參數是要輸出的檔案路徑
  14. setContentView(tv);
  15. }
  16. public native String system(String str ,String path);
  17. static {
  18. System.loadLibrary("hello-jni");
  19. }
  20. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.