Static default installation and uninstallation of applications in Andrdoid

Source: Internet
Author: User

I haven't written a blog for a long time, mainly because of the delay in my recent work and the download of the Android source code (the download of the source code will be written in the subsequent blog, this really makes sense ~~), So what do you want to write today? The main idea is to read the news in the morning and see an article saying that there is an app that uninstalls all browsers on the user's mobile phone in the background and will not be noticed by the user, however, Baidu browser used anti-reconnaissance technology to find this evil application and then took it to court. Then let's take a look at how to achieve static installation and uninstallation of the application? This is to prevent users from knowing. The following describes the implementation steps step by step:


1. Access the hidden API for static default installation and uninstallation 1. The system installer android comes with an installer --- /System/app/PackageInstaller.apk.In most cases, the app installed on our mobile phone is installed using this apk. The Code is also very simple to use:

/* Install apk */public static void installApk (Context context, String fileName) {Intent intent = new Intent (); intent. setAction (Intent. ACTION_VIEW); intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); intent. setDataAndType (Uri. parse ("file: //" + fileName), "application/vnd. android. package-archive "); context. startActivity (intent);}/* uninstall apk */public static void uninstallApk (Context context, String packageName) {Uri uri Uri = Uri. parse ("package:" + packageName); Intent intent = new Intent (Intent. ACTION_DELETE, uri); context. startActivity (intent );}
By sending an intentfile, you can install packageinstaller.apk after installing uri.7.
However, in this case, it is only a demo, and it is difficult to meet developers' needs. For example:
1) Poor Interface

2). Known to users

3) When will the installation and uninstallation be complete?

Of course, for the third point, in order to meet their own needs, I believe many people will listen to the broadcast of system installation and uninstallation and continue the subsequent code logic.


Install broadcast from the listening system
After the installation and uninstallation are complete, the android system sends a broadcast
Android. intent. action. PACKAGE_ADDED (installation)
Android. intent. action. PACKAGE_REMOVED (uninstall)

Let's listen to the broadcast and handle the response logic. Implementation Code:

Public class MonitorSysReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {// receives the installation broadcast if (intent. getAction (). equals ("android. intent. action. PACKAGE_ADDED ") {// TODO} // receives the unmounted broadcast if (intent. getAction (). equals ("android. intent. action. PACKAGE_REMOVED ") {// TODO }}}


Configuration in the AndroidManifest. xml file:
  
                
                                              
      
 


At this point, the overall installation and uninstallation process is all known, but this effect is certainly unable to meet the project requirements.
Generally App Store (pods)You must customize the installation and uninstallation function in the prompt box, instead of calling the system installer.
Then we need to try to install and uninstall it silently.

The following calls the hidden api interface of the system to perform Silent Installation and uninstallation, which is quite reliable and provides a custom prompt interface.

(For this call to the hidden api interface of the system, we have introduced how to obtain the power of a mobile phone in an article about how to obtain the power of a mobile phone.

Http://blog.csdn.net/jiangwei0910410003/article/details/25994337)


2. The hidden api hidden by the system, as the name suggests, cannot be called normally. Flip source code \ Frameworks \ base \ core \ java \ android \ content \ pmPackageManager. java under the directory, you should find
Add the @ hide statement to the comment line. The called installation and download interfaces are as follows:

Installation interface:

public abstract void installPackage(Uri packageURI,IPackageInstallObserver observer, int flags,String installerPackageName);
Uninstall interface:
public abstract void deletePackage(String packageName,IPackageDeleteObserver observer, int flags);


And they are all abstract methods that need to be implemented.
See IPackageInstallObserver observer in the parameter for an aidl callback notification interface. This interface is found in the current directory:
package android.content.pm;/** * API for installation callbacks from the Package Manager. * @hide */oneway interface IPackageInstallObserver {    void packageInstalled(in String packageName, int returnCode);}

Well, there is a ready-made dry goods here, so we can use it directly (if there is no source code, that would be a demo ). Procedure:
Copy the aidl callback interface to be used from the source code: IPackageInstallObserver. aidl, IPackageDeleteObserver. aidlOf course, you can copy the entire pm directory, so that no error is reported.
Pm is used in the project, so PackageManager. java and some related files are also copied. Otherwise, eclipse reports that the PackageManager object cannot be found. The structure is as follows:



<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + 16 KjujxzdHJvbmc + supervisor + Supervisor/supervisor + 1zbPBrL3Tt/Supervisor/ydLUye6 + v8/Co6k8YnI + CjIu1 /tests/fV37DRyc/tests/ra8t8W/tests/qGj1 + 688 rWltcS + zcrH1rG907 + 9sbQ0uPbOxLz + vLS/tests + tests/Tests/ ao6y0 + sLryOfPwqO6PGJyPgo8L3A + CjxwPrCy17C1xLvYtfe907/ao7o8L3A + cjxwp1_vcd4kphbyzsbjbgfzcz0 = "brush: java; ">/* Silent Installation callback */class MyPakcageInstallObserver extends IPackageInstallObserver. stub {@ Overridepublic void packageInstalled (String packageName, int returnCode) {if (returnCode = 1) {Log. e ("DEMO", "successfully installed"); new ToastThread (InstallActivity. this, "successfully installed "). start ();} else {Log. e ("DEMO", "Installation failed, return code:" + returnCode); new ToastThread (InstallActivity. this, "Installation failed, return code:" + returnCode ). start ();}}}


Installation Method:
String fileName = Environment.getExternalStorageDirectory() + File.separator + "baidu"+File.separator +"UC.apk";Uri uri = Uri.fromFile(new File(fileName));int installFlags = 0;PackageManager pm = getPackageManager();try {PackageInfo pi = pm.getPackageInfo("com.UCMobile",PackageManager.GET_UNINSTALLED_PACKAGES);if(pi != null) {installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;}} catch (NameNotFoundException e) {}MyPakcageInstallObserver observer = new MyPakcageInstallObserver();pm.installPackage(uri, observer, installFlags, "com.UCMobile");
Upload to the baidu folder in the SD card, or you can customize a directory for storing files)


The uninstall principle is the same.

Unmount callback interface:

/* Silent uninstall callback */class MyPackageDeleteObserver extends IPackageDeleteObserver. stub {@ Overridepublic void packageDeleted (String packageName, int returnCode) {if (returnCode = 1) {Log. e ("DEMO", "Uninstall successful... "); new ToastThread (InstallActivity. this, "Uninstall successful... "). start ();} else {Log. e ("DEMO", "Uninstall failed... return Code: "+ returnCode); new ToastThread (InstallActivity. this, "Uninstall failed... return Code: "+ returnCode ). start ();}}}


Uninstall:

PackageManager pm = InstallActivity.this.getPackageManager();IPackageDeleteObserver observer = new MyPackageDeleteObserver();pm.deletePackage("com.UCMobile", observer, 0);
Here we must upload a package name.


Since then, the installation and uninstallation code has been silently implemented. Finally, you must register permissions and add them as system user groups in AndroidManifast. xml.

         
       
  
  
  
  
  
  
       ...
 


There are two points to note: the first one must be added:

android:sharedUserId="android.uid.system"

This is to register its application into a system user group.


You must also add the following permissions for installation and uninstallation:

 
 


After all the above work is done, let's use Eclipse to run it:


Well, it seems that it is not so smooth, and there is an installation error. In fact, this information will find a lot of relevant information after going to Baidu, because many people have encountered this problem, so there are a lot of solutions, that is, we need to sign our application into a system level. What should we do?


There are two common methods on the Internet:

The first one is: Get the three files platform. pem, platform. x509.pem and signapk. jar for signature: the signature command is simple:

Java-jar signapk. jar platform. x509.pem platform. pemThe apk to be signed

Is my signature operation:



Method 2: It is very troublesome. Why bother? Because you need to download the source code, and then copy our application to the specified directory:

1. If you have the system source code, the simplest thing is to copy the application in eclipse to the system and compile the system to generateOut/target/product/generic/system/app/abc.apkThe application is signed by the system. The specific method is as follows:
Copy the application folder to the source code directory packages/experimental/project_name/and keep only src, res, libs, and androidmanifest. xml file, which creates an Android. mk file with the following content:
LOCAL_PATH: = $ (call my-dir)
Include $ (CLEAR_VARS)
LOCAL_MODULE_TAGS: = optional
LOCAL_SRC_FILES: = $ (call all-subdir-java-files)
LOCAL_PACKAGE_NAME: = abc
LOCAL_CERTIFICATE: = platform
Include $ (BUILD_PACKAGE)

Then compile it.


In fact, when we put the first method, there is a question: Where can we get the three signature files? I can search for it online, but I download la and then sign it. The result is always failed. So I gave up downloading it from the Internet. What else can I do? Okay, you have to download the Android source code. After compilation, you can find these three files in the specified directory.


But it is not complete yet. Whether it is the first or the second method, I still fail during the experiment. Why? Because if we use these three files for signature or put the project into the source code for compilation, we must pay attention to the following points: that is, the system version of the signed file must be the same as the system version installed on the device. To put it bluntly: now, if the three Signed files are obtained from the downloaded source code, the versions of the three files are the Android source code version, for example, version 4.4, then, the apk package signed with these three files can only be installed on the host whose system version is 4.4. Similarly, if we put the project directly in the Android source code for compilation, if the system version of the Android source code is 4.4, the compiled apk can only be installed on a host whose system version is 4.4.


Therefore, the three Signed files downloaded from the Internet always fail to be signed, so this method is always unreliable, because the signature file we downloaded from the Internet certainly does not know its version number, however, we can install the signed package into each version of the system to try, so the most reliable way is to download the source code and then get the three signature files, because the source code we downloaded must know the version.

The directories corresponding to these three files are:

Signapk. jar: Source directory/out/host/linux-x86/framework/signapk. jar

Platform. pk8 and platform. x509.pem: source code directory/build/target/product/security/platform. pk8 & platform. x509.pem


When we use the first method, we need to use Eclipse to export an unsigned package. This is very simple and will not be introduced here ~~


Running result:


Because there is no 4.4 system on hand and you don't want to brush the machine, you can use the simulator. It may take some time to install and uninstall the software during this process, so wait for a while. Don't worry ~~


We will introduce how to use hidden APIs to install and uninstall APPs by default,

Demo project:

Http://download.csdn.net/detail/jiangwei0910410003/7584423

After importing the project, you need to perform the following steps:

Upload a uc.apk to the baidu folder in the SDK card (which needs to be created)

Export unsigned packages

Download signature tool:

Http://download.csdn.net/detail/jiangwei0910410003/7584441

Follow the above signature steps

Then find a testing machine or simulator whose system is version 4.4 to install the installation package (because the version of my signature file is version 4.4)


2. Use commands to perform static default installation and uninstallation

Next, let's take a look at how to use the command to install and uninstall the app by default. We know that you can use the command:

Adb install apk File

Adb uninstall package name

Installation and uninstallation.


In the code, we can use the Runtime class for operations:

Runtime.getRuntime().exec("adb uninstall com.UCMobile");
Or ProcessBuilder:

new ProcessBuilder().command("adb","uninstall","com.UCMobile").start(); 

The difference between the two classes is that the first is to write the command together, the second is to separate the command with spaces, and then pass it as a parameter, in fact, the parameters of the command method are of the String variable parameter type.


However, when we execute the above Code, we find that the execution always fails, and the results only find that theseThe Directory of command execution is not in the shell layer, but the Command executed on the mobile phone must be in the shell layer, so there may be problems, but we can use the pm command,For example, we use the command line on the PC to install the file:

> Adb shell

> Pm install apk File

In fact, the above two lines of commands and

> Adb install apk File

The same effect

However, if you want to execute the installation file on your mobile phone, you can only execute the following command:Pm install apk File

(The pm command can be used to execute commands from the shell layer)


Let's talk about the code below:

/** M command can be executed in shell through adb. Similarly, we can execute */public static String execCommand (String... command) {Process process = null; InputStream errIs = null; InputStream inIs = null; String result = ""; try {process = new ProcessBuilder (). command (command ). start (); ByteArrayOutputStream baos = new ByteArrayOutputStream (); int read =-1; errIs = process. getErrorStream (); while (read = errIs. read ())! =-1) {baos. write (read);} inIs = process. getInputStream (); while (read = inIs. read ())! =-1) {baos. write (read);} result = new String (baos. toByteArray (); if (inIs! = Null) inIs. close (); if (errIs! = Null) errIs. close (); process. destroy () ;}catch (IOException e) {result = e. getMessage () ;}return result ;}

Call this method:

Protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); final String path = Environment. getExternalStorageDirectory () + File. separator + "baidu" + File. separator + "360MobileSafe.apk"; Button btn1 = (Button) findViewById (R. id. btn1); btn1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// install apk, filePath is the apk file path, for example,/mnt/sdcard/ApiDemos.apk String result = execCommand ("pm", "install", "-f", path); Toast. makeText (MainActivity. this, "installation result:" + result, Toast. LENGTH_LONG ). show () ;}}); Button btn2 = (Button) findViewById (R. id. btn2); btn2.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// uninstall apk, packageName is the package name, such as com. example. android. apisString result = execCommand ("pm", "uninstall", "com. qihoo360.mobilesafe "); Toast. makeText (MainActivity. this, "Uninstall result:" + result, Toast. LENGTH_LONG ). show ();}});}

Configuration in AndroidManifest. xml:

   
 
There are also:
android:sharedUserId="android.uid.system"
We have already mentioned this before, so what we are doing now is to sign the system. The specific method is not described as above.

The following figure shows the running result:



Demo project:

Http://download.csdn.net/detail/jiangwei0910410003/7584429

The steps required to import the downloaded project are the same as those described above ~~


Summary:The above describes how to implement static installation and uninstallation. In fact, there are other methods. For example, we can directly copy the apk file that needs to be installed by default to the directory:

/Data/app, because we know that all applications installed by users are in this directory, but after testing, it is found that the default installation is correct and you can copy it directly.

Yes, but there is a problem during uninstallation. If we delete the apk file directly, the app icon still exists on the mobile phone, but we will

A crash occurs, which is equivalent to the result that the program cannot be opened after a file is accidentally deleted in the Window system. Therefore, this uninstallation is unreliable and is not recommended.

In this way, you also need to obtain the root permission of the mobile phone.


Issues to be resolved:

1. we can see that we are using version 4.4 for signature. We can only install it on a machine with version 4.4 in the system. This is to be verified, because the application we developed cannot only be installed in the specified version, it must be that all systems can be installed (such as pods), so I made a hypothesis, is it easy to install the apk after the system signature of the earlier signature file can be installed in the later version, we can download the Android2.2 source code (because the lowest version on the market now is 2.2), get his signature file, or search for the signature file of this version from the Internet (not found so far, if you have found one, please share it. Thank you !!)

2. Another problem is that the above test environments are all root on mobile phones or simulators. It is worth noting whether the root-less mobile phones will cause problems during installation ~~


The above blog is hard to solve after several months, so I really want to say: do not give up, there are always more ways than problems, be sure to stick to it ~~, In fact, the biggest problem encountered above is the download of the source code process (no technology at all, it is to test our patience, and the network is also an important reason. For some reason, I downloaded the source code of version 4.4, a total of 13 Gb, which will not be made public here. If you really need it, please leave a message. I can share it with you ~~), Another is the compilation process. I spent a week, because in this process, it can be said that there were thousands of difficulties and problems. I re-compiled them several times ~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.