Просмотр исходного кода

创建应用自动审核对应的service,并移到单独后台进程;
下载无响应修改为只提示一次并使用缓存来控制

zengjiebin лет назад: 7
Родитель
Сommit
8889354a0f
26 измененных файлов с 940 добавлено и 656 удалено
  1. 1 1
      app/build.gradle
  2. 1 1
      app/src/main/AndroidManifest.xml
  3. 102 5
      app/src/main/java/com/sheep/gamegroup/greendao/DDProviderHelper.java
  4. 82 0
      app/src/main/java/com/sheep/gamegroup/greendao/download/AcceptTaskRecord.java
  5. 153 0
      app/src/main/java/com/sheep/gamegroup/greendao/download/AcceptTaskRecordDao.java
  6. 8 2
      app/src/main/java/com/sheep/gamegroup/greendao/download/DaoMaster.java
  7. 28 0
      app/src/main/java/com/sheep/gamegroup/greendao/download/DaoSession.java
  8. 69 0
      app/src/main/java/com/sheep/gamegroup/greendao/download/ProcessRecord.java
  9. 147 0
      app/src/main/java/com/sheep/gamegroup/greendao/download/ProcessRecordDao.java
  10. 1 3
      app/src/main/java/com/sheep/gamegroup/helper/TaskHelper.java
  11. 4 0
      app/src/main/java/com/sheep/gamegroup/model/entity/TaskAcceptedEty.java
  12. 10 2
      app/src/main/java/com/sheep/gamegroup/model/entity/UserEntity.java
  13. 54 191
      app/src/main/java/com/sheep/gamegroup/usage/AppUsageManager.java
  14. 57 10
      app/src/main/java/com/sheep/gamegroup/util/CommonUtil.java
  15. 3 0
      app/src/main/java/com/sheep/gamegroup/util/DataUtil.java
  16. 18 0
      app/src/main/java/com/sheep/gamegroup/util/Jump2View.java
  17. 2 2
      app/src/main/java/com/sheep/gamegroup/util/TestUtil.java
  18. 47 19
      app/src/main/java/com/sheep/gamegroup/view/activity/TaskDetailAct.java
  19. 11 44
      app/src/main/java/com/sheep/gamegroup/view/fragment/FgtPersonalCenter.java
  20. 1 1
      app/src/main/java/com/sheep/gamegroup/view/fragment/FgtSmallSheep.java
  21. 1 8
      app/src/main/java/com/sheep/gamegroup/view/fragment/FgtTryMakeMoney.java
  22. 3 7
      app/src/main/java/com/sheep/jiuyan/samllsheep/SheepApp.java
  23. 113 0
      app/src/main/java/com/sheep/jiuyan/samllsheep/service/AutoCheckService.java
  24. 19 16
      app/src/main/java/com/sheep/jiuyan/samllsheep/service/DownloadService.java
  25. 0 340
      app/src/main/java/com/sheep/jiuyan/samllsheep/service/FloatService.java
  26. 5 4
      app/src/main/java/com/sheep/jiuyan/samllsheep/service/ListenerShotService.java

+ 1 - 1
app/build.gradle

@@ -22,7 +22,7 @@ android {
         multiDexEnabled true
     }
     greendao {
-        schemaVersion 10
+        schemaVersion 11
         targetGenDir 'src/main/java'
     }
 //    compileOptions{

+ 1 - 1
app/src/main/AndroidManifest.xml

@@ -120,7 +120,7 @@
 
         <service android:name=".service.DownloadService" />
         <service
-            android:name=".service.FloatService"/>
+            android:name=".service.AutoCheckService"/>
         <service
             android:name=".service.FloatShotScreenService" />
         <service

+ 102 - 5
app/src/main/java/com/sheep/gamegroup/greendao/DDProviderHelper.java

@@ -1,19 +1,20 @@
 package com.sheep.gamegroup.greendao;
 
-import android.content.ContentResolver;
-import android.content.ContentValues;
 import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-
 
+import com.sheep.gamegroup.greendao.download.AcceptTaskRecord;
+import com.sheep.gamegroup.greendao.download.AcceptTaskRecordDao;
 import com.sheep.gamegroup.greendao.download.DaoMaster;
 import com.sheep.gamegroup.greendao.download.DaoSession;
 import com.sheep.gamegroup.greendao.download.DownLoadInfo;
 import com.sheep.gamegroup.greendao.download.DownLoadInfoDao;
+import com.sheep.gamegroup.greendao.download.ProcessRecord;
+import com.sheep.gamegroup.greendao.download.ProcessRecordDao;
 
 import java.util.List;
 
+import rx.functions.Action1;
+
 /**
  * 端端privoder工具
  *
@@ -253,4 +254,100 @@ public class DDProviderHelper {
             }
         }
     }
+    /**
+     * 添加或更新记录
+     * 添加成功返回true
+     * @param context
+     * @param newInfo
+     */
+    public boolean addOrUpdateProcessRecord(Context context, ProcessRecord newInfo) {
+        return addOrUpdateProcessRecord(context, newInfo, null);
+    }
+    /**
+     * 添加或更新记录
+     * 添加成功返回true
+     * @param context
+     * @param newInfo
+     */
+    public boolean addOrUpdateProcessRecord(Context context, ProcessRecord newInfo, Action1<ProcessRecord> action1) {
+        ProcessRecordDao infoDao = getDaossion(context).getProcessRecordDao();
+        ProcessRecord lastInfo = infoDao
+                .queryBuilder()
+                .where(ProcessRecordDao.Properties.PackageName.eq(newInfo.getPackageName()), ProcessRecordDao.Properties.UserId.eq(newInfo.getUserId()))
+                .build()
+                .unique();
+        try{
+            if(action1 != null)
+                action1.call(lastInfo);
+            if (lastInfo == null) {
+                infoDao.insert(newInfo);
+                return true;
+            } else {
+                newInfo.setId(lastInfo.getId());
+                infoDao.update(newInfo);
+            }
+        }catch (Exception e){
+            e.printStackTrace();
+        }
+        return false;
+    }
+    /**
+     * 根据包名获取进程运行的记录,5.0及其以下使用
+     *
+     * @param packageName
+     */
+    public ProcessRecord getProcessRecord(Context context, String packageName) {
+        ProcessRecord processRecord = getDaossion(context)
+                .getProcessRecordDao()
+                .queryBuilder()
+                .where(ProcessRecordDao.Properties.PackageName.eq(packageName))
+                .build()
+                .unique();
+        return processRecord == null ? new ProcessRecord(): processRecord;
+    }
+    /**
+     * 添加记录
+     * 添加成功返回true
+     * @param context
+     * @param newInfo
+     */
+    public boolean addAcceptTaskRecord(Context context, AcceptTaskRecord newInfo) {
+        try{
+            AcceptTaskRecordDao infoDao = getDaossion(context).getAcceptTaskRecordDao();
+            infoDao.insert(newInfo);
+        }catch (Exception e){
+            e.printStackTrace();
+            return false;
+        }
+        return true;
+    }
+    /**
+     * 更新记录
+     * 添加成功返回true
+     * @param context
+     * @param newInfo
+     */
+    public boolean updateAcceptTaskRecord(Context context, AcceptTaskRecord newInfo) {
+        try{
+            AcceptTaskRecordDao infoDao = getDaossion(context).getAcceptTaskRecordDao();
+            infoDao.update(newInfo);
+        }catch (Exception e){
+            e.printStackTrace();
+            return false;
+        }
+        return true;
+    }
+    /**
+     * 根据包名获取接受的自动审核任务的记录,5.1及其以上使用
+     *
+     * @param packageName
+     */
+    public AcceptTaskRecord getAcceptTaskRecord(Context context, String packageName) {
+        return getDaossion(context)
+                .getAcceptTaskRecordDao()
+                .queryBuilder()
+                .where(AcceptTaskRecordDao.Properties.PackageName.eq(packageName))
+                .build()
+                .unique();
+    }
 }

+ 82 - 0
app/src/main/java/com/sheep/gamegroup/greendao/download/AcceptTaskRecord.java

@@ -0,0 +1,82 @@
+package com.sheep.gamegroup.greendao.download;
+
+import org.greenrobot.greendao.annotation.Entity;
+import org.greenrobot.greendao.annotation.Id;
+import org.greenrobot.greendao.annotation.Property;
+import org.greenrobot.greendao.annotation.Generated;
+
+/**
+ * Created by realicing on 2018/9/25.
+ * realicing@sina.com
+ * 接受的自动审核任务运行时长记录表---5.1及其以上使用
+ */
+@Entity
+public class AcceptTaskRecord {
+    /**
+     * id,
+     */
+    @Id(autoincrement = true)
+    private Long id;
+    /**
+     * 用户id
+     */
+    @Property(nameInDb = "user_id")
+    private String userId;
+    /**
+     * 包名
+     */
+    @Property(nameInDb = "package_name")
+    private String packageName;
+    /**
+     * 接受任务时间
+     */
+    @Property(nameInDb = "accept_time")
+    private long acceptTime;
+    /**
+     * 运行时长
+     */
+    @Property(nameInDb = "run_time")
+    private long runTime;
+    public long getAcceptTime() {
+        return this.acceptTime;
+    }
+    public void setAcceptTime(long acceptTime) {
+        this.acceptTime = acceptTime;
+    }
+    public String getPackageName() {
+        return this.packageName;
+    }
+    public void setPackageName(String packageName) {
+        this.packageName = packageName;
+    }
+    public String getUserId() {
+        return this.userId;
+    }
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+    public Long getId() {
+        return this.id;
+    }
+    public void setId(Long id) {
+        this.id = id;
+    }
+    public long getRunTime() {
+        return this.runTime;
+    }
+    public void setRunTime(long runTime) {
+        this.runTime = runTime;
+    }
+    @Generated(hash = 1680818821)
+    public AcceptTaskRecord(Long id, String userId, String packageName,
+            long acceptTime, long runTime) {
+        this.id = id;
+        this.userId = userId;
+        this.packageName = packageName;
+        this.acceptTime = acceptTime;
+        this.runTime = runTime;
+    }
+    @Generated(hash = 889588615)
+    public AcceptTaskRecord() {
+    }
+}

+ 153 - 0
app/src/main/java/com/sheep/gamegroup/greendao/download/AcceptTaskRecordDao.java

@@ -0,0 +1,153 @@
+package com.sheep.gamegroup.greendao.download;
+
+import android.database.Cursor;
+import android.database.sqlite.SQLiteStatement;
+
+import org.greenrobot.greendao.AbstractDao;
+import org.greenrobot.greendao.Property;
+import org.greenrobot.greendao.internal.DaoConfig;
+import org.greenrobot.greendao.database.Database;
+import org.greenrobot.greendao.database.DatabaseStatement;
+
+// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
+/** 
+ * DAO for table "ACCEPT_TASK_RECORD".
+*/
+public class AcceptTaskRecordDao extends AbstractDao<AcceptTaskRecord, Long> {
+
+    public static final String TABLENAME = "ACCEPT_TASK_RECORD";
+
+    /**
+     * Properties of entity AcceptTaskRecord.<br/>
+     * Can be used for QueryBuilder and for referencing column names.
+     */
+    public static class Properties {
+        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
+        public final static Property UserId = new Property(1, String.class, "userId", false, "user_id");
+        public final static Property PackageName = new Property(2, String.class, "packageName", false, "package_name");
+        public final static Property AcceptTime = new Property(3, long.class, "acceptTime", false, "accept_time");
+        public final static Property RunTime = new Property(4, long.class, "runTime", false, "run_time");
+    }
+
+
+    public AcceptTaskRecordDao(DaoConfig config) {
+        super(config);
+    }
+    
+    public AcceptTaskRecordDao(DaoConfig config, DaoSession daoSession) {
+        super(config, daoSession);
+    }
+
+    /** Creates the underlying database table. */
+    public static void createTable(Database db, boolean ifNotExists) {
+        String constraint = ifNotExists? "IF NOT EXISTS ": "";
+        db.execSQL("CREATE TABLE " + constraint + "\"ACCEPT_TASK_RECORD\" (" + //
+                "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
+                "\"user_id\" TEXT," + // 1: userId
+                "\"package_name\" TEXT," + // 2: packageName
+                "\"accept_time\" INTEGER NOT NULL ," + // 3: acceptTime
+                "\"run_time\" INTEGER NOT NULL );"); // 4: runTime
+    }
+
+    /** Drops the underlying database table. */
+    public static void dropTable(Database db, boolean ifExists) {
+        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"ACCEPT_TASK_RECORD\"";
+        db.execSQL(sql);
+    }
+
+    @Override
+    protected final void bindValues(DatabaseStatement stmt, AcceptTaskRecord entity) {
+        stmt.clearBindings();
+ 
+        Long id = entity.getId();
+        if (id != null) {
+            stmt.bindLong(1, id);
+        }
+ 
+        String userId = entity.getUserId();
+        if (userId != null) {
+            stmt.bindString(2, userId);
+        }
+ 
+        String packageName = entity.getPackageName();
+        if (packageName != null) {
+            stmt.bindString(3, packageName);
+        }
+        stmt.bindLong(4, entity.getAcceptTime());
+        stmt.bindLong(5, entity.getRunTime());
+    }
+
+    @Override
+    protected final void bindValues(SQLiteStatement stmt, AcceptTaskRecord entity) {
+        stmt.clearBindings();
+ 
+        Long id = entity.getId();
+        if (id != null) {
+            stmt.bindLong(1, id);
+        }
+ 
+        String userId = entity.getUserId();
+        if (userId != null) {
+            stmt.bindString(2, userId);
+        }
+ 
+        String packageName = entity.getPackageName();
+        if (packageName != null) {
+            stmt.bindString(3, packageName);
+        }
+        stmt.bindLong(4, entity.getAcceptTime());
+        stmt.bindLong(5, entity.getRunTime());
+    }
+
+    @Override
+    public Long readKey(Cursor cursor, int offset) {
+        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
+    }    
+
+    @Override
+    public AcceptTaskRecord readEntity(Cursor cursor, int offset) {
+        AcceptTaskRecord entity = new AcceptTaskRecord( //
+            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
+            cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // userId
+            cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // packageName
+            cursor.getLong(offset + 3), // acceptTime
+            cursor.getLong(offset + 4) // runTime
+        );
+        return entity;
+    }
+     
+    @Override
+    public void readEntity(Cursor cursor, AcceptTaskRecord entity, int offset) {
+        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
+        entity.setUserId(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
+        entity.setPackageName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
+        entity.setAcceptTime(cursor.getLong(offset + 3));
+        entity.setRunTime(cursor.getLong(offset + 4));
+     }
+    
+    @Override
+    protected final Long updateKeyAfterInsert(AcceptTaskRecord entity, long rowId) {
+        entity.setId(rowId);
+        return rowId;
+    }
+    
+    @Override
+    public Long getKey(AcceptTaskRecord entity) {
+        if(entity != null) {
+            return entity.getId();
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public boolean hasKey(AcceptTaskRecord entity) {
+        return entity.getId() != null;
+    }
+
+    @Override
+    protected final boolean isEntityUpdateable() {
+        return true;
+    }
+    
+}

+ 8 - 2
app/src/main/java/com/sheep/gamegroup/greendao/download/DaoMaster.java

@@ -14,21 +14,25 @@ import org.greenrobot.greendao.identityscope.IdentityScopeType;
 
 // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
 /**
- * Master of DAO (schema version 10): knows all DAOs.
+ * Master of DAO (schema version 11): knows all DAOs.
  */
 public class DaoMaster extends AbstractDaoMaster {
-    public static final int SCHEMA_VERSION = 10;
+    public static final int SCHEMA_VERSION = 11;
 
     /** Creates underlying database table using DAOs. */
     public static void createAllTables(Database db, boolean ifNotExists) {
         AppdownloadBeanDao.createTable(db, ifNotExists);
         DownLoadInfoDao.createTable(db, ifNotExists);
+        ProcessRecordDao.createTable(db, ifNotExists);
+        AcceptTaskRecordDao.createTable(db, ifNotExists);
     }
 
     /** Drops underlying database table using DAOs. */
     public static void dropAllTables(Database db, boolean ifExists) {
         AppdownloadBeanDao.dropTable(db, ifExists);
         DownLoadInfoDao.dropTable(db, ifExists);
+        ProcessRecordDao.dropTable(db, ifExists);
+        AcceptTaskRecordDao.dropTable(db, ifExists);
     }
 
     /**
@@ -49,6 +53,8 @@ public class DaoMaster extends AbstractDaoMaster {
         super(db, SCHEMA_VERSION);
         registerDaoClass(AppdownloadBeanDao.class);
         registerDaoClass(DownLoadInfoDao.class);
+        registerDaoClass(ProcessRecordDao.class);
+        registerDaoClass(AcceptTaskRecordDao.class);
     }
 
     public DaoSession newSession() {

+ 28 - 0
app/src/main/java/com/sheep/gamegroup/greendao/download/DaoSession.java

@@ -10,9 +10,13 @@ import org.greenrobot.greendao.internal.DaoConfig;
 
 import com.sheep.gamegroup.greendao.download.AppdownloadBean;
 import com.sheep.gamegroup.greendao.download.DownLoadInfo;
+import com.sheep.gamegroup.greendao.download.ProcessRecord;
+import com.sheep.gamegroup.greendao.download.AcceptTaskRecord;
 
 import com.sheep.gamegroup.greendao.download.AppdownloadBeanDao;
 import com.sheep.gamegroup.greendao.download.DownLoadInfoDao;
+import com.sheep.gamegroup.greendao.download.ProcessRecordDao;
+import com.sheep.gamegroup.greendao.download.AcceptTaskRecordDao;
 
 // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
 
@@ -25,9 +29,13 @@ public class DaoSession extends AbstractDaoSession {
 
     private final DaoConfig appdownloadBeanDaoConfig;
     private final DaoConfig downLoadInfoDaoConfig;
+    private final DaoConfig processRecordDaoConfig;
+    private final DaoConfig acceptTaskRecordDaoConfig;
 
     private final AppdownloadBeanDao appdownloadBeanDao;
     private final DownLoadInfoDao downLoadInfoDao;
+    private final ProcessRecordDao processRecordDao;
+    private final AcceptTaskRecordDao acceptTaskRecordDao;
 
     public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
             daoConfigMap) {
@@ -39,16 +47,28 @@ public class DaoSession extends AbstractDaoSession {
         downLoadInfoDaoConfig = daoConfigMap.get(DownLoadInfoDao.class).clone();
         downLoadInfoDaoConfig.initIdentityScope(type);
 
+        processRecordDaoConfig = daoConfigMap.get(ProcessRecordDao.class).clone();
+        processRecordDaoConfig.initIdentityScope(type);
+
+        acceptTaskRecordDaoConfig = daoConfigMap.get(AcceptTaskRecordDao.class).clone();
+        acceptTaskRecordDaoConfig.initIdentityScope(type);
+
         appdownloadBeanDao = new AppdownloadBeanDao(appdownloadBeanDaoConfig, this);
         downLoadInfoDao = new DownLoadInfoDao(downLoadInfoDaoConfig, this);
+        processRecordDao = new ProcessRecordDao(processRecordDaoConfig, this);
+        acceptTaskRecordDao = new AcceptTaskRecordDao(acceptTaskRecordDaoConfig, this);
 
         registerDao(AppdownloadBean.class, appdownloadBeanDao);
         registerDao(DownLoadInfo.class, downLoadInfoDao);
+        registerDao(ProcessRecord.class, processRecordDao);
+        registerDao(AcceptTaskRecord.class, acceptTaskRecordDao);
     }
     
     public void clear() {
         appdownloadBeanDaoConfig.clearIdentityScope();
         downLoadInfoDaoConfig.clearIdentityScope();
+        processRecordDaoConfig.clearIdentityScope();
+        acceptTaskRecordDaoConfig.clearIdentityScope();
     }
 
     public AppdownloadBeanDao getAppdownloadBeanDao() {
@@ -59,4 +79,12 @@ public class DaoSession extends AbstractDaoSession {
         return downLoadInfoDao;
     }
 
+    public ProcessRecordDao getProcessRecordDao() {
+        return processRecordDao;
+    }
+
+    public AcceptTaskRecordDao getAcceptTaskRecordDao() {
+        return acceptTaskRecordDao;
+    }
+
 }

+ 69 - 0
app/src/main/java/com/sheep/gamegroup/greendao/download/ProcessRecord.java

@@ -0,0 +1,69 @@
+package com.sheep.gamegroup.greendao.download;
+
+import org.greenrobot.greendao.annotation.Entity;
+import org.greenrobot.greendao.annotation.Id;
+import org.greenrobot.greendao.annotation.Property;
+import org.greenrobot.greendao.annotation.Generated;
+
+/**
+ * Created by realicing on 2018/9/21.
+ * realicing@sina.com
+ * 进程运行时长记录表---5.0及其以下使用
+ */
+@Entity
+public class ProcessRecord {
+    /**
+     * id,
+     */
+    @Id(autoincrement = true)
+    private Long id;
+    /**
+     * 用户id
+     */
+    @Property(nameInDb = "user_id")
+    private String userId;
+    /**
+     * 包名
+     */
+    @Property(nameInDb = "package_name")
+    private String packageName;
+    /**
+     * 运行时长
+     */
+    @Property(nameInDb = "run_time")
+    private int runTime;
+    public int getRunTime() {
+        return this.runTime;
+    }
+    public void setRunTime(int runTime) {
+        this.runTime = runTime;
+    }
+    public String getPackageName() {
+        return this.packageName;
+    }
+    public void setPackageName(String packageName) {
+        this.packageName = packageName;
+    }
+    public String getUserId() {
+        return this.userId;
+    }
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+    public Long getId() {
+        return this.id;
+    }
+    public void setId(Long id) {
+        this.id = id;
+    }
+    @Generated(hash = 1731687783)
+    public ProcessRecord(Long id, String userId, String packageName, int runTime) {
+        this.id = id;
+        this.userId = userId;
+        this.packageName = packageName;
+        this.runTime = runTime;
+    }
+    @Generated(hash = 9957031)
+    public ProcessRecord() {
+    }
+}

+ 147 - 0
app/src/main/java/com/sheep/gamegroup/greendao/download/ProcessRecordDao.java

@@ -0,0 +1,147 @@
+package com.sheep.gamegroup.greendao.download;
+
+import android.database.Cursor;
+import android.database.sqlite.SQLiteStatement;
+
+import org.greenrobot.greendao.AbstractDao;
+import org.greenrobot.greendao.Property;
+import org.greenrobot.greendao.internal.DaoConfig;
+import org.greenrobot.greendao.database.Database;
+import org.greenrobot.greendao.database.DatabaseStatement;
+
+// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
+/** 
+ * DAO for table "PROCESS_RECORD".
+*/
+public class ProcessRecordDao extends AbstractDao<ProcessRecord, Long> {
+
+    public static final String TABLENAME = "PROCESS_RECORD";
+
+    /**
+     * Properties of entity ProcessRecord.<br/>
+     * Can be used for QueryBuilder and for referencing column names.
+     */
+    public static class Properties {
+        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
+        public final static Property UserId = new Property(1, String.class, "userId", false, "user_id");
+        public final static Property PackageName = new Property(2, String.class, "packageName", false, "package_name");
+        public final static Property RunTime = new Property(3, int.class, "runTime", false, "run_time");
+    }
+
+
+    public ProcessRecordDao(DaoConfig config) {
+        super(config);
+    }
+    
+    public ProcessRecordDao(DaoConfig config, DaoSession daoSession) {
+        super(config, daoSession);
+    }
+
+    /** Creates the underlying database table. */
+    public static void createTable(Database db, boolean ifNotExists) {
+        String constraint = ifNotExists? "IF NOT EXISTS ": "";
+        db.execSQL("CREATE TABLE " + constraint + "\"PROCESS_RECORD\" (" + //
+                "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
+                "\"user_id\" TEXT," + // 1: userId
+                "\"package_name\" TEXT," + // 2: packageName
+                "\"run_time\" INTEGER NOT NULL );"); // 3: runTime
+    }
+
+    /** Drops the underlying database table. */
+    public static void dropTable(Database db, boolean ifExists) {
+        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"PROCESS_RECORD\"";
+        db.execSQL(sql);
+    }
+
+    @Override
+    protected final void bindValues(DatabaseStatement stmt, ProcessRecord entity) {
+        stmt.clearBindings();
+ 
+        Long id = entity.getId();
+        if (id != null) {
+            stmt.bindLong(1, id);
+        }
+ 
+        String userId = entity.getUserId();
+        if (userId != null) {
+            stmt.bindString(2, userId);
+        }
+ 
+        String packageName = entity.getPackageName();
+        if (packageName != null) {
+            stmt.bindString(3, packageName);
+        }
+        stmt.bindLong(4, entity.getRunTime());
+    }
+
+    @Override
+    protected final void bindValues(SQLiteStatement stmt, ProcessRecord entity) {
+        stmt.clearBindings();
+ 
+        Long id = entity.getId();
+        if (id != null) {
+            stmt.bindLong(1, id);
+        }
+ 
+        String userId = entity.getUserId();
+        if (userId != null) {
+            stmt.bindString(2, userId);
+        }
+ 
+        String packageName = entity.getPackageName();
+        if (packageName != null) {
+            stmt.bindString(3, packageName);
+        }
+        stmt.bindLong(4, entity.getRunTime());
+    }
+
+    @Override
+    public Long readKey(Cursor cursor, int offset) {
+        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
+    }    
+
+    @Override
+    public ProcessRecord readEntity(Cursor cursor, int offset) {
+        ProcessRecord entity = new ProcessRecord( //
+            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
+            cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // userId
+            cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // packageName
+            cursor.getInt(offset + 3) // runTime
+        );
+        return entity;
+    }
+     
+    @Override
+    public void readEntity(Cursor cursor, ProcessRecord entity, int offset) {
+        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
+        entity.setUserId(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
+        entity.setPackageName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
+        entity.setRunTime(cursor.getInt(offset + 3));
+     }
+    
+    @Override
+    protected final Long updateKeyAfterInsert(ProcessRecord entity, long rowId) {
+        entity.setId(rowId);
+        return rowId;
+    }
+    
+    @Override
+    public Long getKey(ProcessRecord entity) {
+        if(entity != null) {
+            return entity.getId();
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public boolean hasKey(ProcessRecord entity) {
+        return entity.getId() != null;
+    }
+
+    @Override
+    protected final boolean isEntityUpdateable() {
+        return true;
+    }
+    
+}

+ 1 - 3
app/src/main/java/com/sheep/gamegroup/helper/TaskHelper.java

@@ -17,13 +17,11 @@ import com.sheep.gamegroup.model.entity.TaskEty;
 import com.sheep.gamegroup.model.entity.TaskReleaseEty;
 import com.sheep.gamegroup.model.util.SheepSubscriber;
 import com.sheep.gamegroup.util.CommonUtil;
-import com.sheep.gamegroup.util.DataUtil;
 import com.sheep.gamegroup.util.GlideImageLoader;
 import com.sheep.gamegroup.util.Jump2View;
 import com.sheep.gamegroup.util.ListUtil;
 import com.sheep.gamegroup.util.RxjavaCountDownTimer;
 import com.sheep.gamegroup.util.TimeUtil;
-import com.sheep.gamegroup.util.UMConfigUtils;
 import com.sheep.gamegroup.util.ViewUtil;
 import com.sheep.jiuyan.samllsheep.R;
 import com.sheep.jiuyan.samllsheep.SheepApp;
@@ -245,7 +243,7 @@ public class TaskHelper {
                                             .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                                                 @Override
                                                 public void onNext(BaseMessage baseMessage) {
-                                                    CommonUtil.getInstance().setTAskEnty(null);
+                                                    CommonUtil.getInstance().updateAutoCheck(null);
                                                     refreshTask();
                                                 }
 

+ 4 - 0
app/src/main/java/com/sheep/gamegroup/model/entity/TaskAcceptedEty.java

@@ -170,4 +170,8 @@ public class TaskAcceptedEty implements Serializable{
     public boolean isIs_running() {
         return status == 1 || status == 2;
     }
+
+    public static final int IS_SUCCESSION_ALL = 3;//所有
+    public static final int SHOW_GAME_TASK_NO = 0;//不获取游戏任务
+    public static final int SHOW_GAME_TASK_YES = 1;//要获取游戏任务
 }

+ 10 - 2
app/src/main/java/com/sheep/gamegroup/model/entity/UserEntity.java

@@ -78,10 +78,10 @@ public class UserEntity implements Serializable {
     private int gender;
     @Column(name = "birthday")
     private String birthday;
-    @Column(name = "package_cate")
+    @Column(name = "package_cate")//1官方包  2邀请包
     private int package_cate;
     @Column(name = "create_time_line")
-    private int create_time_line;
+    private int create_time_line;//1:小绵羊3.0之前的用户(注:以后如果再次有这种区分之前用户的需求就陆续加一)
     @Column(name = "bind_flag")
     private int bind_flag;//绑定表示 二进制形式 从低到高 第一位手机号 第二位QQ号 第三位微信
 
@@ -391,4 +391,12 @@ public class UserEntity implements Serializable {
     public boolean isBindWx(){
         return BinaryUtils.is(bind_flag, 3);
     }
+
+    /**
+     * 是否是官方包注册用户
+     * @return
+     */
+    public boolean isKfzsPackageUser() {
+        return !TextUtils.isEmpty(parent_code) || (create_time_line < 2) || (package_cate == 1);
+    }
 }

+ 54 - 191
app/src/main/java/com/sheep/gamegroup/usage/AppUsageManager.java

@@ -1,44 +1,32 @@
 package com.sheep.gamegroup.usage;
 
-import android.annotation.SuppressLint;
-import android.app.Activity;
 import android.app.AppOpsManager;
-import android.app.Service;
-import android.app.usage.UsageEvents;
 import android.app.usage.UsageStats;
 import android.app.usage.UsageStatsManager;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
 import android.os.Build;
 import android.provider.Settings;
 import android.support.v7.app.AlertDialog;
 import android.text.TextUtils;
 import android.view.View;
 
-import com.kfzs.duanduan.utils.ApkUtils;
-import com.sheep.gamegroup.model.entity.AppRecord;
 import com.sheep.gamegroup.model.entity.AppUsage;
 import com.sheep.gamegroup.model.entity.DialogConfig;
-import com.sheep.gamegroup.model.entity.UserAssets;
 import com.sheep.gamegroup.model.util.AutoTaskListUtil;
 import com.sheep.gamegroup.util.ActivityManager;
 import com.sheep.gamegroup.util.DataUtil;
 import com.sheep.gamegroup.util.ListUtil;
 import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.MyDbManager;
-import com.sheep.gamegroup.util.SysAppUtil;
 import com.sheep.gamegroup.util.ViewUtil;
 import com.sheep.jiuyan.samllsheep.SheepApp;
 import com.sheep.jiuyan.samllsheep.utils.G;
 
 import java.util.Calendar;
 import java.util.Date;
-import java.util.HashMap;
 import java.util.List;
-import java.util.TreeMap;
 
 import static android.content.Context.USAGE_STATS_SERVICE;
 
@@ -59,83 +47,12 @@ public class AppUsageManager {
         return instance;
     }
 
-    //记录前台app运行时长
-    public void recordCurrentAppUsage() {
-//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//android 7.0以上不支持
-//            return;
-//        }
-//        List<AndroidAppProcess> processes = AndroidProcesses.getRunningForegroundApps(SheepApp.getInstance());
-//        AndroidAppProcess androidAppProcess = ListUtil.getLast(processes);
-//        if (androidAppProcess != null) {
-//            String packageName = androidAppProcess.name;
-//            String appName = null;
-//            try {
-//                PackageInfo packageInfo = androidAppProcess.getPackageInfo(SheepApp.getInstance(), 0);
-//                appName = packageInfo.applicationInfo.loadLabel(SheepApp.getInstance().getPackageManager()).toString();
-//
-//                LogUtil.println("getAppTime", appName, packageName);
-//            } catch (PackageManager.NameNotFoundException e) {
-//                e.printStackTrace();
-//            }
-
-        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {//android 5.0以上不支持
-            return;
-        }
-        android.app.ActivityManager.RunningAppProcessInfo process = getAppProcessInfoInForeground();
-        if (process != null) {
-//                LogUtil.println("getRunningAppProcesses", process.processName, process.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND);
-            String packageName = process.processName;//没有packageName字段,可能会出问题
-            String appName = null;
-            PackageInfo packageInfo = ApkUtils.getPackageInfo(SheepApp.getInstance().getPackageName());
-            if (packageInfo != null)
-                appName = packageInfo.applicationInfo.loadLabel(SheepApp.getInstance().getPackageManager()).toString();
-
-            LogUtil.println("getAppTime", appName, packageName);
-
-            if (AutoTaskListUtil.getInstance().isLastAppRecord(packageName)) {//仍然是之前的app
-                return;
-            }
-
-            long curTime = System.currentTimeMillis();
-            AppRecord appRecord = new AppRecord();
-            appRecord.setPackageName(packageName);
-            if (appName != null)
-                appRecord.setTag(appName);
-
-            AppRecord lastAppRecord = AutoTaskListUtil.getInstance().getLastAppRecord();
-            long lastTime = AutoTaskListUtil.getInstance().getLastTime();
-            if (lastAppRecord != null && lastTime != 0)
-                lastAppRecord.setTime(lastAppRecord.getTime() + curTime - lastTime);
-            if (lastAppRecord != null && AutoTaskListUtil.getInstance().hasTask(lastAppRecord)) {
-                MyDbManager.getInstance().saveOrUpdate(lastAppRecord);
-                LogUtil.println("AppUsageManager", "recordCurrentAppUsage", "MyDbManager", "saveOrUpdate", "lastAppRecord", lastAppRecord.getPackageName(), lastAppRecord.getTime());
-            }
-
-            AutoTaskListUtil.getInstance().setLastTime(curTime);
-            AutoTaskListUtil.getInstance().setLastAppRecord(appRecord);
-        }
-    }
-
-    private android.app.ActivityManager.RunningAppProcessInfo getAppProcessInfoInForeground() {
-        android.app.ActivityManager manager = (android.app.ActivityManager) SheepApp.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
-        List<android.app.ActivityManager.RunningAppProcessInfo> processList = manager == null ? null : manager.getRunningAppProcesses();
-        if(!ListUtil.isEmpty(processList)){
-            for (android.app.ActivityManager.RunningAppProcessInfo item : processList) {
-                if(item != null && item.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
-                    return item;
-                }
-            }
-        }
-        return null;
-    }
-
     /**
      * 需要开启查看应用使用情况的权限
      *
      * @return
      */
-    @SuppressLint("NewApi")
-    public  boolean needOpenLookAppUsageStatsPermisson(boolean isSaveData){
+    public  boolean needOpenLookAppUsageStatsPermission(boolean isSaveData){
         if(android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){   // 如果大于等于5.1 再做判断
             long time = System.currentTimeMillis();
             UsageStatsManager usageStatsManager=(UsageStatsManager)SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
@@ -164,41 +81,41 @@ public class AppUsageManager {
      * 尝试打开权限对话框 5.1及以上使用
      * @param isSaveData 是否保存AppUsage数据,因为AppUsage通过系统获取的数据转化而来,而且,不切换应用时不会改变,而要实时显示时间就必须缓冲数据
      */
-    public void tryOpenLookAppUsageStatsPermisson(boolean isSaveData) {
-        if (!needOpenLookAppUsageStatsPermisson(isSaveData)) {//不需要开启
+    public void tryOpenLookAppUsageStatsPermission(boolean isSaveData) {
+        if (!needOpenLookAppUsageStatsPermission(isSaveData)) {//不需要开启
             return;
         }
         if(AutoTaskListUtil.getInstance().isShowing()){//对话框仍在显示,就不显示 打开权限功能的对话框
             return;
         }
-        LogUtil.println("tryOpenLookAppUsageStatsPermisson", "start");
+        LogUtil.println("tryOpenLookAppUsageStatsPermission", "start");
         AutoTaskListUtil.getInstance().clearAlertDialog();
         if(!AutoTaskListUtil.getInstance().isEmpty() || DataUtil.IS_LISTEN_SCREEN_SHOT){
-            LogUtil.println("tryOpenLookAppUsageStatsPermisson", "notEmpty");
+            LogUtil.println("tryOpenLookAppUsageStatsPermission", "notEmpty");
             showAccessibilityDialog();
         } else {
-            LogUtil.println("tryOpenLookAppUsageStatsPermisson","else");
+            LogUtil.println("tryOpenLookAppUsageStatsPermission","else");
         }
-        LogUtil.println("tryOpenLookAppUsageStatsPermisson","end");
+        LogUtil.println("tryOpenLookAppUsageStatsPermission","end");
     }
     public void showAccessibilityDialog() {
-        AlertDialog tipToOpernAccessibilityDialog = ViewUtil.showMsgDialog(ActivityManager.getInstance().currentActivity(), new DialogConfig().setTitle("温馨提示!")
+        AlertDialog tipToOpenAccessibilityDialog = ViewUtil.showMsgDialog(ActivityManager.getInstance().currentActivity(), new DialogConfig().setTitle("温馨提示!")
                 .setMsg("亲!系统检测到您需要手动开启小绵羊查看应用情况的权限才能继续任务!")
                 .setBtnLeftText("去开启").setBtnLeftOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {
-                        openLookAppUsageStatsPermisson();
+                        openLookAppUsageStatsPermission();
                     }
                 }));
-        tipToOpernAccessibilityDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
+        tipToOpenAccessibilityDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
             @Override
             public void onDismiss(DialogInterface dialogInterface) {
                 AutoTaskListUtil.getInstance().clearAlertDialog();
             }
         });
-        AutoTaskListUtil.getInstance().setTipToOpernAccessibilityDialog(tipToOpernAccessibilityDialog);
+        AutoTaskListUtil.getInstance().setTipToOpernAccessibilityDialog(tipToOpenAccessibilityDialog);
     }
-    public void openLookAppUsageStatsPermisson(){
+    public void openLookAppUsageStatsPermission(){
         if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
             try {
                 Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
@@ -210,89 +127,6 @@ public class AppUsageManager {
             }
         }
     }
-    private HashMap<String, Long> totalTimeMap = new HashMap<>();
-    private HashMap<String, Long> timeMap = new HashMap<>();
-    public long getTotalTimeInForeground(String packageName) {
-        AppUsage appUsage = new AppUsage();
-        appUsage.setPackageName(packageName);
-        return getTotalTimeInForeground(appUsage);
-    }
-    @SuppressLint("NewApi")
-    public long getTotalTimeInForeground(AppUsage appUsage) {
-        String packageName = appUsage.getPackageName();
-        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
-            UsageStatsManager mUsageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);//usagestats
-            long time = System.currentTimeMillis();
-            if(mUsageStatsManager != null) {
-                List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, AutoTaskListUtil.getInstance().getReceiveTaskTime(), time);
-
-                if (usageStatsList != null && !usageStatsList.isEmpty()) {
-                    if(packageName == null){//为空时需要获取前台的packageName
-                        TreeMap<Long,UsageStats> mySortedMap = new TreeMap<>();
-                        for (UsageStats item : usageStatsList) {
-                            mySortedMap.put(item.getLastTimeUsed(),item);
-                        }
-
-                        UsageStats usageStats = mySortedMap.get(mySortedMap.lastKey());
-
-                        packageName = usageStats.getPackageName();
-                        appUsage.setPackageName(packageName);
-                        long totalTime = usageStats.getTotalTimeInForeground();
-                        long saveTotalTime = MyDbManager.getInstance().getAppUsageTime(packageName);
-                        if((saveTotalTime <= 0 || saveTotalTime > totalTime) && totalTime > 0){
-                            appUsage.setTotalTimeInForeground(totalTime);
-                            MyDbManager.getInstance().saveOrUpdate(appUsage);
-                        }
-                        if (totalTimeMap.containsKey(packageName) && totalTimeMap.get(packageName) == totalTime) {
-                            totalTime += time - timeMap.get(packageName);
-                        } else {
-                            totalTimeMap.put(packageName, totalTime);
-                            timeMap.put(packageName, time);
-                        }
-                        return Math.max(0, totalTime - saveTotalTime);
-                    } else {//小绵羊在前台时调用
-                        for (UsageStats usageStats : usageStatsList) {
-                            if (usageStats != null && TextUtils.equals(packageName, usageStats.getPackageName())) {
-                                long saveTotalTime = MyDbManager.getInstance().getAppUsageTime(packageName);
-                                long totalTime = usageStats.getTotalTimeInForeground();
-                                return Math.max(0, totalTime - saveTotalTime);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        if(packageName == null) {//为空时需要获取前台的packageName
-//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//android 7.0以上不支持
-//                return 0;
-//            }
-            //compile 'com.jaredrummler:android-processes:1.1.1'
-//            List<AndroidAppProcess> processes = AndroidProcesses.getRunningForegroundApps(SheepApp.getInstance());
-//            AndroidAppProcess androidAppProcess = ListUtil.getLast(processes);
-//            if (androidAppProcess != null) {
-//                packageName = androidAppProcess.name;
-//                appUsage.setPackageName(packageName);
-//            }
-
-            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {//android 5.0以上不支持
-                return 0;
-            }
-            android.app.ActivityManager.RunningAppProcessInfo process = getAppProcessInfoInForeground();
-            if(process != null ) {
-                packageName = process.processName;//没有packageName字段,可能会出问题
-                appUsage.setPackageName(packageName);
-            }
-            if(TextUtils.isEmpty(packageName)){//没有获取到当前正在运行的应用
-                return 0;
-            }
-        }
-        long runTime = MyDbManager.getInstance().getAppRunTime(packageName);
-
-        if(AutoTaskListUtil.getInstance().isLastAppRecord(packageName)){
-            runTime +=  System.currentTimeMillis() - AutoTaskListUtil.getInstance().getLastTime();
-        }
-        return runTime;
-    }
 
     public void println() {
         if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
@@ -316,22 +150,51 @@ public class AppUsageManager {
      * 获取应用最后使用时间
      * 24*60*60*1000
      */
-    public long getAppLastUseTime(String pakageName, long intervalTime){
-        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
-            Calendar calendar=Calendar.getInstance();
+    public long getAppLastUseTime(String packageName, long intervalTime){
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
+            Calendar calendar = Calendar.getInstance();
             calendar.setTime(new Date());
-            long endt = calendar.getTimeInMillis();//结束时间
+            long endTime = calendar.getTimeInMillis();//结束时间
             calendar.add(Calendar.DAY_OF_MONTH, -1);//时间间隔为一个月
-            long statt = calendar.getTimeInMillis();//开始时间
-            long time =System.currentTimeMillis()-intervalTime;
-            UsageStatsManager usageStatsManager=(UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
-            //获取一个月内的信息
-            List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,statt,endt);
-            if(queryUsageStats != null && queryUsageStats.size() > 0){
-                for(UsageStats usageStats: queryUsageStats){
-                    if(usageStats.getPackageName().equals(pakageName)){
-                        return usageStats.getLastTimeUsed();
+            long startTime = calendar.getTimeInMillis();//开始时间
+            UsageStatsManager usageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
+            if (usageStatsManager != null) {
+                //获取一个月内的信息
+                List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, startTime, endTime);
+                if (queryUsageStats != null && queryUsageStats.size() > 0) {
+                    for (UsageStats usageStats : queryUsageStats) {
+                        if (usageStats.getPackageName().equals(packageName)) {
+                            return usageStats.getLastTimeUsed();
+                        }
+                    }
+                }
+            }
+        }
+        return 0;
+    }
+
+    //未开启查看应用使用情况的权限
+    public static final long NOT_OPEN_USAGE_STATS = -1L;
+    /**
+     * 获取应用从2018-01-01 0:0:0到现在,在前台运行的时长
+     * @param packageName
+     * @return
+     */
+    public long getTotalTimeInForeground(String packageName) {
+        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
+            UsageStatsManager mUsageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
+            long time = System.currentTimeMillis();
+            if(mUsageStatsManager != null) {
+                List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 1_514_736_000_000L, time);//1_514_736_000_000L 对应 2018-01-01 0:0:0
+
+                if (usageStatsList != null && !usageStatsList.isEmpty()) {
+                    for (UsageStats usageStats : usageStatsList) {
+                        if (usageStats != null && TextUtils.equals(packageName, usageStats.getPackageName())) {
+                            return usageStats.getTotalTimeInForeground();
+                        }
                     }
+                } else {
+                    return NOT_OPEN_USAGE_STATS;
                 }
             }
         }

+ 57 - 10
app/src/main/java/com/sheep/gamegroup/util/CommonUtil.java

@@ -36,6 +36,8 @@ import com.sheep.gamegroup.absBase.BaseActivity;
 import com.sheep.gamegroup.alipay.PayResult;
 import com.sheep.gamegroup.event.BigEvent;
 import com.sheep.gamegroup.event.EventTypes;
+import com.sheep.gamegroup.greendao.DDProviderHelper;
+import com.sheep.gamegroup.greendao.download.AcceptTaskRecord;
 import com.sheep.gamegroup.greendao.download.DownLoadInfo;
 import com.sheep.gamegroup.model.entity.BaseMessage;
 import com.sheep.gamegroup.model.entity.DialogConfig;
@@ -50,6 +52,7 @@ import com.sheep.gamegroup.model.entity.PlayGameEntity;
 import com.sheep.gamegroup.model.entity.RobTask;
 import com.sheep.gamegroup.model.entity.RouserArticlesEntity;
 import com.sheep.gamegroup.model.entity.SlideshowEty;
+import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
 import com.sheep.gamegroup.model.entity.TaskChild;
 import com.sheep.gamegroup.model.entity.TaskDescEntity;
 import com.sheep.gamegroup.model.entity.TaskEty;
@@ -57,7 +60,6 @@ import com.sheep.gamegroup.model.entity.TaskReleaseEty;
 import com.sheep.gamegroup.model.entity.UserEntity;
 import com.sheep.gamegroup.model.entity.WithdrawalEty;
 import com.sheep.gamegroup.model.entity.XiaomiGameEntity;
-import com.sheep.gamegroup.model.util.AutoTaskListUtil;
 import com.sheep.gamegroup.model.util.EntityUtils;
 import com.sheep.gamegroup.model.util.SheepSubscriber;
 import com.sheep.gamegroup.usage.AppUsageManager;
@@ -67,6 +69,7 @@ import com.sheep.gamegroup.view.dialog.DialogShare;
 import com.sheep.jiuyan.samllsheep.BuildConfig;
 import com.sheep.jiuyan.samllsheep.R;
 import com.sheep.jiuyan.samllsheep.SheepApp;
+import com.sheep.jiuyan.samllsheep.service.AutoCheckService;
 import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
 import com.sheep.jiuyan.samllsheep.utils.FileUtil;
 import com.sheep.jiuyan.samllsheep.utils.G;
@@ -567,19 +570,63 @@ public class CommonUtil {
         activity.finish();
     }
 
+    private boolean isLoadingAcceptedTaskList = false;
     /**
      * 添加应用自动审核任务
      */
-    public void setTAskEnty(TaskEty tAskEnty) {
-        if (tAskEnty != null) {
-            if (AutoTaskListUtil.getInstance().addTask(tAskEnty)) {
-                AutoTaskListUtil.getInstance().resetReceiveTaskTime();//重置比对时间  5.1及以上使用
+    public void updateAutoCheck(TaskEty task) {
+        if (AutoCheckService.IS_USE_THIS_SERVICE) {//5.0及以下设备,不管取消还是接受任务都重新更新正在运行的自动审核任务列表
+            reloadAutoTaskList();
+        } else {//5.1及以上设备,直接记录任务开始时间
+            if (task != null && task.isAppAutoCommitTask() && !TextUtils.isEmpty(task.getPackage_names())) {//接受自动审核任务才记录
+                AcceptTaskRecord lastAcceptTaskRecord = DDProviderHelper.getInstance().getAcceptTaskRecord(SheepApp.getInstance(), task.getPackage_names());
+                long runTime = AppUsageManager.getInstance().getTotalTimeInForeground(task.getPackage_names());
+                if(lastAcceptTaskRecord == null){
+                    AcceptTaskRecord acceptTaskRecord = new AcceptTaskRecord();
+                    acceptTaskRecord.setPackageName(task.getPackage_names());
+                    acceptTaskRecord.setUserId(DataUtil.getInstance().getUserId());
+                    acceptTaskRecord.setAcceptTime(System.currentTimeMillis());
+                    acceptTaskRecord.setRunTime(runTime);
+                    DDProviderHelper.getInstance().addAcceptTaskRecord(SheepApp.getInstance(), acceptTaskRecord);//重置记录 5.1及以上使用
+                } else {
+                    lastAcceptTaskRecord.setRunTime(runTime);
+                    DDProviderHelper.getInstance().updateAcceptTaskRecord(SheepApp.getInstance(), lastAcceptTaskRecord);
+                }
             }
-            AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermisson(true);//尝试打开权限对话框 5.1及以上使用
-            AutoTaskListUtil.getInstance().initTaskList();
-        } else {//每次取消任务都重置记录
-            AutoTaskListUtil.getInstance().initTaskList();
-            MyDbManager.getInstance().removeAppRecord();//删除记录表 5.0及以下使用
+        }
+    }
+    //5.0及以下设备,不管取消还是接受任务都重新更新正在运行的自动审核任务列表
+    public void reloadAutoTaskList() {
+        if (AutoCheckService.IS_USE_THIS_SERVICE){
+            if (isLoadingAcceptedTaskList) {
+                return;
+            }
+            isLoadingAcceptedTaskList = true;
+            SheepApp.getInstance().getNetComponent().getApiService()
+                    .returnTask(TaskAcceptedEty.IS_SUCCESSION_ALL, TaskAcceptedEty.SHOW_GAME_TASK_NO)
+                    .subscribeOn(Schedulers.io())
+                    .observeOn(AndroidSchedulers.mainThread())
+                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
+                        @Override
+                        public void onError(BaseMessage baseMessage) {
+                            isLoadingAcceptedTaskList = false;
+                        }
+
+                        @Override
+                        public void onNext(BaseMessage baseMessage) {
+                            List<TaskAcceptedEty> list = baseMessage.getDatas(TaskAcceptedEty.class);
+                            ArrayList<String> packageNameList = ListUtil.emptyList();
+                            for (TaskAcceptedEty item : list) {
+                                TaskReleaseEty taskReleaseEty;
+                                TaskEty taskEty;
+                                if ((taskReleaseEty = item.getRelease_task()) != null && (taskEty = taskReleaseEty.getTask()) != null
+                                        && taskEty.isAppAutoCommitTask() && !TextUtils.isEmpty(taskEty.getPackage_names()))
+                                    packageNameList.add(taskEty.getPackage_names());
+                            }
+                            Jump2View.getInstance().startAutoCheckService(SheepApp.getInstance(), packageNameList);
+                            isLoadingAcceptedTaskList = false;
+                        }
+                    });
         }
     }
 

+ 3 - 0
app/src/main/java/com/sheep/gamegroup/util/DataUtil.java

@@ -48,6 +48,9 @@ public class DataUtil {
     private DataUtil() {
         userEntity = getCacheResult(ApiKey.get_info, UserEntity.class);//先从缓存中初始化用户信息
         token = SpUtils.getToken(SheepApp.getInstance());
+        if(!TextUtils.isEmpty(token)){//如果有token,启动后台进程并初始化正在运行的自动审核任务列表
+            CommonUtil.getInstance().reloadAutoTaskList();
+        }
         uid = TextUtils.isEmpty(token) ? "" : token.split("@")[0];
         if (userEntity != null && !TextUtils.equals(userEntity.getId(), uid)) {//当前用户id与缓存的用户信息不符时,清除缓存
             clearData();

+ 18 - 0
app/src/main/java/com/sheep/gamegroup/util/Jump2View.java

@@ -107,6 +107,7 @@ import com.sheep.gamegroup.view.dialog.DialogShare;
 import com.sheep.jiuyan.samllsheep.BuildConfig;
 import com.sheep.jiuyan.samllsheep.R;
 import com.sheep.jiuyan.samllsheep.SheepApp;
+import com.sheep.jiuyan.samllsheep.service.AutoCheckService;
 import com.sheep.jiuyan.samllsheep.service.FloatService;
 import com.sheep.jiuyan.samllsheep.service.FloatShotScreenService;
 import com.sheep.jiuyan.samllsheep.utils.G;
@@ -1069,6 +1070,23 @@ public class Jump2View {
         intent.putExtra("isShow", isShow);
         context.startService(intent);
     }
+    /**
+     * 启动小绵羊悬浮窗
+     *
+     * @param context
+     */
+    public void startAutoCheckService(Context context, ArrayList<String> taskList) {
+        String userId = DataUtil.getInstance().getUserId();
+        if(TextUtils.isEmpty(userId)){
+            return;
+        }
+        if(AutoCheckService.IS_USE_THIS_SERVICE) {
+            Intent intent = new Intent(context, AutoCheckService.class);
+            intent.putStringArrayListExtra(AutoCheckService.EXTRA_KEY_TASK_LIST, taskList);
+            intent.putExtra(AutoCheckService.EXTRA_KEY_USER_ID, userId);
+            context.startService(intent);
+        }
+    }
 
     /**
      * 启动小绵羊悬浮窗

+ 2 - 2
app/src/main/java/com/sheep/gamegroup/util/TestUtil.java

@@ -284,13 +284,13 @@ public class TestUtil {
                                 });
                                 break;
                             case "尝试开启第三方应用使用情况":
-                                AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermisson(false);
+                                AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermission(false);
                                 break;
                             case "第三方应用使用情况":
                                 AppUsageManager.getInstance().println();
                                 break;
                             case "开启第三方应用使用情况":
-                                AppUsageManager.getInstance().openLookAppUsageStatsPermisson();
+                                AppUsageManager.getInstance().openLookAppUsageStatsPermission();
                                 break;
                             case "h5跳转":
                                 Jump2View.getInstance().goXianwanWeb(activity,null,null);

+ 47 - 19
app/src/main/java/com/sheep/gamegroup/view/activity/TaskDetailAct.java

@@ -19,14 +19,16 @@ import com.arialyy.aria.core.Aria;
 import com.arialyy.aria.core.download.DownloadTarget;
 import com.arialyy.aria.core.download.DownloadTask;
 import com.arialyy.aria.core.inf.IEntity;
-import com.sheep.gamegroup.event.BigEvent;
-import com.sheep.gamegroup.event.EventTypes;
-import com.sheep.gamegroup.greendao.download.DownLoadInfo;
-import com.sheep.gamegroup.util.DownloadUtil;
 import com.kfzs.duanduan.utils.ApkUtils;
 import com.sheep.gamegroup.absBase.AbsChooseImageActivity;
 import com.sheep.gamegroup.di.components.DaggerTaskDetailComponent;
 import com.sheep.gamegroup.di.modules.TaskDetailModule;
+import com.sheep.gamegroup.event.BigEvent;
+import com.sheep.gamegroup.event.EventTypes;
+import com.sheep.gamegroup.greendao.DDProviderHelper;
+import com.sheep.gamegroup.greendao.download.AcceptTaskRecord;
+import com.sheep.gamegroup.greendao.download.DownLoadInfo;
+import com.sheep.gamegroup.greendao.download.ProcessRecord;
 import com.sheep.gamegroup.helper.TaskHelper;
 import com.sheep.gamegroup.model.api.ICallBack;
 import com.sheep.gamegroup.model.api.IDownload;
@@ -39,7 +41,6 @@ import com.sheep.gamegroup.model.entity.TaskChild;
 import com.sheep.gamegroup.model.entity.TaskDescEntity;
 import com.sheep.gamegroup.model.entity.TaskEty;
 import com.sheep.gamegroup.model.entity.TaskReleaseEty;
-import com.sheep.gamegroup.model.util.AutoTaskListUtil;
 import com.sheep.gamegroup.model.util.EntityUtils;
 import com.sheep.gamegroup.model.util.SheepSubscriber;
 import com.sheep.gamegroup.presenter.TaskDetailContract;
@@ -48,11 +49,12 @@ import com.sheep.gamegroup.usage.AppUsageManager;
 import com.sheep.gamegroup.util.CommonUtil;
 import com.sheep.gamegroup.util.DataUtil;
 import com.sheep.gamegroup.util.DeviceUtil;
+import com.sheep.gamegroup.util.DownloadUtil;
 import com.sheep.gamegroup.util.GlideImageLoader;
 import com.sheep.gamegroup.util.Jump2View;
 import com.sheep.gamegroup.util.ListUtil;
 import com.sheep.gamegroup.util.LocationUtils;
-import com.sheep.gamegroup.util.MyDbManager;
+import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.MyListview;
 import com.sheep.gamegroup.util.PngUtil;
 import com.sheep.gamegroup.util.SelfCountDownTimer;
@@ -64,6 +66,7 @@ import com.sheep.gamegroup.view.adapter.TaskdetailSonListviewAdp;
 import com.sheep.jiuyan.samllsheep.BuildConfig;
 import com.sheep.jiuyan.samllsheep.R;
 import com.sheep.jiuyan.samllsheep.SheepApp;
+import com.sheep.jiuyan.samllsheep.service.AutoCheckService;
 import com.sheep.jiuyan.samllsheep.utils.G;
 import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
 import com.sheep.jiuyan.samllsheep.utils.SpUtils;
@@ -249,7 +252,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
         ViewUtil.setDefaultText(dateTv);
         ViewUtil.setDefaultText(num_tv);
         if(DataUtil.IS_LISTEN_SCREEN_SHOT){//监听小绵羊截图功能需要开启查看应用使用情况的权限
-            AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermisson(false);
+            AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermission(false);
         }
     }
 
@@ -309,7 +312,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
             taskdetail_explain_layout.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {
-                    AppUsageManager.getInstance().openLookAppUsageStatsPermisson();
+                    AppUsageManager.getInstance().openLookAppUsageStatsPermission();
                 }
             });
             taskdetail_explain_layout.setVisibility(View.VISIBLE);
@@ -775,7 +778,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
                                 hideProgress();
                                 gettaskAcceptedEty = null;
                                 taskReleaseEty = null;
-                                CommonUtil.getInstance().setTAskEnty(null);
+                                CommonUtil.getInstance().updateAutoCheck(null);
                                 presenter.taskDesc(releaseTaskId);
                             }
                         });
@@ -831,7 +834,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
             } else {
                 accepteReceiveAward();
             }
-        } else if (taskEty.getInspect_type() == INSPECT_TYPE_SHEEP) {//应用自动审核任务
+        } else if (taskEty.isAppAutoCommitTask()) {//应用自动审核任务
             try {
                 checkAndCommitTask();
             } catch (Exception e) {
@@ -958,13 +961,38 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
             String gps = LocationUtils.getInstance().getLongitudeLatitude();
             JSONObject object = new JSONObject();
             object.put("gps", gps);
+            if(AutoCheckService.IS_USE_THIS_SERVICE) {
+                ProcessRecord processRecord = DDProviderHelper.getInstance().getProcessRecord(SheepApp.getInstance(), taskEty.getPackage_names());
+                object.put("task_time", processRecord.getRunTime());
+                LogUtil.println(1, "checkAndCommitTask", processRecord.getRunTime());
+                if (processRecord.getId() != null) {
+                    processRecord.setRunTime(0);
+                    DDProviderHelper.getInstance().addOrUpdateProcessRecord(SheepApp.getInstance(), processRecord);//重置记录 5.0及以下使用
+                }
+            } else {
+                long runTime = AppUsageManager.getInstance().getTotalTimeInForeground(taskEty.getPackage_names());
+                if(runTime == AppUsageManager.NOT_OPEN_USAGE_STATS){//获取不到应用使用情况,提示用户开启权限
+                    AppUsageManager.getInstance().showAccessibilityDialog();
+                    return;
+                }
+                AcceptTaskRecord acceptTaskRecord = DDProviderHelper.getInstance().getAcceptTaskRecord(SheepApp.getInstance(), taskEty.getPackage_names());
+                if(acceptTaskRecord == null){
+                    object.put("task_time", 0);
+                    LogUtil.println(2, "checkAndCommitTask", 0);
+                    acceptTaskRecord = new AcceptTaskRecord();
+                    acceptTaskRecord.setPackageName(taskEty.getPackage_names());
+                    acceptTaskRecord.setUserId(DataUtil.getInstance().getUserId());
+                    acceptTaskRecord.setAcceptTime(System.currentTimeMillis());
+                    acceptTaskRecord.setRunTime(runTime);
+                    DDProviderHelper.getInstance().addAcceptTaskRecord(SheepApp.getInstance(), acceptTaskRecord);//重置记录 5.1及以上使用
+                } else {
+                    object.put("task_time", runTime < 0 || runTime < acceptTaskRecord.getRunTime() ? 0 : (runTime - acceptTaskRecord.getRunTime()) / 1000L);
+                    LogUtil.println(3, "checkAndCommitTask", runTime, acceptTaskRecord.getRunTime());
+                    acceptTaskRecord.setRunTime(runTime);
+                    DDProviderHelper.getInstance().updateAcceptTaskRecord(SheepApp.getInstance(), acceptTaskRecord);//重置记录 5.1及以上使用
+                }
+            }
 
-            final long runTime = Math.max(AppUsageManager.getInstance().getTotalTimeInForeground(taskEty.getPackage_names()), 0);
-            MyDbManager.getInstance().removeAppRecord();//删除记录表 5.0及以下使用
-            AutoTaskListUtil.getInstance().resetReceiveTaskTime();//重置比对时间  5.1及以上使用
-            AppUsageManager.getInstance().needOpenLookAppUsageStatsPermisson(true);//重新保存应用使用情况的数据
-
-            object.put("task_time", runTime / 1000);
             object.put("release_task_id", taskReleaseEty.getId());
             addCanCommitTaskChildId(object, taskEty);
             SheepApp.getInstance().getNetComponent().getApiService().commitAutoTask(object)
@@ -973,7 +1001,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
                     .subscribe(new SheepSubscriber<BaseMessage>(getApplicationContext()) {
                         @Override
                         public void onNext(BaseMessage baseMessage) {
-                            CommonUtil.getInstance().setTAskEnty(null);
+                            CommonUtil.getInstance().updateAutoCheck(null);
                             //这里领取了奖励,要刷新用户信息
                             CommonUtil.getInstance().updateUserInfo(null);
                             String amount = taskReleaseEty.getBonusText();
@@ -1191,7 +1219,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
                             @Override
                             public void call(Integer integer) {
                                 taskReleaseEty.setAccepted_task_id(0);
-                                CommonUtil.getInstance().setTAskEnty(null);
+                                CommonUtil.getInstance().updateAutoCheck(null);
                                 acceptedTask();
                             }
                         });
@@ -1261,7 +1289,7 @@ public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailC
                         hideProgress();
                         taskReleaseEty.setIs_running(true);
                         taskReleaseEty.getTask().setRelease_task_id(taskReleaseEty.getId());
-                        CommonUtil.getInstance().setTAskEnty(taskReleaseEty.getTask());
+                        CommonUtil.getInstance().updateAutoCheck(taskReleaseEty.getTask());
 
                         getAcceptedTaskDetail(releaseTaskId);
 

+ 11 - 44
app/src/main/java/com/sheep/gamegroup/view/fragment/FgtPersonalCenter.java

@@ -149,7 +149,6 @@ public class FgtPersonalCenter extends BaseFragment {
             }
         });
         initUserInfo();
-        initWidget();
         String newVersionUrl = ACache.get(SheepApp.getInstance()).getAsString("version_url");
         personal_center_version_new.setVisibility(TextUtils.isEmpty(newVersionUrl) ? View.GONE : View.VISIBLE);
         String appVersionName = ApkUtils.getCurrentPkgVersionName(SheepApp.getInstance());
@@ -159,12 +158,19 @@ public class FgtPersonalCenter extends BaseFragment {
     }
 
     private void initUserInfo() {
-        userEntity = DataUtil.getInstance().getUserEntity();
-        initWidget();
+        CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
+            @Override
+            public void call(UserEntity userEntity) {
+                if(userEntity != null){
+                    FgtPersonalCenter.this.userEntity = userEntity;
+                    ivRedpackage.setVisibility(userEntity.isKfzsPackageUser() ? View.GONE : View.VISIBLE);
+                    initWidget();
+                }
+            }
+        });
     }
 
     private void initWidget() {
-
         personalcenter_item_price_tv.setText(String.format(Locale.CHINA, "%s\u0020元", userEntity.getBalance()));
         ViewUtil.setText(nameTv, userEntity.getNickname());
         sheepNumTv.setText(String.format(Locale.CHINA, "绵羊号:%s", userEntity.getInvitation_code()));
@@ -180,12 +186,6 @@ public class FgtPersonalCenter extends BaseFragment {
         return rootView;
     }
 
-    @Override
-    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
-        super.onViewCreated(view, savedInstanceState);
-        getLastUserInfo(null);
-    }
-
     /**
      * 获取是否有未读消息并更新图标
      */
@@ -320,39 +320,6 @@ public class FgtPersonalCenter extends BaseFragment {
                 });
     }
 
-    public void getLastUserInfo(final Action1<UserEntity> action1) {
-        SheepApp.getInstance()
-                .getNetComponent()
-                .getApiService()
-                .getInfo()
-                .subscribeOn(Schedulers.io())
-                .observeOn(AndroidSchedulers.mainThread())
-                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
-                    @Override
-                    public void onError(BaseMessage baseMessage) {
-                        if (action1 != null)
-                            action1.call(null);
-
-                    }
-
-                    @Override
-                    public void onNext(BaseMessage baseMessage) {
-                        UserEntity userEntity = baseMessage.getData(UserEntity.class);
-                        if (userEntity != null) {
-                            DataUtil.getInstance().setUserEntity(userEntity);
-                            if (!userEntity.getParent_code().equals("") || (userEntity.getCreate_time_line() < 2) || (userEntity.getPackage_cate() == 1)) {
-                                ivRedpackage.setVisibility(View.GONE);
-                            } else {
-                                ivRedpackage.setVisibility(View.VISIBLE);
-                            }
-                        }
-                        //   initUserInfo();
-                        if (action1 != null)
-                            action1.call(userEntity);
-                    }
-                });
-    }
-
     @Override
     public void onDestroyView() {
         super.onDestroyView();
@@ -445,12 +412,12 @@ public class FgtPersonalCenter extends BaseFragment {
 
     @Override
     public void onResume() {
-        getLastUserInfo(null);
         super.onResume();
         try {
             initData();
         } catch (Exception e) {
             e.printStackTrace();
+            G.showToast(e.getMessage());
         }
     }
 }

+ 1 - 1
app/src/main/java/com/sheep/gamegroup/view/fragment/FgtSmallSheep.java

@@ -996,7 +996,7 @@ public class FgtSmallSheep extends BaseFragment implements SmallSheepContract.Vi
     @Override
     public void giveUpTaskSuccesView(Object object) {
         G.showToast("取消任务成功");
-        CommonUtil.getInstance().setTAskEnty(null);
+        CommonUtil.getInstance().updateAutoCheck(null);
         refreshTaskList();
         FgtTryMakeMoney item = (FgtTryMakeMoney) adpViewPagerDetail.getItem(0);//因为放弃了任务,所以刷新可以接收的任务列表
         item.refreshData();

+ 1 - 8
app/src/main/java/com/sheep/gamegroup/view/fragment/FgtTryMakeMoney.java

@@ -2,7 +2,6 @@ package com.sheep.gamegroup.view.fragment;
 
 import android.app.Activity;
 import android.os.Bundle;
-import android.os.Handler;
 import android.support.v7.widget.LinearLayoutManager;
 import android.support.v7.widget.RecyclerView;
 import android.text.TextUtils;
@@ -10,14 +9,10 @@ import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.LinearLayout;
-import android.widget.RelativeLayout;
 import android.widget.TextView;
 
-import com.jcodecraeer.xrecyclerview.XRecyclerView;
 import com.scwang.smartrefresh.layout.SmartRefreshLayout;
 import com.scwang.smartrefresh.layout.api.RefreshLayout;
-import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
-import com.scwang.smartrefresh.layout.header.ClassicsHeader;
 import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
 import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
 import com.sheep.gamegroup.event.BigEvent;
@@ -37,7 +32,6 @@ import com.sheep.gamegroup.util.DataUtil;
 import com.sheep.gamegroup.util.ListUtil;
 import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.RefreshUtil;
-import com.sheep.gamegroup.util.ViewUtil;
 import com.sheep.gamegroup.view.activity.GamemakeMoneyAct;
 import com.sheep.gamegroup.view.activity.TryMakeMoneyact;
 import com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp;
@@ -59,7 +53,6 @@ import javax.inject.Inject;
 import butterknife.BindView;
 import butterknife.ButterKnife;
 import butterknife.Unbinder;
-import rx.functions.Action1;
 
 
 /**
@@ -466,7 +459,7 @@ public class FgtTryMakeMoney extends BaseFragment implements TryMakeMoneyContrac
     @Override
     public void giveUpTaskSuccesView(Object object) {
         G.showToast("取消任务成功");
-        CommonUtil.getInstance().setTAskEnty(null);
+        CommonUtil.getInstance().updateAutoCheck(null);
         refreshData();
     }
 

+ 3 - 7
app/src/main/java/com/sheep/jiuyan/samllsheep/SheepApp.java

@@ -8,7 +8,6 @@ import android.support.multidex.MultiDex;
 import android.support.multidex.MultiDexApplication;
 import android.text.TextUtils;
 import android.util.DisplayMetrics;
-import android.util.Log;
 
 import com.arialyy.aria.core.Aria;
 import com.baidu.location.BDAbstractLocationListener;
@@ -30,14 +29,13 @@ import com.sheep.gamegroup.util.DataUtil;
 import com.sheep.gamegroup.util.Jump2View;
 import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.RefreshUtil;
-import com.sheep.gamegroup.util.ScreenShotListenManager;
 import com.sheep.gamegroup.util.SysAppUtil;
 import com.sheep.gamegroup.util.UMConfigUtils;
 import com.sheep.gamegroup.view.activity.ActMain;
 import com.sheep.gamegroup.view.activity.GameCertificationActivity;
 import com.sheep.gamegroup.view.activity.LoginAct;
+import com.sheep.jiuyan.samllsheep.service.AutoCheckService;
 import com.sheep.jiuyan.samllsheep.service.DownloadService;
-import com.sheep.jiuyan.samllsheep.service.FloatService;
 import com.sheep.jiuyan.samllsheep.service.FloatShotScreenService;
 import com.sheep.jiuyan.samllsheep.service.ListenerShotService;
 import com.sheep.jiuyan.samllsheep.utils.G;
@@ -351,7 +349,7 @@ public class SheepApp extends MultiDexApplication {
                     Beta.autoDownloadOnWifi = !BuildConfig.DEBUG;
                     Bugly.init(getApplicationContext(), Config.BUGLY_APPID, BuildConfig.DEBUG);
                 }
-                AppUsageManager.getInstance().needOpenLookAppUsageStatsPermisson(true);//尝试保存应用使用情况的数据
+                AppUsageManager.getInstance().needOpenLookAppUsageStatsPermission(true);//尝试保存应用使用情况的数据
                 LogUtil.println("SheepApp onActivityCreated", activity.getClass().getSimpleName(), mActivityCount);
                 UMConfigUtils.Event.SHEEP_CREATED.onEvent();
             }
@@ -370,7 +368,6 @@ public class SheepApp extends MultiDexApplication {
                     if (DataUtil.IS_LISTEN_SCREEN_SHOT) {
                         startService(new Intent(activity, ListenerShotService.class));
                     }
-                    Jump2View.getInstance().startFloat(activity, false);
                     Jump2View.getInstance().startShotScreenFloat(activity, false);
                 }
             }
@@ -393,7 +390,6 @@ public class SheepApp extends MultiDexApplication {
                     notStop = false;
                     LogUtil.println("SheepApp onActivityStopped", activity.getClass().getSimpleName(), mActivityCount);
                     UMConfigUtils.Event.SHEEP_STOPPED.onEvent();
-                    Jump2View.getInstance().startFloat(activity, true);
                     Jump2View.getInstance().startShotScreenFloat(activity, true);
                 }
             }
@@ -415,7 +411,7 @@ public class SheepApp extends MultiDexApplication {
 //                if (DataUtil.IS_LISTEN_SCREEN_SHOT) {
 //                    stopService(new Intent(activity, ListenerShotService.class));
 //                }
-                stopService(new Intent(SheepApp.this, FloatService.class));
+                stopService(new Intent(SheepApp.this, AutoCheckService.class));
                 if (DataUtil.IS_USE_SCREEN_SHOT)
                     stopService(new Intent(SheepApp.this, FloatShotScreenService.class));
                 SpUtils.saveOrder("order", 1);

+ 113 - 0
app/src/main/java/com/sheep/jiuyan/samllsheep/service/AutoCheckService.java

@@ -0,0 +1,113 @@
+package com.sheep.jiuyan.samllsheep.service;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.text.TextUtils;
+
+import com.sheep.gamegroup.greendao.DDProviderHelper;
+import com.sheep.gamegroup.greendao.download.ProcessRecord;
+import com.sheep.gamegroup.util.ListUtil;
+import com.sheep.gamegroup.util.LogUtil;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import rx.Observable;
+import rx.Subscription;
+import rx.android.schedulers.AndroidSchedulers;
+import rx.functions.Action1;
+import rx.schedulers.Schedulers;
+
+/**
+ * Created by realicing on 2018/5/8.
+ * realicing@sina.com
+ * 应用自动审核任务监听应用使用时长----5.0以下使用该方案;5.0以上在app内直接读取应用使用情况
+ */
+public class AutoCheckService extends Service {
+    private void stopTimer() {
+        if (subscription != null) {
+            subscription.unsubscribe();
+        }
+        subscription = null;
+    }
+
+    private Subscription subscription;
+
+    private void startTimer() {
+        if (subscription == null)
+            subscription = Observable.interval(1_000L, TimeUnit.MILLISECONDS)
+                    .subscribeOn(Schedulers.io())
+                    .observeOn(AndroidSchedulers.mainThread())
+                    .subscribe(new Action1<Long>() {
+                        @Override
+                        public void call(Long count) {
+                            LogUtil.println("AutoCheckService", "count", "=", count);
+                            if(TextUtils.isEmpty(userId)){//没有登录不统计
+                                return;
+                            }
+                            String packageName = ListenerShotService.getProcessPackageNameInForeground(getApplicationContext());
+                            if(TextUtils.equals(lastPackageName, packageName) && !TextUtils.isEmpty(packageName) && !ListUtil.isEmpty(taskList) && taskList.contains(packageName)) {
+                                final ProcessRecord processRecord = new ProcessRecord();
+                                processRecord.setPackageName(packageName);
+                                processRecord.setUserId(userId);
+                                DDProviderHelper.getInstance().addOrUpdateProcessRecord(getApplicationContext(), processRecord, new Action1<ProcessRecord>() {
+                                    @Override
+                                    public void call(ProcessRecord lastProcessRecord) {
+                                        if(lastProcessRecord == null){
+                                            processRecord.setRunTime(1);
+                                        } else {
+                                            processRecord.setRunTime(lastProcessRecord.getRunTime() + 1);
+                                        }
+                                    }
+                                });
+                            }
+                            lastPackageName = packageName;
+                        }
+                    }, new Action1<Throwable>() {
+                        @Override
+                        public void call(Throwable throwable) {
+                            LogUtil.println("AutoCheckService", "Throwable", "=", throwable.getMessage());
+                        }
+                    });
+    }
+    //上一次获取到的包名
+    private String lastPackageName;
+
+
+    //不与Activity进行绑定.
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        startTimer();
+    }
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        stopTimer();
+    }
+
+
+    //需要监听的
+    private List<String> taskList;
+    public static final String EXTRA_KEY_TASK_LIST = "task_list";
+    public static final String EXTRA_KEY_USER_ID = "user_id";
+    //是否采用该方案
+    public static final boolean IS_USE_THIS_SERVICE = true;//android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP;
+    //登录的用户id
+    private String userId;
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        if (intent != null) {
+            taskList = intent.getStringArrayListExtra(EXTRA_KEY_TASK_LIST);
+            userId = intent.getStringExtra(EXTRA_KEY_USER_ID);
+        }
+        return super.onStartCommand(intent, flags, startId);
+    }
+
+}

+ 19 - 16
app/src/main/java/com/sheep/jiuyan/samllsheep/service/DownloadService.java

@@ -22,6 +22,7 @@ import com.sheep.gamegroup.event.EventTypes;
 import com.sheep.gamegroup.model.entity.DialogConfig;
 import com.sheep.gamegroup.model.entity.TaskEty;
 import com.sheep.gamegroup.util.ActivityManager;
+import com.sheep.gamegroup.util.DataUtil;
 import com.sheep.gamegroup.util.DownloadUtil;
 import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.StringUtils;
@@ -58,29 +59,33 @@ public class DownloadService extends Service {
         Aria.download(this).register();
         mDownloadTaskService = new DownloadUtil(this);
     }
-
-    private Map<String, DownloadTask> downloadTaskMap = new HashMap<>();
+    public static final String ON_PRE = "onPre";
+    public static final String RUNNING = "running";
+    public static final String HAS_SHOW = "hasShow";
 
     @Download.onPre
     void onPre(final DownloadTask task) {
         LogUtil.println("DownloadService", "onPre", task.getKey(), task.getTaskName());
-        downloadTaskMap.put(task.getKey(), task);
 
-        Observable.just(1).delay(5000L, TimeUnit.MILLISECONDS)
+        Observable.just(1).delay(10_000L, TimeUnit.MILLISECONDS)
                 .subscribeOn(Schedulers.io())
                 .observeOn(AndroidSchedulers.mainThread())
                 .subscribe(new Action1<Integer>() {
                     @Override
                     public void call(Integer integer) {
-                        if (downloadTaskMap.containsKey(task.getKey())) {
-                            ViewUtil.showMsgDialog(ActivityManager.getInstance().currentActivity(), new DialogConfig().setTitle("提示")
-                                    .setMsg("下载无响应,是否使用其它下载方式(在列表中长按任务也可选择其它下载方式)").setBtnLeftText("取消").setBtnRightText("确定")
-                                    .setBtnRightOnClickListener(new View.OnClickListener() {
-                                        @Override
-                                        public void onClick(View view) {
-                                            showDownloadType(task.getKey(), task.getTaskName());
-                                        }
-                                    }));
+                        String taskStatus = DataUtil.getAsString(String.format(Locale.CHINA, "hasShow[%s]", task.getKey()), ON_PRE);
+                        switch (taskStatus) {
+                            case ON_PRE:
+                                DataUtil.putAsString(String.format(Locale.CHINA, "hasShow[%s]", task.getKey()), HAS_SHOW);
+                                ViewUtil.showMsgDialog(ActivityManager.getInstance().currentActivity(), new DialogConfig().setTitle("提示")
+                                        .setMsg("任务【"+task.getTaskName()+"】下载无响应,是否使用其它下载方式(在列表中长按任务也可选择其它下载方式)").setBtnLeftText("取消").setBtnRightText("确定")
+                                        .setBtnRightOnClickListener(new View.OnClickListener() {
+                                            @Override
+                                            public void onClick(View view) {
+                                                showDownloadType(task.getKey(), task.getTaskName());
+                                            }
+                                        }));
+                                break;
                         }
                     }
                 });
@@ -100,9 +105,7 @@ public class DownloadService extends Service {
     @Download.onTaskRunning
     protected void running(DownloadTask task) {
         LogUtil.println("DownloadService", "running", task.getKey(), task.getTaskName(), task.getPercent());
-        if (downloadTaskMap.containsKey(task.getKey())) {
-            downloadTaskMap.remove(task.getKey());
-        }
+        DataUtil.putAsString(String.format(Locale.CHINA, "hasShow[%s]", task.getKey()), RUNNING);
         mDownloadTaskService.setDownloadTaskPercent(task.getPercent(), task.getCurrentProgress() / 1024d / 1024d, task.getFileSize() / 1024d / 1024d, 0, task.getKey());
         EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.GENERATION_ACCOUNT_REFRESH_ADAPTER).setData(task));
     }

+ 0 - 340
app/src/main/java/com/sheep/jiuyan/samllsheep/service/FloatService.java

@@ -1,340 +0,0 @@
-package com.sheep.jiuyan.samllsheep.service;
-
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.PixelFormat;
-import android.os.Build;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.Message;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.Gravity;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.WindowManager;
-import android.widget.TextView;
-
-import com.sheep.gamegroup.model.entity.AppUsage;
-import com.sheep.gamegroup.model.util.AutoTaskListUtil;
-import com.sheep.gamegroup.usage.AppUsageManager;
-import com.sheep.gamegroup.util.DataUtil;
-import com.sheep.gamegroup.util.LogUtil;
-import com.sheep.gamegroup.util.TestUtil;
-import com.sheep.gamegroup.util.TimeUtil;
-import com.sheep.jiuyan.samllsheep.R;
-import com.sheep.jiuyan.samllsheep.SheepApp;
-import com.sheep.jiuyan.samllsheep.utils.SpUtils;
-
-import java.util.Locale;
-import java.util.concurrent.TimeUnit;
-
-import rx.Observable;
-import rx.Subscription;
-import rx.android.schedulers.AndroidSchedulers;
-import rx.functions.Action1;
-import rx.schedulers.Schedulers;
-
-/**
- * Created by realicing on 2018/5/8.
- * realicing@sina.com
- */
-public class FloatService extends Service {
-    private void stopTimer() {
-        if (subscription != null) {
-            subscription.unsubscribe();
-        }
-        subscription = null;
-    }
-
-    private Subscription subscription;
-
-    private void startTimer() {
-        if (subscription == null)
-            subscription = Observable.interval(1_000L, TimeUnit.MILLISECONDS)
-                    .subscribeOn(Schedulers.io())
-                    .observeOn(AndroidSchedulers.mainThread())
-                    .subscribe(new Action1<Long>() {
-                        @Override
-                        public void call(Long count) {
-                            LogUtil.println("FloatService", "count", "=", count);
-                            if(DataUtil.IS_LISTEN_SCREEN_SHOT){//监听小绵羊截图功能需要开启查看应用使用情况的权限
-                                if(count % 60 == 30){
-                                    AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermisson(false);
-                                }
-                            }
-                            if (!TextUtils.isEmpty(SpUtils.getToken(SheepApp.getInstance())) &&!AutoTaskListUtil.getInstance().isEmpty()) {//登录情况下并且有应用自动审核任务才会记录
-                                if(count % 60 == 0){
-                                    AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermisson(false);
-                                }
-                                try {
-                                    AppUsageManager.getInstance().recordCurrentAppUsage();
-                                } catch (Exception e) {
-                                    e.printStackTrace();
-                                }
-                                if(isShowFloat) {
-                                    Message message = handler.obtainMessage(1);
-                                    message.obj = count;
-                                    handler.sendMessage(message);
-                                    LogUtil.println("FloatService", 1);
-                                }
-                            } else {
-                                if(isShowFloat) {
-                                    removeMessages();
-                                    mHandler.sendEmptyMessage(OPERATION_HIDE);
-                                    LogUtil.println("FloatService", 2);
-                                }
-                            }
-
-                        }
-                    }, new Action1<Throwable>() {
-                        @Override
-                        public void call(Throwable throwable) {
-                            LogUtil.println("FloatService", "Throwable", "=", throwable.getMessage());
-                        }
-                    });
-    }
-
-
-    //不与Activity进行绑定.
-    @Override
-    public IBinder onBind(Intent intent) {
-        return null;
-    }
-
-    @Override
-    public void onCreate() {
-        super.onCreate();
-        if(isShowFloat)
-            createFloatView();
-        startTimer();
-    }
-    private Handler handler = new Handler(Looper.getMainLooper()){
-        @Override
-        public void handleMessage(Message msg) {
-            if(isShowFloat) {
-                try {
-                    switch (msg.what) {
-                        case 1:
-                            onHandleMessage1();
-                            break;
-                    }
-                } catch (Exception e) {
-                    e.printStackTrace();
-                    LogUtil.println("FloatService", 4);
-                }
-            }
-        }
-
-        private void onHandleMessage1() {
-            LogUtil.println("FloatService", 3);
-            AppUsage appUsage = new AppUsage();
-            //更新悬浮窗
-            long totalTimeInForeground = AppUsageManager.getInstance().getTotalTimeInForeground(appUsage);
-            if(!AutoTaskListUtil.getInstance().hasTask(appUsage.getPackageName())){
-                FloatService.this.removeMessages();
-                mHandler.sendEmptyMessage(OPERATION_HIDE);
-                LogUtil.println("FloatService", 5);
-                return;
-            }
-            LogUtil.println("FloatService", 6);
-            if(!isAdded){
-                windowManager.addView(floatView, params);
-                isAdded = true;
-                LogUtil.println("FloatService", 7);
-            }
-            btn_floatView.setText(String.format(Locale.CHINA,"约运行%s",TimeUtil.getHours(totalTimeInForeground)));
-            windowManager.updateViewLayout(floatView, params);
-            LogUtil.println("FloatService", 8);
-        }
-
-    };
-    @Override
-    public void onDestroy() {
-        super.onDestroy();
-        removeMessages();
-        if (floatView != null) {
-            try {
-                if(isAdded)
-                    windowManager.removeViewImmediate(floatView);
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        }
-        stopTimer();
-    }
-
-//    public static final String OPERATION = "operation";
-    public static final int OPERATION_SHOW = 100;
-    public static final int OPERATION_HIDE = 101;
-
-    private static final int HANDLE_CHECK_ACTIVITY = 200;
-
-    private boolean isAdded = false; // 是否已增加悬浮窗
-    private WindowManager windowManager;
-    private WindowManager.LayoutParams params;
-    private View floatView;
-    private TextView btn_floatView;
-
-
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        if(isShowFloat) {
-            if (intent != null) {
-                if (intent.getBooleanExtra("isShow", true)) {
-                    mHandler.sendEmptyMessageDelayed(OPERATION_SHOW, 1000L);
-                } else {
-                    removeMessages();
-                    mHandler.sendEmptyMessage(OPERATION_HIDE);
-                }
-            }
-        }
-        return super.onStartCommand(intent, flags, startId);
-    }
-    private void removeMessages(){
-        if(isShowFloat) {
-            mHandler.removeMessages(OPERATION_HIDE);
-            mHandler.removeMessages(OPERATION_SHOW);
-        }
-    }
-
-    private Handler mHandler = new TwHandler(this);
-
-    static class TwHandler extends Handler {
-        TwHandler(FloatService service) {
-            this.service = service;
-        }
-
-        FloatService service;
-
-        @Override
-        public void handleMessage(Message msg) {
-            if(service.isShowFloat) {
-                switch (msg.what) {
-                    case OPERATION_SHOW:
-                        if (!service.isAdded) {
-                            try {
-//                            service.floatView.setAlpha(1.0f);
-//                            windowManager.updateViewLayout(service.floatView, params);
-                                service.windowManager.addView(service.floatView, service.params);
-                            } catch (Exception e) {
-                                e.printStackTrace();
-                            }
-                            service.isAdded = true;
-                        }
-                        break;
-                    case OPERATION_HIDE:
-                    case HANDLE_CHECK_ACTIVITY:
-                        if (service.isAdded) {
-                            try {
-//                            service.floatView.setAlpha(0.0f);
-//                            windowManager.updateViewLayout(service.floatView, params);
-                                service.windowManager.removeViewImmediate(service.floatView);
-                            } catch (Exception e) {
-                                e.printStackTrace();
-                            }
-                            service.isAdded = false;
-                        }
-                        break;
-                }
-            }
-        }
-    }
-    private boolean canTouchWindow = false;//是否可以操作悬浮窗
-    private boolean isShowFloat = TestUtil.isTest();//是否显示悬浮窗
-
-    public void setCanTouchWindow(boolean canTouchWindow) {
-        this.canTouchWindow = canTouchWindow;
-    }
-
-    /**
-     * 创建悬浮窗
-     */
-    private void createFloatView() {
-        LayoutInflater inflater = LayoutInflater.from(getApplication());
-//        //获取浮动窗口视图所在布局.
-        floatView = inflater.inflate(R.layout.float_window, null);
-        btn_floatView = floatView.findViewById(R.id.float_tv);
-
-        windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
-        params = new WindowManager.LayoutParams();
-
-        // 设置window type
-//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){//6.0
-//            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
-//        }else {
-//            params.type =  WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
-//        }
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
-            //  大于等于 24 即为 7.0 及以上执行内容
-            Log.e("qx", "7.0");
-            params.type = WindowManager.LayoutParams.TYPE_PHONE; // 7.1
-        } else {
-            //  低于 24 即为 7.0 以下执行内容
-            params.type = WindowManager.LayoutParams.TYPE_TOAST;   // 4.4
-            Log.e("qx", "4.4");
-
-        }
-        /*
-         * 如果设置为params.type = WindowManager.LayoutParams.TYPE_PHONE; 那么优先级会降低一些,
-         * 即拉下通知栏不可见
-         */
-
-        params.format = PixelFormat.RGBA_8888; // 设置图片格式,效果为背景透明
-
-        if(canTouchWindow) {
-            // 设置Window flag
-            params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
-                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
-            // 设置悬浮窗的Touch监听
-            floatView.setOnTouchListener(new View.OnTouchListener() {
-                int lastX, lastY;
-                int paramX, paramY;
-                private boolean isMove = false;
-                private long downTime = 0;
-
-                public boolean onTouch(View v, MotionEvent event) {
-                    switch (event.getAction()) {
-                        case MotionEvent.ACTION_DOWN:
-                            isMove = false;
-                            downTime = System.currentTimeMillis();
-                            lastX = (int) event.getRawX();
-                            lastY = (int) event.getRawY();
-                            paramX = params.x;
-                            paramY = params.y;
-                            break;
-                        case MotionEvent.ACTION_MOVE:
-                            int dx = (int) event.getRawX() - lastX;
-                            int dy = (int) event.getRawY() - lastY;
-                            params.x = paramX + dx;
-                            params.y = paramY + dy;
-                            // 更新悬浮窗位置
-                            windowManager.updateViewLayout(floatView, params);
-                            isMove = true;
-                            break;
-                        case MotionEvent.ACTION_UP:
-                            if(!isMove && System.currentTimeMillis()-downTime < 1000L){//没有移动过并且小于1秒就弹起来就点击
-                                v.performClick();
-                            }
-                            isMove = false;
-                            break;
-                    }
-                    return false;
-                }
-            });
-        } else {
-            /*
-             * 下面的flags属性的效果形同“锁定”。 悬浮窗不可触摸,不接受任何事件,同时不影响后面的事件响应。
-             */
-            params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
-        }
-
-        // 设置悬浮窗的长得宽
-        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
-        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
-        params.gravity = Gravity.START | Gravity.BOTTOM;
-    }
-}

+ 5 - 4
app/src/main/java/com/sheep/jiuyan/samllsheep/service/ListenerShotService.java

@@ -38,6 +38,7 @@ import rx.schedulers.Schedulers;
 /**
  * Created by realicing on 2018/9/20.
  * realicing@sina.com
+ * 监听截图
  */
 public class ListenerShotService extends Service {
 
@@ -61,7 +62,7 @@ public class ListenerShotService extends Service {
         //发送一个通知栏,保证存活
         Notification notification = new Notification();
         //通知栏没有展开时的显示内容
-        notification.icon = R.mipmap.icon;
+        notification.icon = R.mipmap.remenyx;
         notification.tickerText = "回到小绵羊";
 
         //下拉通知栏的显示内容
@@ -102,7 +103,7 @@ public class ListenerShotService extends Service {
     public String getPackageNameInForeground1(Context context) {
         String topPackageName = runningTaskUtil.getTopRunningTasks();
         if (TextUtils.isEmpty(topPackageName)) {
-            return getAppProcessInfoInForeground(context);
+            return getProcessPackageNameInForeground(context);
         }
         return topPackageName;
     }
@@ -132,10 +133,10 @@ public class ListenerShotService extends Service {
                 }
             }
         }
-        return getAppProcessInfoInForeground(context);
+        return getProcessPackageNameInForeground(context);
     }
 
-    private static String getAppProcessInfoInForeground(Context context) {
+    public static String getProcessPackageNameInForeground(Context context) {
         android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
         List<android.app.ActivityManager.RunningAppProcessInfo> processList = manager == null ? null : manager.getRunningAppProcesses();
         if (!ListUtil.isEmpty(processList)) {