In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian for you to introduce in detail "Android server how to achieve so file call", the content is detailed, the steps are clear, the details are handled properly, I hope that this "Android server how to achieve so file call" article can help you solve your doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.
With the rapid development of Android mobile security, no matter for the sake of execution efficiency or program security, the sinking of key code in native layer has become a basic operation.
The development of native layer is the general JNI/NDK development. Through JNI, we can realize the mutual call between java layer and native layer (mainly native +). The native layer produces so dynamic link library after compilation. So files have the advantages of wide portability, high execution efficiency, strong confidentiality and so on.
So the problem is, how to call the so file is extremely important, of course, you can also directly analyze the pseudo code of the so file, using strong programming skills to directly simulate key operations, but I think hair is still more important for ordinary people.
The current mainstream operation for invoking so files should be:
1, various implementations based on Unicorn (still in learning, not listed for the time being)
2 the construction of Android server, and complete the requirement of calling so from http service in App (of course, only if the so verification and other operations are performed)
As for why I chose AndServer, well, I don't know why, just because I found it.
Why combine Service, learn about the life cycle of Service when learning Android development, and personally understand that it is better to use Service to create Http services.
Of course, there is also a simple use of Application, because in the formal environment, the logic of most so documents have some context package names, signed validation, and so on. If you customize Application, you can get context parameters.
Introduction to libyemu.so
This is a so file I compiled, which is to do a simple string concatenation according to the input parameters (the following is the pre-compiled c code of the native layer)
Extern "C" JNIEXPORT jstring JNICALLJava_com_fw_myapplication_ndktest_NdkTest_stringFromUTF (JNIEnv * env, jobject instance, jstring str_) {jclass String_clazz = env- > FindClass ("java/lang/String"); jmethodID concat_methodID = env- > GetMethodID (String_clazz, "concat", "(Ljava/lang/String;) Ljava/lang/String;"); jstring str = env- > NewStringUTF ("from so-[NightTeam Night]") Jobject str1 = env- > CallObjectMethod (str_, concat_methodID, str); const char * chars = env- > GetStringUTFChars ((jstring) str1, 0); return env- > NewStringUTF (chars);}
It is necessary to post this part of the code. Simple static registration uses the idea of reflection, which is very important in reverse.
Next is the java code, which defines the native function
Package com.fw.myapplication.ndktest;public class NdkTest {public static native String stringFromUTF (String str); static {System.loadLibrary ("yemu");}}
If you are a little confused here, you may need to make up the foundation of Android development.
Android Project Test so
Let's talk about my environment first, because the impact of this environment is too great.
1,AndroidStudio 3.4
2, Mobile Android 6 architecture armeabi-v7a
Open AndroidStudio New project
Cdn.nlark.com/yuque/0/2020/webp/97322/1607479407035-f0bfc349-9792-4b75 microbe4bcopyright 0b2c52f2cabc.webpendxwashossW1pY3JvaGVpgradtypewritten d3F5LW1pY3JvaGVpGrade10 textbooks Gl0b2RhdGEuY29tcoloring FFFFF shadowbooks 50 minutes 80 moment glossary xbooks 10 references 10 ">
Add this sentence to module's build, and then sync
Copy the compiled so file to the libs folder (corresponding to the jniLibs.srcDirs just now)
Copy the java code corresponding to so, and pay attention to the consistency of package name and class name.
Open the activity_main.xml file to add an id for TextView
Open MainActiviy.java to start coding
What these two lines mean is to first find the TextView of the corresponding id from the layout, and then set the Text for it (the return value of calling the native function)
Let's test our so call.
You can see that our so file is called successfully (here our so is not validated, just to test whether app can be called normally)
AndServer code writing
AndServer official document: https://yanzhenjie.com/AndServer/
Open the official document, see other people's introduction, create a new java file
For example, the C of the classic MVC is written, and a nightteam_sign interface is defined, the request method is get, the request parameter is sign, the native function is called, and then json is returned. But here I want to use Application to get the context object, take down the package name, and then customize the Applictaion.
Package com.nightteam.httpso;import android.app.Application;public class MyApp extends Application {private static MyApp myApp; public static MyApp getInstance () {return myApp;} @ Override public void onCreate () {super.onCreate (); myApp = this;}}
Then specify the Application to start in the manifest file
Then modify the code of MyController.java
Next, copy the code of the official document-server.
Import some packages and modify some of the code as follows
The new version of AndServer.serverBuilder already needs to pass context. Here, the network address and port number are also modified to be obtained from the construction parameters. Here, the AndServer is basically finished. In fact, we build an interface to call so without too much business logic, so the code is the easiest to use.
Service code writing
Here we start Service with the click event of the button, so add a button to the activity_main.xml and specify the click event
Next, write custom Service code
Package com.nightteam.httpso.Service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import com.nightteam.httpso.ServerManager;import java.net.InetAddress;import java.net.UnknownHostException;public class MyService extends Service {private static final String TAG = "NigthTeam"; @ Override public void onCreate () {super.onCreate (); Log.d (TAG, "onCreate: MyService") New Thread () {@ Override public void run () {super.run (); InetAddress inetAddress = null; try {inetAddress = InetAddress.getByName ("0.0.0.0"); Log.d (TAG, "onCreate:" + inetAddress.getHostAddress ()) ServerManager serverManager = new ServerManager (getApplicationContext (), inetAddress, 8005); serverManager.startServer ();} catch (UnknownHostException e) {e.printStackTrace ();} .start ();} @ Override public IBinder onBind (Intent intent) {return null;}}
Start the AndServer service in the child thread with several log (when using UI thread and child thread is the basis of Android, which will not be discussed here)
Note that here you get inetAddress from 0.0.0.0, but don't make a mistake. The difference between localhost and 0.0.0.0 is the search engine.
Then the context,inetAddress,port is passed to the constructor of ServerManager to use the new object, and then the service is opened
Finally, check the declaration of Service in the manifest file.
Open Service and get the native ip
Go back to the operate of our MainActivity.java (the click event of button) and write the startup Service code
Public void operate (View view) {switch (view.getId ()) {case R.id.id_bt_index: / / start the service: create-> start-> destroy / / if the service has been created and started repeatedly later, the operation is the same service and will not be re-created Unless you destroy it first Intent it1 = new Intent (this, MyService.class) Log.d (TAG, "operate: button"); startService (it1); ((Button) view) .setText ("Service enabled"); break;}}
Our service is basically set up here, but for convenience, I want to display our native ip on App so that we don't have to set it up and check it again.
I found a tool class to obtain the ip address on the Internet, the source code is as follows:
Package com.nightteam.httpso;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import java.util.regex.Pattern Public class NetUtils {private static final Pattern IPV4_PATTERN = Pattern.compile ("^ (" + "([0-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [0-4] [0-9] | 25 [0-5])\.) {3}" + "([0-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [0-9]) 4] [0-9] | 25 [0-5]) $") Private static boolean isIPv4Address (String input) {return IPV4_PATTERN.matcher (input). Matches ();} / / get the native IP address public static InetAddress getLocalIPAddress () {Enumeration enumeration = null; try {enumeration = NetworkInterface.getNetworkInterfaces ();} catch (SocketException e) {e.printStackTrace () } if (enumeration! = null) {while (enumeration.hasMoreElements ()) {NetworkInterface nif = enumeration.nextElement (); Enumeration inetAddresses = nif.getInetAddresses (); if (inetAddresses! = null) while (inetAddresses.hasMoreElements ()) {InetAddress inetAddress = inetAddresses.nextElement () If (! inetAddress.isLoopbackAddress () & isIPv4Address (inetAddress.getHostAddress () {return inetAddress;} return null;}}
Add the utility class copy to our Android project and continue to code in MainActivity.java
Get the local address and Android SDK version (different ways to start Service after Android 8)
Apply for permission to start App
The last step is to apply for network permission for app.
Then connect to our mobile phone, run the project, test it, and click to start the service.
Check the AndroidStudio log.
Everything seems to be fine, try it under browser access (ip is the ip address shown in App)
As shown in the picture, we have normal access to what we want.
Going back to Service, open the settings of our phones and find the application management-running services (different phones, different ways)
You can see that our program runs a service, which is the MyService we coded.
Then kill the App process and view the running service again
Read here, this "Android server how to achieve so file call" article has been introduced, want to master the knowledge of this article also need to practice and use in order to understand, if you want to know more about the article, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.