手机屏幕关了后台怎么让软件继续启动?
答案:2 悬赏:50 手机版
解决时间 2021-02-03 03:32
- 提问者网友:不爱我么
- 2021-02-03 00:24
手机屏幕关了后台怎么让软件继续启动?
最佳答案
- 五星知识达人网友:执傲
- 2021-02-03 00:40
要实现软件后台运行,只需要改写返回键事件监听,使得back键功能类似home键,让Acitivty退至后台时不被系统销毁,代码如下:
public boolean onKeyDown(int keyCode, KeyEvent event) {
PackageManager pm = getPackageManager();
ResolveInfo homeInfo =
pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
if (keyCode == KeyEvent.KEYCODE_BACK) {
ActivityInfo ai = homeInfo.activityInfo;
Intent startIntent = new Intent(Intent.ACTION_MAIN);
startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
startActivitySafely(startIntent);
return true;
} else
return super.onKeyDown(keyCode, event);
}
private void startActivitySafely(Intent intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "null",
Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(this, "null",
Toast.LENGTH_SHORT).show();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
PackageManager pm = getPackageManager();
ResolveInfo homeInfo =
pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
if (keyCode == KeyEvent.KEYCODE_BACK) {
ActivityInfo ai = homeInfo.activityInfo;
Intent startIntent = new Intent(Intent.ACTION_MAIN);
startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
startActivitySafely(startIntent);
return true;
} else
return super.onKeyDown(keyCode, event);
}
private void startActivitySafely(Intent intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "null",
Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(this, "null",
Toast.LENGTH_SHORT).show();
}
}
全部回答
- 1楼网友:由着我着迷
- 2021-02-03 01:09
手机系统问题吧,我用的魅族手机就可以你说的这样,边聊扣扣边听他们直播
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯