问题描述
我正在使用 recyclerView 中的应用程序抽屉制作启动器应用程序,显示设备上当前安装的每个应用程序。长按视图中的应用程序会显示上下文菜单,用户可以从中卸载应用程序。
我只是不知道我将如何去做。我希望能够只提示系统“是否要卸载此应用程序”对话框 like this。
目前我有一个空的 void 方法,它以 recyclerview 中的应用程序位置作为输入参数,仅此而已。
这里是相关的recyclerview方法——如果你想要整个类,我可以编辑它。
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.ViewHolder> {
public List<AppObject> appsList;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener {
public TextView appNameTV;
public ImageView appIconIV;
public TextView appCategoryTV;
public LinearLayout appDrawerItemLL;
//This is the subclass ViewHolder which simply
//'holds the views' for us to show on each row
public ViewHolder(View itemView) {
super(itemView);
//Finds the views from our row.xml
appNameTV = (TextView) itemView.findViewById(R.id.applicationNameTextView);
appIconIV = (ImageView) itemView.findViewById(R.id.applicationIconImageView);
appCategoryTV = (TextView) itemView.findViewById(R.id.appCategoryTextView);
appDrawerItemLL = (LinearLayout) itemView.findViewById(R.id.app_drawer_item);
itemView.setonClickListener(this);
itemView.setonCreateContextMenuListener(this);
}
@Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.add(this.getAdapterPosition(),1,"Add to Favourites");
menu.add(this.getAdapterPosition(),2,"App info");
menu.add(this.getAdapterPosition(),3,"Uninstall app");
}
}
public void uninstallApp(int position) {
appsList.remove(position); //removes item from listview but it doesn't uninstall it
notifyDataSetChanged();
}
}
public boolean onContextItemSelected(@NonNull MenuItem item) {
switch (item.getItemId())
{
case 1: // add to favourites in homescreen
addAppToFavourites();
return true;
case 2: // show information about app
showApplicationInfo();
return true;
case 3: // uninstall application
adapter.uninstallApp(item.getGroupId());
displayMessage("Uninstalled application");
return true;
default:
displayMessage("You should not be seeing this message");
}
return super.onContextItemSelected(item);
}
如您所见,上下文菜单是在 recyclerview 适配器类中创建的,然后 App Drawer 类中的 onContextItemSelected 方法选择单击每个选项时发生的情况。当用户单击“卸载应用程序”时,它会运行 recyclerview 适配器类中的 .uninstallApp 方法。这是卸载功能应该去的地方。我该如何实施?
解决方法
您需要知道要卸载的应用程序的包名称。然后调用这个简单的方法-
public void uninstallApp(String packagename){
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:"+packagename));
startActivity(intent);
}
不要忘记添加此权限-
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES"/>
这应该会提示用户卸载该应用。