Android 点击桌面快捷方式和Notifycation跳转到Task栈顶Activity
我们一般下载的应用在第一次启动应用的时候都会给我创建一个桌面快捷方式,然后我在网上找了些资料整理下了,写了一个快捷方式的工具类,这样我们以后要创建快捷方式的时候直接拷贝这个类,里面提供了一些静态方法,主要的三个方法如下
1.addShortCut(Context context, String shortCutName, int resourceId, Class<?> cls)添加快捷方式的方法
2.delShortcut(Context context) 删除快捷方式的方法
3.hasShortcut(Context context)判断桌面上是否有该快捷方式的方法
工具类代码如下,使用这三个方法都需要添加相对于的权限,我在代码中也写的比较清楚
- package com.example.shortcut;
- import java.util.List;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.Intent.ShortcutIconResource;
- import android.content.pm.PackageInfo;
- import android.content.pm.PackageManager;
- import android.content.pm.ProviderInfo;
- import android.content.pm.PackageManager.NameNotFoundException;
- import android.database.Cursor;
- import android.net.Uri;
- import android.text.TextUtils;
- /**
- * 桌面快捷方式有关的工具类
- * @author xiaanming
- *
- */
- public class ShortCutUtils {
- /**
- * 快捷方式添加的action
- */
- private final static String SHORTCUT_ADD_ACTION = "com.android.launcher.action.INSTALL_SHORTCUT";
- /**
- * 快捷方式删除的action
- */
- private final static String SHORTCUT_DEL_ACTION = "com.android.launcher.action.UNINSTALL_SHORTCUT";
- /**
- * 读取数据库需要的权限
- */
- private final static String READ_SETTINGS_PERMISSION = "com.android.launcher.permission.READ_SETTINGS";
- /**
- * 添加快捷方式到桌面,添加快捷方式需要添加用户权限
- * <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
- * @param context
- * @param shortCutName
- * @param resourceId
- * @param cls
- */
- public static void addShortCut(Context context, String shortCutName, int resourceId, Class<?> cls){
- Intent shortCutIntent = new Intent(SHORTCUT_ADD_ACTION);
- //添加快捷方式的名字
- shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortCutName);
- //不允许重复添加
- shortCutIntent.putExtra("duplicate", false);
- //指定当前的Activity为快捷方式启动的对象
- shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent().setClass(context, cls));
- //添加快捷方式的图标
- ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, resourceId);
- shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
- context.sendBroadcast(shortCutIntent);
- }
- /**
- * 删除桌面上的快捷方式,需要添加权限
- * <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
- * @param context
- */
- public static void delShortcut(Context context) {
- Intent shortcut = new Intent(SHORTCUT_DEL_ACTION);
- // 获取当前应用名称
- String appName = null;
- try {
- appName = obtatinAppName(context);
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- // 快捷方式名称
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
- Intent shortcutIntent = context.getPackageManager() .getLaunchIntentForPackage(context.getPackageName());
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
- context.sendBroadcast(shortcut);
- }
- /**
- * 判断桌面上是否有快捷方式,调用此方法需要添加权限
- * <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
- * @param context
- * @return
- * @throws NameNotFoundException
- */
- public static boolean hasShortcut(Context context) {
- String AUTHORITY = getAuthorityFromPermission(context, READ_SETTINGS_PERMISSION);
- if (AUTHORITY == null) {
- return false;
- }
- Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
- String appName = null;
- try {
- appName = obtatinAppName(context);
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- Cursor c = context.getContentResolver().query(CONTENT_URI, new String[] { "title" }, "title=?", new String[] { appName },null);
- if (c != null && c.getCount() > 0) {
- return true;
- }
- return false;
- }
- /**
- * android系统桌面的基本信息由一个launcher.db的Sqlite数据库管理,里面有三张表
- * 其中一张表就是favorites。这个db文件一般放在data/data/com.android.launcher(launcher2)文件的databases下
- * 但是对于不同的rom会放在不同的地方
- * 例如MIUI放在data/data/com.miui.home/databases下面
- * htc放在data/data/com.htc.launcher/databases下面
- * @param context
- * @param permission 读取设置的权限 READ_SETTINGS_PERMISSION
- * @return
- */
- private static String getAuthorityFromPermission(Context context, String permission) {
- if (TextUtils.isEmpty(permission)) {
- return null;
- }
- List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
- if (packs == null) {
- return null;
- }
- for (PackageInfo pack : packs) {
- ProviderInfo[] providers = pack.providers;
- if (providers != null) {
- for (ProviderInfo provider : providers) {
- if (permission.equals(provider.readPermission)|| permission.equals(provider.writePermission)) {
- return provider.authority;
- }
- }
- }
- }
- return null;
- }
- /**
- * 获取应用的名称
- * @param context
- * @return
- * @throws NameNotFoundException
- */
- private static String obtatinAppName(Context context) throws NameNotFoundException{
- PackageManager packageManager = context.getPackageManager();
- return packageManager.getApplicationLabel(packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)).toString();
- }
- }
接下来我们来使用该工具类,我们在onCreate()的方法中先判断桌面上是否有该快捷方式,没有我们就创建一个快捷方式,然后提供一个删除快捷方式的按钮,代码还是比较简单,相信你很容易看懂的
- package com.example.shortcut;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class MainActivity extends Activity implements OnClickListener{
- private final static String TAG = "Activity";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Log.i(TAG, "onCreate");
- if(! ShortCutUtils.hasShortcut(this)){
- ShortCutUtils.addShortCut(this, getString(R.string.app_name), R.drawable.icon);
- }
- //删除快捷方式的按钮
- Button mButton = (Button) findViewById(R.id.delete);
- mButton.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.delete:
- ShortCutUtils.delShortcut(this);
- break;
- default:
- break;
- }
- }
- }
这样子我们就添加好了快捷方法,可是你会发现
一、当我们进入MainActivity的时候,然后按HOME键进入后台,找到该桌面快捷方式点击,你会发现MainActivity的onCreate()被再一次的执行
二、你删掉我们添加的快捷方式,然后再应用主界面找到该应用图片,长按几秒钟,系统也会帮我们创建一个桌面快捷方式,你进入MainActivity,然后按HOME键,找到桌面快捷方式进入MainActivity,这时候你会发现,MainActivity的onCreate()方法没有被执行了
显然第一种方式不是我们想要的,那怎么才能实现我们想要的第二种方式呢,别着急,我们只需要小小的修改一下,将上面的添加快捷方式Intent修改如下
- shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent()
- .setAction(Intent.ACTION_MAIN)
- .addCategory(Intent.CATEGORY_LAUNCHER)
- .setClass(context, cls));
设置好了,你在试一试,这时候你会发现,很应用列表长按的效果一样了,哈哈!
接下来我们来讨论下点击Notifycation的问题
我们点击一个按钮产生一个Notifycation,当我们点击Notifycation的时候,我们在onCreate()中调用如下方法来初始化Notifycation的有关东西
- /**
- * 初始化Notifycation
- */
- private void initNotify(){
- nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- n = new Notification();
- n.flags = Notification.FLAG_AUTO_CANCEL;;
- n.icon = R.drawable.notification_icon;
- n.when = System.currentTimeMillis();
- n.flags = Notification.FLAG_AUTO_CANCEL;
- n.defaults = Notification.DEFAULT_SOUND;
- n.tickerText = "CSDN给你发来了一条消息,请查看!";
- Intent intent = new Intent().setClass(getApplication(), MainActivity.class);
- PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
- n.setLatestEventInfo(getApplication(), "我的微信", "CSDN给你发来了一条消息,请查看!", pi);
- }
当我们产生通知的时候,点击通知进入MainActivity,此时的MainActivity并没有被销毁,我们发现MainActivity被重新创建了,这并不是我们想要的效果,可不可以做成如果Activity在栈中我们不重新创建,答案是肯定的,我们将上面的修改做类似的修改
- /**
- * 初始化Notifycation
- */
- private void initNotify(){
- nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- n = new Notification();
- n.flags = Notification.FLAG_AUTO_CANCEL;;
- n.icon = R.drawable.notification_icon;
- n.when = System.currentTimeMillis();
- n.flags = Notification.FLAG_AUTO_CANCEL;
- n.defaults = Notification.DEFAULT_SOUND;
- n.tickerText = "CSDN给你发来了一条消息,请查看!";
- Intent intent = new Intent()
- .setAction(Intent.ACTION_MAIN)
- .addCategory(Intent.CATEGORY_LAUNCHER)
- .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- .setClass(getApplication(), MainActivity.class);
- PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
- n.setLatestEventInfo(getApplication(), "我的微信", "CSDN给你发来了一条消息,请查看!", pi);
- }
问题就解决了,这个类似扣扣的效果,你点击Notifycation跳转到处于栈顶的Activity,这样是不是很方便呢,如果你觉得这篇文章对你有点帮助你就顶下,如果你发现错误请指出,谢谢!
上面那个创建快捷方式的工具类有点错误,不能删除创建的快捷方式,我将修改好的工具类贴在下面,也是完整的代码,直接可以用的
package com.example.shortcut; import java.util.List; import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils; /**
* 桌面快捷方式有关的工具类
* @author xiaanming
*
*/
public class ShortCutUtils {
/**
* 快捷方式添加的action
*/
private final static String SHORTCUT_ADD_ACTION = "com.android.launcher.action.INSTALL_SHORTCUT";
/**
* 快捷方式删除的action
*/
private final static String SHORTCUT_DEL_ACTION = "com.android.launcher.action.UNINSTALL_SHORTCUT";
/**
* 读取数据库需要的权限
*/
private final static String READ_SETTINGS_PERMISSION = "com.android.launcher.permission.READ_SETTINGS"; /**
* 添加快捷方式到桌面,添加快捷方式需要添加用户权限
* <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
* @param context 当前的context对象
* @param resourceId 快捷方式的图标资源id
*/
public static void addShortCut(Context context, int resourceId){
Intent shortCutIntent = new Intent(SHORTCUT_ADD_ACTION);
//添加快捷方式的名字
// 获取当前应用名称
String appName = null;
try {
appName = obtatinAppName(context);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
//不允许重复添加
shortCutIntent.putExtra("duplicate", false); shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER).setClassName(context.getPackageName(), context.getClass().getName()));
//添加快捷方式的图标
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, resourceId);
shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); context.sendBroadcast(shortCutIntent);
} /**
* 删除桌面上的快捷方式,需要添加权限
* <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
* @param context
*/
public static void delShortcut(Context context, Activity activity) {
Intent shortcut = new Intent(SHORTCUT_DEL_ACTION);
// 获取当前应用名称
String appName = null;
try {
appName = obtatinAppName(context);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
// 快捷方式名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER).setClassName(context.getPackageName(), context.getClass().getName()));
context.sendBroadcast(shortcut);
} /**
* 判断桌面上是否有快捷方式,调用此方法需要添加权限
* <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
* @param context
* @return
* @throws NameNotFoundException
*/
public static boolean hasShortcut(Context context) {
String AUTHORITY = getAuthorityFromPermission(context, READ_SETTINGS_PERMISSION); System.out.println(AUTHORITY); if (AUTHORITY == null) {
return false;
}
Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
String appName = null;
try {
appName = obtatinAppName(context);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
Cursor c = context.getContentResolver().query(CONTENT_URI, new String[] { "title" }, "title=?", new String[] { appName },null);
if (c != null && c.getCount() > 0) {
return true;
}
return false;
} /**
* android系统桌面的基本信息由一个launcher.db的Sqlite数据库管理,里面有三张表
* 其中一张表就是favorites。这个db文件一般放在data/data/com.android.launcher(launcher2)文件的databases下
* 但是对于不同的rom会放在不同的地方
* 例如MIUI放在data/data/com.miui.home/databases下面
* htc放在data/data/com.htc.launcher/databases下面
* @param context
* @param permission 读取设置的权限 READ_SETTINGS_PERMISSION
* @return
*/
private static String getAuthorityFromPermission(Context context, String permission) {
if (TextUtils.isEmpty(permission)) {
return null;
}
List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
if (packs == null) {
return null;
}
for (PackageInfo pack : packs) {
ProviderInfo[] providers = pack.providers;
if (providers != null) {
for (ProviderInfo provider : providers) {
if (permission.equals(provider.readPermission)|| permission.equals(provider.writePermission)) {
return provider.authority;
}
}
}
}
return null;
} /**
* 获取应用的名称
* @param context
* @return
* @throws NameNotFoundException
*/
private static String obtatinAppName(Context context) throws NameNotFoundException{
PackageManager packageManager = context.getPackageManager();
return packageManager.getApplicationLabel(packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)).toString();
} }
上面的有些代码不太完整代码下载
Android 点击桌面快捷方式和Notifycation跳转到Task栈顶Activity的更多相关文章
- android Activity启动过程(三)从栈顶Activity的onPause到启动activityon的Resume过程
ActivityStack.startPausingLocked() IApplicationThread.schudulePauseActivity() ActivityThread.sendMes ...
- android 点击桌面图标,打开手机浏览器进入对应的站点
做一个假的adnroid app.要实现点击桌面图标.打开手机浏览器进入对应的站点,实现方法非常easy import android.app.Activity; import android.con ...
- Android中的桌面快捷方式
一.判断是否已有快捷方式 private String getAuthorityFromPermission(Context context, String permission){ if (perm ...
- android点击桌面App图标activity启动流程
1.点击桌面App图标,Launcher进程采用Binder IPC向system_server进程发起startActivity请求:2.system_server进程接收到请求后,向zygote进 ...
- android Activity启动过程(二)从ActivityManagerService的startActivity到栈顶Activity的onPause过程
ActivityManagerService.startActivity() ActvityiManagerService.startActivityAsUser() ActivityStackSup ...
- android桌面快捷方式跳转到指定activity
AndroidManifest.xml 应用主入口配置: <activity android:name="com.*.cust.contacts.MainActivity" ...
- Android桌面快捷方式那些事与那些坑
原文来自http://blog.zanlabs.com/2015/03/14/android-shortcut-summary/ 将近二个多月没写博客了.之前一段时间一直在搞红包助手,就没抽时间写博客 ...
- Android创建桌面快捷方式
在桌面上创建特定界面的快捷入口,icon和title根据请求参数命名.在网上收集的一些相关资 料,在使用intent发送广播的时候,一些型号的收集会有问题,如魅族MX,红米,以及华为,使用setCla ...
- (转)Android创建桌面快捷方式两种方法
[IT168技术]Android在桌面上生成快捷方式有两种情况,一种是直接在桌面直接生成;一种是长按桌面,在弹出的快捷菜单中生成. 谈谈在桌面上直接生成.个人觉得这个比较爽快,既然都是快捷方式了干嘛还 ...
随机推荐
- 解决方案命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Ajax”(是否缺少程序集引用?)
首先对System.Web.Mvc这个dll文件重新引用本地的,添加引用,搜索mvc就可以出来,选择相应的版本.如果还不能正常运行, 然后右键打开这个项目引用System.Web.Mvc, 将复制本地 ...
- Hibernate 一对多注解 mappedby 作用
package oneToMany; import java.util.Set; import javax.persistence.*; /* 注意导入时,是导入:import javax.persi ...
- java通过SVG导出图片
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import ja ...
- 微信应用号开发知识贮备之Webpack实战
天地会珠海分舵注:随着微信应用号的呼之欲出,相信新一轮的APP变革即将发生.作为行业内人士,我们很应该去拥抱这个趋势.这段时间在忙完工作之余准备储备一下这方面的知识点,以免将来被微信应用号的浪潮所淹没 ...
- 为网上流行论点“UIAutomator不能通过中文文本查找控件”正名
1. 问题描述和起因 相信大家学习UIAutomator一开始的时候必然会看过一下这篇文章. Android自动化测试(UiAutomator)简要介绍 因为你在百度输入UIAutomator搜索的时 ...
- 单元测试之Qunit
单元测试之Qunit 前言 因为公司开发了一套javascript SDK需要测试,在网上找了很久,找到了JQuery团队开发的QUnit,和基于JUnit的JsUnit,还有一些还没有看,先讲讲QU ...
- Mysql 使用 select into outfile
Mysql支持将查询结果到处 默认语法 select .. from table into outfile "filepath\filename.txt"; 如果在执行的过程中遇 ...
- 分析Java因为语言慢
Java在早期的(例JDK1.2一旦)这是很慢.也许是因为有很多的优化,以提高装置的版本号,Java这是越来越快,所以这是现在非常的Java和C/C++什么什么慢速争议. 我想我自己的理解.谈论的影响 ...
- .net的页面在大并发下出现503错误
.net的页面在大并发下偶尔出现503错误 我们开发了一个回调页面,由一个工具负责调用,由于压力非常大,回调页面通过6台服务器负载均衡的: 最近业务系统又再次扩容,回调页面压力成倍增加,在高峰时间段偶 ...
- CodeSmith开发系列资料总结
CodeSmith开发系列资料总结 最近跟同事在研究CodeSmith,感觉中文文档是少之又少,所以我们自己写(翻译)了一些文档,总结如下,希望对使用CodeSmith的朋友有所帮助: “努力学习的熊 ...