Android5.0以上的服务要显式调用/关于时间差问题/判断程序是否在前台

这几天遇到了两个小问题,我在这里记录下:

一、服务报如下异常:

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个小时减去

 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);
//这里最后把时间差的毫秒转成了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;
    }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值