这几天遇到了两个小问题,我在这里记录下:
一、服务报如下异常:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent...
这是因为Android5.0以上的服务要进行显式调用,隐式调用只能在安卓5.0以下,我们需要修改成:
<service android:enabled="true" android:name=".push.androidPn.client.NotificationService" android:label="NotificationService">
<intent-filter>
<action android:name="org.androidpn.client.NotificationService" />
</intent-filter>
</service>
以上是假设你需要到的服务,解决方法如下:
Intent intent = new Intent();
intent.setAction("org.androidpn.client.NotificationService");
intent.setPackage(context.getPackageName());
context.startService(intent);
public void stopService() {
Intent intent = NotificationService.getIntent();
//Android5.0以上要显式调用,加入setAction和setPackage可以使用
intent.setAction("org.androidpn.client.NotificationService");
intent.setPackage(context.getPackageName());
context.stopService(intent);
}
二、我们用两个日期相减,得到一个long型的间隔毫秒,当我们转换成字符串后,发现多了8个小:
原因是中国时间是比格林威治时间多8个小时的,所以你用时间差转换成中国的时间字符串时,需要把多的8个小时减去
//这里最后把时间差的毫秒转成了Date,然后再格式化成字符串SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA); long end = simpleDateFormat.parse(endTime).getTime(); long begin = simpleDateFormat.parse(nowTime).getTime(); long gap = end - begin - 28800000; //默认的中国时间要加8小时,因此这里要先减去八个小时 Log.e("lenita","gap = "+ gap); Date date = com.blankj.utilcode.utils.TimeUtils.milliseconds2Date(gap); SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss",Locale.UK); gapString = s.format(date);
//如何判断程序是否后台运行
public static boolean isBackground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<android.app.ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses.size() > 0) { android.app.ActivityManager.RunningAppProcessInfo appProcess = appProcesses.get(0); // 判断第一个是不是自己的应用就可以了 if (appProcess.processName.equals(context.getPackageName())) { Log.i("前台", appProcess.processName); return false; } else { Log.i("后台", appProcess.processName); return true; } } return false; }