最近工作中接触Android应用实现卸载自身的逻辑,踩了一些坑之后整理下来。使用的方法是Intent.ACTION_DELETE,这里没有什么好说的。
MainActivity.java :
package com.example.uninstalldemo; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE = 1; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button uninstallButton = findViewById(R.id.uninstall_button); uninstallButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UninstallApk(); } }); } private void UninstallApk() { String packageName = getPackageName(); Log.d(TAG, "UninstallApk: "+packageName); Uri packageURI = Uri.parse("package:" + packageName); Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI); startActivityForResult(uninstallIntent,REQUEST_CODE); } @Override public void onActivityResult(int requestCode,int resultCode,Intent data){ Log.d(TAG, "requestCode:" + String.valueOf(requestCode) + ", resultCode:" + String.valueOf(resultCode)); switch (requestCode){ case 1: if(resultCode == RESULT_OK){ Log.d(TAG, "onActivityResult: executed"); //点击确定,为什么打印此行?? }else{ Log.d(TAG, "onActivityResult: executed in here**");//点击取消,打印此行。 } break; default: break; } } }
activity_main.xml中添加一个按钮,点击之后卸载应用程序apk.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/uninstall_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Uninstall"/> </LinearLayout>
最后,在Android 9中,完成上面的代码但是点击Uninstall无反应,找了很久答案,才知道在android 9中需要在添加权限,在AndroidManifest.xml添加:
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES"/>
运行程序,logcat信息如下:
2019-03-11 21:05:45.451 31622-31622/com.example.uninstalldemo D/MainActivity: UninstallApk: com.example.uninstalldemo
2019-03-11 21:05:48.827 31622-31622/com.example.uninstalldemo D/MainActivity: requestCode:1, resultCode:0
2019-03-11 21:05:48.827 31622-31622/com.example.uninstalldemo D/MainActivity: onActivityResult: executed in here**
点击确定删除不打印log信息,暂不知道为什么。