Service后台奔溃
1.启动
Intent intent = new Intent(this, SpotLightService.class);
this.startService(intent); //这个普通启动会在低内存的时候被杀掉
//普通的启动修改成前台启动
this.startForegroundService(intent);
2.修改SERVICE
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int startResult = super.onStartCommand(intent,flags,startId);
startForeground();
return START_STICKY;
}
private void startForeground() {
final NotificationManager noMan = getSystemService(NotificationManager.class);
noMan.createNotificationChannel(new NotificationChannel(
NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_ID,
NotificationManager.IMPORTANCE_DEFAULT));
//Log.d(TAG, "Starting foreground. myUid=" + Process.myUid());
startForeground(NOTIFICATION_ID,
new Notification.Builder(this,NOTIFICATION_CHANNEL_I
根据包名启动应用
public boolean startAPPFromPackageName( String pckName) {
if (pckName.equals("acr.browser.lightning.activity.MainActivity") || pckName.equals("com.android.bthsrv.MainActivity")) {
Intent intent = new Intent().setComponent(new ComponentName("com.viso.mdm" , pckName) );
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
sContext.startActivity(intent);
}
try {
Intent intent = isexit(pckName);
if (intent == null) {
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
sContext.startActivity(intent);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public Intent isexit(String pk_name) {
PackageManager packageManager = sContext.getPackageManager();
Intent it = packageManager.getLaunchIntentForPackage(pk_name);
return it;
}
其中从最近任务栏进入wps如果不经过特殊处理则不能进入
//判断是否为WPS,如果是WPS应用,通过任务ID启动,否则当有多个WPS任务时,会导致WPS报错
if ("cn.wps.moffice_eng".equals(bean.getPackageName())) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
manager.moveTaskToFront(bean.getId(), ActivityManager.MOVE_TASK_WITH_HOME);
} else {
mRecentTaskHelper.startAppByClassName(this, bean.getPackageName(), bean.getClassName());
}
//获取最近任务栏应用
List<ActivityManager.RecentTaskInfo> appTasks = activityManager.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
if (appTasks == null || appTasks.size() == 0) {
emitter.onNext(taskList);
return;
}
for (ActivityManager.RecentTaskInfo taskInfo : appTasks) {
ResolveInfo resolveInfo = packageManager.resolveActivity(taskInfo.baseIntent, 0);
String packageName = resolveInfo.activityInfo.packageName;
//过滤不需要的应用
if (!isNotShowApp(mContext, packageName)) {
TaskBean bean = new TaskBean();
bean.setName(resolveInfo.loadLabel(
System.currentTimeMillis()的时间会有误差,如果时区不同会造成误差,所以使用SystemClock.elapsedRealtime();是比较准确的做法
** 替换FragmentManager **
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_fragment, fragment);
transaction.addToBackStack(null);
transaction.commit();