Reprint Please specify source: http://blog.csdn.net/yyh352091626/article/details/50542554
Development of a need to live in the background of the app is actually a very headache, not only to deal with the major domestic manufacturers of ROM, but also need to deal with various types of security butler ... Although the continuous study of various methods, but the effect is not good, such as the task Manager to kill the app, service will not come up ...
After searching online, the main methods are the following methods, but they are not a cure for the symptoms:
1, Improve service priority: this, can only be said in the system memory needs to reclaim resources, high priority, not easy to be recycled, and then eggs ...
2, improve the service process priority: the effect is not very obvious
3, restart the service in the OnDestroy method: This is quite effective a method, but, directly kill the process, the OnDestroy method will not come in, and do not want to restart the
4, broadcast broadcast: And the 3rd kind, did not enter OnDestroy, do not know when to broadcast, in addition, in Android4.4 above, the program completely quit, it is not good to receive the broadcast, need to broadcast the local specific processing
5, put under the System/app as a system application: This is the usual play, not much practical significance.
6, the service's Onstartcommand method, returns the Start_sticky, this also mainly is for the system resources insufficient and causes the services to be closed, still has the certain reason.
The way to deal with it is that it is more cumbersome to implement. If you can customize the ROM yourself, there are a number of options, such as adding your app to the whitelist, or installing an app with no icons as a daemon ... However, where everything is customized, for Android developers, this challenge must be compromised ~
Then, there is no way in an app, open a sub-thread, after the main thread has been killed, the child thread through the monitoring, polling, and other ways to determine whether the service exists, does not exist to open the service. The answer is naturally yes, by means of JNI (NDK programming), fork () out a sub-thread as a daemon, polling the state of the listener service. A daemon (Daemon) is a special process that runs in the background. It is independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. The file descriptor is independent of the session group and current directory of the daemon. Running in the background is just a fork in the terminal that allows the program to execute in the background, none of these changes.
Then we first look at Android4.4 source code, Activitymanagerservice (source/frameworks/base/services/core/java/com/android/server/am/ Activitymanagerservice.java) is how to turn off cleanup of memory after an app exits:
Process.killprocessquiet (PID);
After the application exits, Activitymanagerservice kills the main process, but in Android5.0, the activitymanagerservice is handled like this:
Process.killprocessquiet (APP.PID); Process.killprocessgroup (App.info.uid, app.pid);
It's a bad word, but it's a big difference. Android5.0 after the application exits, Activitymanagerservice not only kills the main process, but also kills the process group that the main process belongs to, so that as the child process and the main process are in the same process group, the child process is stopped ... Otherwise, Android5.0 has done a lot of updates on security.
Then, there is no way to let the child process out, not to be affected by the main process, of course, is also possible. So how do you do it in the C/s + + layer? First on the key code:
/** * srvname Process name * SD before creating a child process PID write file path */int start (int argc, char* srvname, char* SD) {pthread_t id;int ret;struct Rli MIT r;int pid = fork (); Logi ("Fork pid:%d", PID), if (PID < 0) {Logi ("First fork () error PID%d,so exit", PID); exit (0);} else if (pid! = 0) {LO GI ("First fork (): I ' am Father pid=%d", Getpid ());//exit (0);} else {//First sub-process Logi ("Primary fork (): I ' am Child pid=%d", Getpid ()); Setsid (); Logi ("First fork (): setsid=%d", Setsid ()); umask (0); Give the file more permissions because the inherited file may have some permissions that are masked by the int pid = fork (), if (PID = = 0) {///second sub-process)//This is actually to prevent the re-opening of the thread, should have the corresponding processing logi ("I am child-child pid=%d ", Getpid ()); ChDir ("/"); <span style= "font-family:arial, Helvetica, Sans-serif;" > Modify the process working directory to the root directory, chdir ("/") </span>//close the unwanted file descriptor inherited from the parent process. if (R.rlim_max = = rlim_infinity) {R.rlim_max = 1024;} int i;for (i = 0; i < R.rlim_max; i++) {Close (i);} Umask (0); ret = Pthread_create (&id, NULL, (void *) thread, srvname); Open thread, poll to listen for startup service if (ret! = 0) {printf ("Create pthread error!\n"); exit (1);} int STDFD = opEn ("/dev/null", O_RDWR);d up2 (STDFD, Stdout_fileno);d up2 (STDFD, Stderr_fileno);} else {exit (0);}} return 0;} /** * Start service */void java_com_yyh_fork_nativeruntime_startservice (jnienv* env, Jobject thiz,jstring cchrptr_ ProcessName, jstring sdpath) {char * RTN = jstringtostring (env, cchrptr_processname);//Get Process name char * SD = jstringtostring (env, Sdpath); Logi ("Java_com_yyh_fork_nativeruntime_startservice run ....") Processname:%s ", RTN); a = Rtn;start (1, RTN, SD);}Here are a few key points to understand:
1, why fork two times? The function of the first fork is to serve the back setsid. The Setsid caller cannot be the process group leader (group leader), while the parent process is the leader of the process group the first time it is called. After the second call, the previous fork out of the sub-process, so that the second fork out of the sub-process, and they are out of the relationship.
2. What is the role of Setsid ()? Setsid () enables the second subprocess to be the conversation leader (Sid==pid), and also the process group leader (Pgid = = pid), and is detached from the original control terminal. Therefore, regardless of the control terminal How to operate, the new process normally will not receive the signals he sent.
3, the role of Umask (0): Because the child process inherits from the parent process some things, may not have inherited permissions, so to give him higher privileges, convenient for child process operation.
4, ChDir ("/"); role: When the process activity, its working directory is located in the file system can not be removed, it is generally necessary to change the working directory to the root directory.
5. The process inherits the open file descriptor from the parent process that created it. Without shutting down, system resources will be wasted, causing the file system where the process is located to fail to unload and cause unexpected errors. So in the end, remember to close down the file descriptor inherited from the parent process.
Then, in the above code to open the thread after the thing, is to loop to StartService (), the code is as follows:
void thread ( Char* srvname) {while (1) {check_and_restart_service (srvname);//should be to judge the service status, here has been restart is insufficient sleep (4);}} /** * Detection service, boot if no service exists. * Start a laucher service through the AM command, the Laucher service is responsible for the detection of the main service, Laucher service automatically exits after detection */void check_and_restart_service (char* service) {Logi ( "Current Process pid=", getpid ()), Char cmdline[200];sprintf (cmdline, "AM startservice--user 0-n%s", service); Char tmp[200]; sprintf (tmp, "cmd=%s", cmdline); Executecommandwithpopen (CmdLine, TMP, 200); Logi (TMP, LOG);} /** * Execute command */void executecommandwithpopen (char* command, char* out_result,int resultbuffersize) {FILE * fp;out_result[res UltBufferSize-1] = ' + '; fp = popen (Command, "R"); if (FP) {fgets (Out_result, resultBufferSize-1, FP); OUT_RESULT[RESULTB UfferSize-1] = ';p close (FP);} else {logi ("Popen null,so exit"); exit (0);}}
The two functions that start the service, which involve some Android and Linux commands, I will not elaborate here. Especially am, very powerful function, not only can open the service, can also open the radio and so on ... Then call the Ndk-build command to compile, generate so library, NDK will not, self-Baidu slightly ~
The key part of the C + + end is the above, and naturally, the Java side has to cooperate with the execution.
First, take a look at the load classes of so libraries compiled by C + + code, and the native call:
Package Com.yyh.fork;import Java.io.datainputstream;import Java.io.dataoutputstream;import java.io.File;public Class Nativeruntime {private static Nativeruntime theinstance = Null;private nativeruntime () {}public static Nativeruntim e getinstance () {if (theinstance = = null) Theinstance = new Nativeruntime (); return theinstance;} /** * runexecutable to start a self-lib*.so file * @date 2016-1-18 pm 8:22:28 * @param pacaagename * @param filename * @param alias alias * @param args parameter * @return */public string runexecutable (String pacaagename, string filename, string alias, String args) {String Path = "/data/data/" + pacaagename; String cmd1 = path + "/lib/" + filename; String cmd2 = path + "/" + alias; String cmd2_a1 = path + "/" + alias + "+ args; String cmd3 = "chmod 777" + cmd2; String CMD4 = "dd if=" + cmd1 + "of=" + cmd2; StringBuffer Sb_result = new StringBuffer (), if (!new File ("/data/data/" + alias). Exists ()) {Runlocalusercommand ( Pacaagename, CMD4, Sb_result); Copy lib/libtest.so to the previous directory, and also named Test.sb_reSult.append (";");} Runlocalusercommand (Pacaagename, Cmd3, Sb_result); Change the properties of test to make it executable sb_result.append (";"); Runlocalusercommand (Pacaagename, CMD2_A1, Sb_result); Execute the test program. Sb_result.append (";"); return sb_result.tostring ();} /** * Execute local User command * @date 2016-1-18 pm 8:23:01 * @param pacaagename * @param command * @param sb_out_result * @return */public Boolean Runlocalusercommand (String pacaagename, String command, StringBuffer sb_out_result) {Process process = Null;try { Process = Runtime.getruntime (). EXEC ("sh"); Get shell process DataInputStream InputStream = new DataInputStream (Process.getinputstream ());D Ataoutputstream OutputStream = new DataOutputStream (Process.getoutputstream ()); Outputstream.writebytes ("cd/data/data/" + Pacaagename + "\ n"); Ensure that the command is executed in its own data directory to have permission to write files to the current directory outputstream.writebytes (Command + "&\n"); Let the program run in the background, the front desk immediately return to Outputstream.writebytes ("exit\n"); Outputstream.flush ();p rocess.waitfor (); byte[] buffer = new byte [Inputstream.available ()];inputstream.read (buffer); String s = new String (buffer), if (sb_out_result! = null) sb_out_result.append ("CMD result:\n" + s);} catch (Exception e) {if (Sb_out_result! = null) sb_out_result.append ("Exception:" + e.getmessage ()); return false;} return true;} public native void StartActivity (string compname);p ublic native String stringfromjni ();p ublic native void StartService ( String srvname, String sdpath);p ublic native int findprocess (string packname);p ublic native int stopservice (); static {try {system.loadlibrary ("helper");//load So library} catch (Exception e) {e.printstacktrace ();}}}Then, we start the service after receiving the power-on broadcast.
Package Com.yyh.activity;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.util.log;import Com.yyh.fork.nativeruntime;import com.yyh.utils.FileUtils; public class Phonestatreceiver extends Broadcastreceiver {private String tag = "tag"; @Overridepublic void OnReceive (Conte XT context, Intent Intent) {if (Intent.ACTION_BOOT_COMPLETED.equals (Intent.getaction ())) {log.i (TAG, "Phone powered on ~ ~"); Nativeruntime.getinstance (). StartService (Context.getpackagename () + "/com.yyh.service.hostmonitor", Fileutils.createrootpath ());} else if (Intent.ACTION_USER_PRESENT.equals (Intent.getaction ())) {}}}
Service, you can do what you need to do.
Package Com.yyh.service;import Android.app.service;import Android.content.intent;import android.os.IBinder;import Android.util.log;public class Hostmonitor extends Service {@Overridepublic void OnCreate () {super.oncreate (); LOG.I ("Daemon_java", "hostmonitor:oncreate! I can not be killed! ");} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {log.i ("Daemon_java", "Hostmonitor: onstartcommand! I can not be killed! "); Return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic ibinder onbind (Intent arg0) {return null;}}
Of course, don't forget to configure receiver and service in the Manifest.xml file:
<receiver android:name= "com.yyh.activity.PhoneStatReceiver" android:enabled= "true" Android: permission= "Android.permission.RECEIVE_BOOT_COMPLETED" > <intent-filter> <action android: Name= "Android.intent.action.BOOT_COMPLETED"/> <action android:name= "android.intent.action.USER_ PRESENT "/> </intent-filter> </receiver> <service android:name=" Com.yyh.service.HostMonitor " android:enabled=" true " android:exported=" true "> </service >
Run up, in the program application inside, the end of this process, will be, and automatically up ~ ~ ~ ~ with the rogue software like, yes, it is so cheap, is so overbearing!!
This side is running on Google native system, Android version is 5.0 ... To sum up: Service resident should not deal with all kinds of difficult technology, but the big ROM. QQ Why not be killed, is because the domestic big ROM don't want to let him die ...
This article is mainly to provide a train of thought, to achieve there are many shortcomings, rookie of the work, do not like to spray.
Finally, the source code for this example is attached: Android implements a dual daemon through JNI
Android implements daemons through JNI