您的位置:首页 > 移动开发 > Android开发

程序监听本身被卸载后自动删除快捷方式?| 判定快捷方式已存在

2011-05-28 10:48 183 查看
      当程序安装/卸载时,会发出PACKAGE_ADDED/PACKAGE_REMOVED广播,按理只要应用程序监听这样的广播,就能在收到相应广播时触发相应处理(例如,添加/删除 桌面快捷方式)。事实验证,这个是完全可以实现的。

      但是,如果是由应用程序进行这些广播的监听,同时,又卸载自身,那能否收到相应广播并触发相应处理呢?实验证明行不通。
自身已经被卸载了,无法自救!! 如果还有其他方法盼赐教,无限期待。

      HL耐心研究了这个许久,还说一定要把它实现。后生可畏呢。

 

    为客户服务就不要顶着一个技术至上的大帽子,踏踏实实做好每个细节。 :)

 

  
public class installReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Toast.makeText(context, "有应用被添加", Toast.LENGTH_LONG).show();
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Toast.makeText(context, "有应用被删除", Toast.LENGTH_LONG).show();
} else if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
Toast.makeText(context, "有应用被替换", Toast.LENGTH_LONG).show();
}
}
}


 

  
<receiver android:name=".installReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED"></action>
<action android:name="android.intent.action.PACKAGE_REMOVED"></action>
<action android:name="android.intent.action.PACKAGE_REPLACED"></action>
<data android:scheme="package"></data>
</intent-filter>
</receiver>


 

判定快捷方式已存在

通过发送广播给Launcher创建桌面快捷方式,Laucher收到该广播创建快捷方式后会有Toast提示
创建成功,如果该快捷方式已经存在,也会有Toast提示
已存在。若每次进入程序时都执行如下代码,就每次都有Toast提示出现,频繁地出现打扰了用户


private void addSelfShortcut() {
if(!judgeShoutcutInstalled(this))
{
Intent shortcut = new Intent(SHORTCUT_INSTALL);
// 显示的名字
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getResources().getString(R.string.app_name));
// 显示的图标
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
// 不允许重复创建
shortcut.putExtra("duplicate", false);

// 这个是快捷方式所实现的功能
Intent intent = new Intent(this, Shutcut.class);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// 发送广播用以创建shortcut
this.sendBroadcast(shortcut);
}


 

所以,在决定是否执行以上代码之前就添加是否存在该快捷方式的判定
,如果没有该快捷方式,就发出广播告诉Laucher创建快捷方式(会弹窗一次Toast),如果该快捷方式已经存在,则不需执行该代码去创建,当然也就不会出现Toast了。

private boolean judgeShoutcutInstalled (Context context){
boolean isInstallShortcut = false ;
final ContentResolver cr = context.getContentResolver();
final String AUTHORITY = "com.android.launcher.settings";
final Uri CONTENT_URI = Uri.parse("content://" +
AUTHORITY + "/favorites?notify=true");

Cursor c = cr.query(CONTENT_URI,
new String[] {"title","iconResource" },
"title=?",
new String[] {getResources().getString(R.string.app_name) }, null);//XXX表示应用名称。
if(c!=null && c.getCount()>0){
isInstallShortcut = true ;
}


判定是否存在该快捷方式,需要权限:

<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"></uses-permission>


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息