获取应用在线时间长短(区分前后台)

package com.example.onlinetimedemo;

import com.example.onlinetimedemo.MyService1.MyBinder;
import com.example.onlinetimedemo.util.StatisticUtil;

import android.app.Application;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.widget.Toast;

public class MyApplication extends Application {
    private MyBroadcastReceive myBroadcastReceive;
    private long totalOnLineTime = 0;
    private long foregroudOnLineTime = 0;
    private long backgroundOnLineTime = 0;
    private MyBinder binder;
    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(MyApplication.this, MyService1.class);
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        IntentFilter filter = new IntentFilter();
        filter.addAction("my.receive.time");
        myBroadcastReceive = new MyBroadcastReceive();
        registerReceiver(myBroadcastReceive, filter);
    }
    private class MyBroadcastReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (binder != null) {
                totalOnLineTime = binder.getTotalOnLineTime();
                foregroudOnLineTime = binder.getForegroudOnLineTime();
                backgroundOnLineTime = binder.getBackgroundOnLineTime();
            }
            Toast.makeText(getApplicationContext(), "接受到广播!", 0).show();
        }
    }
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyBinder) service;
        }
    };

}

// 推荐在 activity中 绑定 服务 借帮服务




package com.example.onlinetimedemo;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;

import com.example.onlinetimedemo.util.StatisticUtil;

public class MyService1 extends Service {
    private boolean isLoop = true;
    private static long tatalOnLineTime = 0;
    private static long foregroudOnLineTime = 0;
    private static long backgroudOnLineTime = 0;
    private SharedPreferences shPreferences;
    private Editor edit;

    @Override
    public IBinder onBind(Intent arg0) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Notification notification=new Notification();
        startForeground(1, notification); // 设置为 前台 服务 不被 杀 死
        
        shPreferences = getApplication().getSharedPreferences("onlinetime", Context.MODE_PRIVATE);
        edit = shPreferences.edit();
        new Thread() {

            public void run() {
                long startTime = System.currentTimeMillis();
                long startForBackground = 0;
                long endTime = 0;
                long endTimeForBackground = 0;
                while (isLoop) {
                    // 判断是否在前台( is foregroud or backgroud)
                    if (StatisticUtil.isTopActivity(getApplicationContext())) {
                        startForBackground = endTime = System.currentTimeMillis();
                        foregroudOnLineTime = endTime - startTime;
                    } else {
                        endTimeForBackground = System.currentTimeMillis();
                        backgroudOnLineTime = endTimeForBackground - startForBackground;
                    }
                    tatalOnLineTime = backgroudOnLineTime + foregroudOnLineTime;
                    edit.putLong("foregroudOnLineTime", foregroudOnLineTime);
                    edit.putLong("tatalOnLineTime", tatalOnLineTime);
                    edit.putLong("backgroudOnLineTime", backgroudOnLineTime);
                    edit.commit();
                    SystemClock.sleep(6000);
                    sendBroadcast(new Intent("my.receive.time"));
                }
            }
        }.start();
    }

    public long getTotalOnLineTime() {
        return shPreferences.getLong("tatalOnlineTime", 0);
    }

    public long getBackgroundOnLineTime() {
        return shPreferences.getLong("backgroudOnLineTime", 0);
    }

    public long getForegroudOnLineTime() {
        return shPreferences.getLong("foregroudOnLineTime", 0);
    }

    @Override
    public void onDestroy() {
        isLoop = false;
       // edit.clear().commit();
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public class MyBinder extends Binder {
        public long getTotalOnLineTime() {
            return MyService1.this.getTotalOnLineTime();
        }

        public long getBackgroundOnLineTime() {
            return MyService1.this.getBackgroundOnLineTime();
        }

        public long getForegroudOnLineTime() {
            return MyService1.this.getForegroudOnLineTime();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}



package com.example.onlinetimedemo;

import com.example.onlinetimedemo.MyService1.MyBinder;
import com.example.onlinetimedemo.util.StatisticUtil;

import android.R.layout;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private long totalOnLineTime = 0;
    private long foregroudOnLineTime = 0;
    private long backgroundOnLineTime = 0;
    private SharedPreferences shPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        total = (TextView) findViewById(R.id.tatalontime);
        foregroud = (TextView) findViewById(R.id.foreroudontime);
        backgroud = (TextView) findViewById(R.id.backgroudontime);
        shPreferences = getApplication().getSharedPreferences("onlinetime", Context.MODE_PRIVATE);
    }

    public void getTime(View v) {
        total.setText("总台时长 :" + StatisticUtil.getOnLineTime(shPreferences.getLong("tatalOnLineTime", 0)));
        foregroud.setText("前台时长 :" + StatisticUtil.getOnLineTime(shPreferences.getLong("foregroudOnLineTime", 0)));
        backgroud.setText("后台时长 :" + StatisticUtil.getOnLineTime(shPreferences.getLong("backgroudOnLineTime", 0)));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private TextView total;
    private TextView foregroud;
    private TextView backgroud;

    @Override
    protected void onDestroy() {
        // unregisterReceiver(myBroadcastReceive);
        // unbindService(conn);
        // conn = null;
        super.onDestroy();
    }

}



package com.example.onlinetimedemo.util;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;

/*
 import com.android.internal.app.IUsageStats;
 import com.android.internal.os.PkgUsageStats;*/

@SuppressLint("SimpleDateFormat")
public class StatisticUtil {
    private static StatisticUtil statisticalUtils = null;
    private static final String TAG = "ReportStatisticalUtils";
    private static SimpleDateFormat format;
    private StatisticUtil() {
    }

    public static StatisticUtil getInstance() {
        if (statisticalUtils == null) {
            statisticalUtils = new StatisticUtil();
        }
        return statisticalUtils;
    }
    static{
        format = new SimpleDateFormat("yyyy年MM月dd日");
    }
    /**
     * 判断 桌面应用 是否 在前台 运行
     *
     * @param context
     * @return
     */
    public static boolean isTopActivity(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            if ("com.example.onlinetimedemo".equals(tasksInfo.get(0).topActivity.getPackageName())) {
                System.out.println("在前台运行!!!!!!!!!!!!");
                return true;
            }
        }
        return false;
    }

    /**
     * 把 long 型 转换 成 时间
     */
    public static String getOnLineTime(long onlinetime) {
        String date = format.format(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("HH时mm分ss秒");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        return date + ": " + formatter.format(onlinetime);
    }

    /**
     * 格式 分钟 秒钟 时钟 format hour minute and millis
     *
     * @param onlinetime
     * @return
     */
    public static String parseOnLineTime(long onlinetime) {
        int hour;
        int minute;
        int millis;
        StringBuilder sb = new StringBuilder();
        System.out.println(onlinetime);
        hour = (int) onlinetime / (60 * 60 * 1000);
        System.out.println(hour);
        String date = format.format(System.currentTimeMillis());
        if (hour > 0) {
            formatHour(hour, sb);
            minute = (int) ((onlinetime - hour * 60 * 60 * 1000) / (60 * 1000));
            if (minute > 0) {
                formatMinute(minute, sb);
                millis = (int) ((onlinetime - minute * 60 * 1000 - hour * 60 * 60 * 1000) / 1000);
                formatMills(millis, sb);
            } else {
                sb.append("00" + "分");
                millis = (int) ((onlinetime - minute * 60 * 1000 - hour * 60 * 60 * 1000) / 1000);
                formatMills(millis, sb);
            }
        } else {
            sb.append("00" + "时");
            minute = (int) onlinetime / (60 * 1000);
            if (minute > 0) {
                formatMinute(minute, sb);
                millis = (int) ((onlinetime - minute * 60 * 1000) / 1000);
                formatMills(millis, sb);
            } else {
                millis = (int) (onlinetime / 1000);
                sb.append("00" + "分");
                formatMills(millis, sb);
            }
        }
        return date + ": " + sb.toString();
    }

    public static void formatHour(int hour, StringBuilder sb) {
        if (hour <= 9) {
            sb.append("0" + hour + "时");
        } else {
            sb.append(hour + "时");
        }
    }

    public static void formatMinute(int minute, StringBuilder sb) {
        if (minute <= 9) {
            sb.append("0" + minute + "分");
        } else {
            sb.append(minute + "分");
        }
    }

    public static void formatMills(int millis, StringBuilder sb) {
        if (millis <= 9) {
            sb.append("0" + millis + "秒");
        } else {
            sb.append(millis + "秒");
        }
    }
    /*
     * public String getUseTime(String pkName) { IUsageStats mUsageStatsService
     * = IUsageStats.Stub .asInterface(ServiceManager.getService("usagestats"));
     * PkgUsageStats[] stats = null; try { stats =
     * mUsageStatsService.getAllPkgUsageStats(); } catch (RemoteException e) {
     * e.printStackTrace(); return "unsupport"; } if (stats == null) { return
     * ""; } for (PkgUsageStats ps : stats) { if (ps.packageName.equals(pkName))
     * { return String.valueOf(ps.launchCount); } } return "not found"; } public
     * String getUseDuration(String pkName) { IUsageStats mUsageStatsService =
     * IUsageStats.Stub .asInterface(ServiceManager.getService("usagestats"));
     * PkgUsageStats[] stats; try { stats =
     * mUsageStatsService.getAllPkgUsageStats(); } catch (RemoteException e) {
     * e.printStackTrace(); return "unsupport"; } if (stats == null) { return
     * ""; } for (PkgUsageStats ps : stats) { if (ps.packageName.equals(pkName))
     * { return String.valueOf(ps.usageTime); } } return "not found"; }
     */
}



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dip" >

    <TextView
        android:id="@+id/tatalontime"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/foreroudontime"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/backgroudontime"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/mybutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="getTime"
        android:text="获取在线时间" />

</LinearLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值