全志代码首次提交

This commit is contained in:
2025-11-06 10:55:48 +08:00
commit fc767791f3
299 changed files with 26337 additions and 0 deletions

View File

@@ -0,0 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.system"
package="com.ik.mboxlauncher">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="droidlogic.permission.SYSTEM_CONTROL" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REMOVED"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission
android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="permission.REQUEST_DELETE_PACKAGES" />
<uses-permission
android:name="android.permission.DELETE_PACKAGES"/>
<uses-feature android:name="android.hardware.type.mouse" android:required="false"/>
<application
android:name="com.ik.mboxlauncher.ui.MyApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="false"
android:usesCleartextTraffic="true"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<activity
android:label="@string/app_name"
android:name="com.ik.mboxlauncher.ui.Launcher"
android:launchMode="singleTask"
android:supportsRtl="true"
android:clearTaskOnLaunch="true"
android:exported="true">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
<!-- <category android:name="android.intent.category.LAUNCHER"/>-->
</intent-filter>
</activity>
<!-- <activity-->
<!-- android:name="com.ik.mboxlauncher.ui.MyActivity"-->
<!-- android:configChanges="screenSize|orientation|keyboardHidden"-->
<!-- android:screenOrientation="user">-->
<!-- </activity>-->
<activity
android:name="com.ik.mboxlauncher.ui.SplashscreenActivity"
android:configChanges="screenSize|orientation|keyboardHidden"
android:screenOrientation="user">
</activity>
<activity
android:name=".ui.CategoryActivity"
android:configChanges="screenSize|orientation|keyboardHidden"
android:screenOrientation="user"/>
<!-- <activity-alias android:name="allapps"-->
<!-- android:targetActivity="com.ik.mboxlauncher.ui.Launcher"-->
<!-- android:supportsRtl="false"-->
<!-- android:icon="@drawable/ic_launcher"-->
<!-- android:label="@string/app_name"-->
<!-- android:exported="true">-->
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.ALLAPPS" />-->
<!-- <category android:name="android.intent.category.DEFAULT" />-->
<!-- </intent-filter>-->
<!-- </activity-alias>-->
<!-- <activity android:name="com.ik.mboxlauncher.ui.CustomAppsActivity"-->
<!-- android:theme="@android:style/Theme.Translucent">-->
<!-- </activity>-->
<service android:name=".SystemService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.ik.ad.SystemService"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
<receiver android:name="com.ik.mboxlauncher.ui.StartupBroadcast"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.PACKAGE_REMOVED"/>-->
<!-- <action android:name="android.intent.action.PACKAGE_ADDED"/>-->
<!-- <action android:name="android.intent.action.MEDIA_EJECT"/>-->
<!-- <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>-->
<!-- <action android:name="android.intent.action.MEDIA_MOUNTED"/>-->
<!-- <data android:scheme="package" />-->
<!-- </intent-filter>-->
</receiver>
<provider
android:authorities="com.ik.mboxlauncher.aw.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/sharefile" />
</provider>
</application>
</manifest>

View File

@@ -0,0 +1,5 @@
package com.ik.download;
public interface DownLoadAppListener {
void onDowanlaodResult(int msg,String path);
}

View File

@@ -0,0 +1,127 @@
package com.ik.download;
import android.content.Context;
import com.android.util.FileUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadAppTask extends Thread{
private String downurl;
private Context mContext;
/**存储路径*/
private String FILEPATH_STORAGE;
/**临时文件名称*/
private static String FILENAME_TMP="launcher.bak";
/**正是文件名称*/
private static String FILENAME_APK="launcher.apk";
private DownLoadAppListener mDownLoadAppListener;
private long startIndex = 0;
private long totalSize = 0;
public DownloadAppTask(Context context,String url,long fileSize,DownLoadAppListener downLoadAppListener){
mContext = context;
this.downurl = url;
this.totalSize = fileSize;
this.mDownLoadAppListener = downLoadAppListener;
this.FILEPATH_STORAGE = FileUtil.getBakPath(mContext,1) ;
}
@Override
public void run() {
super.run();
try {
File tempfile =new File(FILEPATH_STORAGE,FILENAME_TMP);
if(tempfile.exists()){
startIndex = tempfile.length();
}else {
tempfile.createNewFile();
}
HttpURLConnection urlConnection;
URL url = new URL(downurl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(2000*10); //设置连接超时事件为5秒
urlConnection.setRequestMethod("GET"); //设置请求方式为GET
//设置用户端可以接收的媒体类型
urlConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, " +
"image/pjpeg, application/x-shockwave-flash, application/xaml+xml, " +
"application/vnd.ms-xpsdocument, application/x-ms-xbap," +
" application/x-ms-application, application/vnd.ms-excel," +
" application/vnd.ms-powerpoint, application/msword, */*");
urlConnection.setRequestProperty("Accept-Language", "zh-CN"); //设置用户语言
urlConnection.setRequestProperty("Charset", "UTF-8"); //设置客户端编码
//设置用户代理
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; " +
"Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727;" +
" .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
//设置下载位置
urlConnection.setRequestProperty("Range", "bytes=" + startIndex + "-" + totalSize);
InputStream in = urlConnection.getInputStream();
RandomAccessFile raf = new RandomAccessFile(tempfile.getPath(), "rwd");
raf.seek(startIndex);
int len = 0;
byte buf[] =new byte[1024];
while((len = in.read(buf))!=-1){
raf.write(buf, 0, len);
}
in.close();
raf.close();
File apkFile = new File(FILEPATH_STORAGE,FILENAME_APK);
if(tempfile.length()==totalSize){
tempfile.renameTo(apkFile);
tempfile.delete();
// executeAppInstall(FILEPATH_STORAGE+"/"+FILENAME_APK);
if(mDownLoadAppListener!=null){
mDownLoadAppListener.onDowanlaodResult(0,apkFile.getPath());
}
}else {
if(mDownLoadAppListener!=null){
mDownLoadAppListener.onDowanlaodResult(-1,null);
}
}
} catch (Exception e) {
e.printStackTrace();
if(mDownLoadAppListener!=null){
mDownLoadAppListener.onDowanlaodResult(-1,null);
}
}
}
public boolean executeAppInstall(String apkPath){
boolean result = false;
try {
Runtime.getRuntime().exec("su");
String command = "pm install -r " + apkPath + "\n";
Process process = Runtime.getRuntime().exec(command);
BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String msg = "";
String line;
while ((line = errorStream.readLine()) != null) {
msg += line;
}
if (!msg.contains("Failure")) {
result = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,101 @@
package com.ik.download;
import android.content.Context;
import android.content.SharedPreferences;
import com.android.util.FileUtil;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadImgTask extends Thread{
private String downurl;
private Context mContext;
private String FILEPATH_STORAGE;
private String name;
private String[] baks = {"0.bak","1.bak","2.bak","3.bak","4.bak"};
public static String[] imgs = {"bcg","video","f_video","recomm","f_recomm"};
private long startIndex = 0;
private long totalSize = 0;
private static int Count = 0;
private int mIndex = 0;
private SharedPreferences mSharedPreferences;
public DownloadImgTask(Context context, String url, long fileSize,int index,SharedPreferences sharedPreferences,String name,ReconnNetIMG reconnNetIMG){
mContext = context;
this.downurl = url;
this.totalSize = fileSize;
this.FILEPATH_STORAGE = FileUtil.getBakPath(mContext,0) ;
this.mIndex = index;
this.mSharedPreferences = sharedPreferences;
this.name = name;
this.mReconnNetIMG = reconnNetIMG;
}
@Override
public void run() {
super.run();
try {
int len = 0;
File tempfile =new File(FILEPATH_STORAGE,baks[mIndex]);
if(tempfile.exists()){
startIndex = tempfile.length();
}else {
tempfile.createNewFile();
}
HttpURLConnection urlConnection;
URL url = new URL(downurl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(2000*10); //设置连接超时事件为5秒
urlConnection.setRequestMethod("GET"); //设置请求方式为GET
urlConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, " +
"image/pjpeg, application/x-shockwave-flash, application/xaml+xml, " +
"application/vnd.ms-xpsdocument, application/x-ms-xbap," +
" application/x-ms-application, application/vnd.ms-excel," +
" application/vnd.ms-powerpoint, application/msword, */*");
urlConnection.setRequestProperty("Accept-Language", "zh-CN"); //设置用户语言
urlConnection.setRequestProperty("Charset", "UTF-8"); //设置客户端编码
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; " +
"Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727;" +
" .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
urlConnection.setRequestProperty("Range", "bytes=" + startIndex + "-" + totalSize);
InputStream in = urlConnection.getInputStream();
RandomAccessFile raf = new RandomAccessFile(tempfile.getPath(), "rwd");
raf.seek(startIndex);
byte buf[] =new byte[1024];
while((len = in.read(buf))!=-1){
raf.write(buf, 0, len);
}
in.close();
raf.close();
// Log.i("==========","============"+totalSize);
if(tempfile.length()==totalSize){
String tmp = FileUtil.getBakPath(mContext,0)+"/"+mSharedPreferences.getString(DownloadImgTask.imgs[mIndex], "0.png");
File tmpFile1 = new File(tmp);
if(tmpFile1.exists()){
tmpFile1.delete();
}
File apkFile = new File(FILEPATH_STORAGE, name);
mSharedPreferences.edit().putString(imgs[mIndex],name).apply();
tempfile.renameTo(apkFile);
tempfile.delete();
Count++;
if(mReconnNetIMG!=null){
mReconnNetIMG.LoadIMG(Count);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public ReconnNetIMG mReconnNetIMG;
interface ReconnNetIMG{
void LoadIMG(int c);
}
}

View File

@@ -0,0 +1,372 @@
package com.ik.mboxlauncher;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.android.device.NetStateChangeReceiver;
import com.android.eventbaus.EventBusUtils;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.ADManager;
import com.android.device.NetStateChangeObserver;
import com.android.nebulasdk.bean.ADInfo;
import com.android.nebulasdk.presenter.AppnetPresenter;
import com.android.nebulasdk.presenter.callback.AppnetCallback;
import com.android.util.LogUtils;
import com.android.util.NetUtil;
import com.android.util.NetworkType;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/**
* 资源同步后台服务
* 功能:
* 1. 首次执行无条件请求接口(不检查时间)
* 2. 首次成功执行后必须等待8小时才能再次请求
* 3. 仅在请求成功时记录时间,失败不记录
* 4. 设备重启后重置为首次请求状态
*/
public class SystemService extends Service implements AppnetCallback, NetStateChangeObserver {
private static final int WHAT_REQUEST_ADMSG = 0;
private static final int WHAT_NETWORK_CHANGE = 3;
private static final int WHAT_PERIODIC_REQUEST = 4;
// 请求间隔8小时正式环境
// private static final long REQUEST_INTERVAL = 8 * 60 * 60 * 1000;
// 测试用短间隔
private static final long REQUEST_INTERVAL = 5 * 60 * 1000; // 5分钟
//持久化存储成功请求时间
private static final String KEY_LAST_SUCCESS_TIME = "last_success_time";
private boolean isFirstRequestDone = false; // 首次请求是否完成重启后重置为false
private boolean isRunning = false;
private boolean isRequesting = false;
private AppnetPresenter appnetPresenter;
private Handler handler;
private SharedPreferences sharedPreferences;
private PowerManager powerManager;
@Override
public void onCreate() {
super.onCreate();
if (!isRunning) {
isRunning = true;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
initHandler();
NetStateChangeReceiver.registerReceiver(this);
NetStateChangeReceiver.registerObserver(this);
// 检查是否是重启后首次启动服务
checkRebootStatus();
// 检查网络并执行首次请求
checkNetworkAndInitiateFirstRequest();
//handler.postDelayed(() -> ADManager.getInstance().restDownloadTask(), 3000);
}
}
/**
* 检查是否是重启后首次启动
*/
private void checkRebootStatus() {
if (powerManager != null) {
// 判断是否是开机后首次启动服务
boolean isReboot = powerManager.isInteractive();
if (isReboot) {
// LogUtils.loge("检测到设备重启,重置为首次请求状态");
isFirstRequestDone = false;
}
}
}
private void initHandler() {
handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case WHAT_REQUEST_ADMSG:
handleAdRequest();
break;
case WHAT_NETWORK_CHANGE:
notifyNetworkChange();
break;
case WHAT_PERIODIC_REQUEST:
handlePeriodicRequest();
break;
}
}
};
}
private void handlePeriodicRequest() {
// boolean should=shouldRequestImmediately();
// LogUtils.loge("shouldRequestImmediately()="+should+"isRequesting="+isRequesting);
if (isNetworkAvailable() && shouldRequestImmediately() && !isRequesting) {
LogUtils.loge("定时任务:满足条件,执行请求,task turn on");
handleAdRequest();
} else {
scheduleNextPeriodicRequest();
}
}
private void checkNetworkAndInitiateFirstRequest() {
if (isFirstRequestDone) {
if (shouldRequestImmediately() && !isRequesting) {
handler.sendEmptyMessage(WHAT_REQUEST_ADMSG);
} else {
LogUtils.loge("首次请求已完成,启动定时任务 first request");
scheduleNextPeriodicRequest();
}
return;
}
boolean currentNetworkAvailable = isNetworkAvailable();
if (currentNetworkAvailable && !isRequesting) {
LogUtils.loge("执行首次请求 first request handler msg");
handler.sendEmptyMessage(WHAT_REQUEST_ADMSG);
} else {
LogUtils.loge("网络不可用,安排首次请求检查 network dont work");
scheduleNextPeriodicRequest();
}
}
private void scheduleNextPeriodicRequest() {
handler.removeMessages(WHAT_PERIODIC_REQUEST);
if (!isFirstRequestDone) {
LogUtils.loge("首次请求未完成5分钟后再次检查 first uncompletely");
handler.sendEmptyMessageDelayed(WHAT_PERIODIC_REQUEST, 5*60 * 1000);
return;
}
long lastSuccessTime = getLastSuccessTime();
long currentTime = System.currentTimeMillis();
// 从未成功过,使用检查间隔
if (lastSuccessTime == 0) {
LogUtils.loge("从未成功请求过1个小时后再次尝试,no success,1hour later try");
handler.sendEmptyMessageDelayed(WHAT_PERIODIC_REQUEST, 60 * 60 * 1000);
return;
}
long nextRequestTime = lastSuccessTime + REQUEST_INTERVAL;
long delay = Math.max(0, nextRequestTime - currentTime);
LogUtils.loge("delay="+delay);
handler.sendEmptyMessageDelayed(WHAT_PERIODIC_REQUEST, delay);
// if (isNetworkAvailable()){
// LogUtils.loge("定时任务安排完成:" +
// "上次成功时间=" + formatTime(lastSuccessTime) +
// ",当前时间=" + formatTime(currentTime) +
// ",延迟=" + (delay / 1000 / 60) + "分钟" +
// ",下次执行=" + formatTime(currentTime + delay));
// }
}
private boolean shouldRequestImmediately() {
if (!isFirstRequestDone) {
return true;
}
long lastSuccessTime = getLastSuccessTime();
long currentTime = System.currentTimeMillis();
if (lastSuccessTime == 0) {
LogUtils.loge("从未成功请求过,应立即请求 unsuccess task turn on");
return true;
}
if (currentTime < lastSuccessTime) {
LogUtils.loge("满足(时间回退),应立即请求 time forecase task turn on");
return true;
}
long timeDiff = currentTime - lastSuccessTime;
if (timeDiff >= REQUEST_INTERVAL) {
LogUtils.loge("满足8小时间隔条件应立即请求 delay 8 hour task turn on");
return true;
}
LogUtils.loge("不满足8小时间隔条件不应请求 undelay 8 hour task turn off");
return false;
}
private void markFirstRequestDone() {
isFirstRequestDone = true;
// LogUtils.loge("标记首次请求已完成");
}
private void handleAdRequest() {
if (isRequesting) {
return;
}
if (appnetPresenter == null) {
try {
appnetPresenter = new AppnetPresenter(this);
} catch (Exception e) {
isRequesting = false;
if (!isFirstRequestDone) {
markFirstRequestDone();
}
// 失败时不保存时间
// saveLastSuccessTime();
LogUtils.loge("请求异常 request exception");
scheduleNextPeriodicRequest();
return;
}
}
isRequesting = true;
appnetPresenter.postLauncherAds(this);
}
private void notifyNetworkChange() {
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_MEDIA_STATUS));
}
private boolean isNetworkAvailable() {
int netState = NetUtil.getNetWorkState(this);
return netState == NetUtil.NETWORK_MOBILE
|| netState == NetUtil.NETWORK_WIFI
|| netState == NetUtil.NETWORK_ETHERNET;
}
private long getLastSuccessTime() {
return sharedPreferences.getLong(KEY_LAST_SUCCESS_TIME, 0);
}
private void saveLastSuccessTime() {
long currentTime = System.currentTimeMillis();
sharedPreferences.edit()
.putLong(KEY_LAST_SUCCESS_TIME, currentTime)
.apply();
LogUtils.loge("已保存本次成功请求时间refresh" + formatTime(currentTime));
}
@Override
public void onNetDisconnected() {
LogUtils.loge("网络断开 netdisconnect");
handler.sendEmptyMessage(WHAT_NETWORK_CHANGE);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onNetConnected(NetworkType networkType) {
LogUtils.loge("网络连接恢复netconnect" + networkType.name());
scheduleNextPeriodicRequest();
handler.sendEmptyMessage(WHAT_NETWORK_CHANGE);
}
@Override
public void onResult(Object data) {
isRequesting = false;
List<ADInfo> adInfoList = (data instanceof List<?>) ? (List<ADInfo>) data : new ArrayList<>();
ADManager.getInstance().updateADInfo(adInfoList);
if (!isFirstRequestDone) {
markFirstRequestDone();
}
// 成功时保存时间
saveLastSuccessTime();
scheduleNextPeriodicRequest();
}
@Override
public void onViewFailureString(int code, String message) {
isRequesting = false;
LogUtils.loge("接口请求失败(视图层):错误码= code" + code + ",错误信息= viewmsg" + message);
handleRequestFailure();
}
@Override
public void onExceptionFailure(String message) {
isRequesting = false;
LogUtils.loge("接口请求异常:异常信息= exceptionmsg" + message);
handleRequestFailure();
}
@Override
public void onServerFailure(int code, String message) {
isRequesting = false;
LogUtils.loge("接口请求失败(服务端):错误码= code" + code + ",错误信息= servermsg" + message);
// handleRequestFailure();
// 仅保留首次请求完成标记(必须保留,避免无限重复首次请求)
if (!isFirstRequestDone) {
markFirstRequestDone();
}
boolean isTimeout = code==0 || message.contains("The server is busy");
if (isTimeout) {
handler.removeMessages(WHAT_PERIODIC_REQUEST);
handler.sendEmptyMessageDelayed(WHAT_PERIODIC_REQUEST, REQUEST_INTERVAL);
} else {
//保留原逻辑
scheduleNextPeriodicRequest();
}
}
private void handleRequestFailure() {
if (!isFirstRequestDone) {
markFirstRequestDone();
}
// 失败时不保存时间
// saveLastSuccessTime();
scheduleNextPeriodicRequest();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
isRequesting = false;
NetStateChangeReceiver.unRegisterObserver(this);
NetStateChangeReceiver.unRegisterReceiver(this);
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
if (appnetPresenter != null) {
appnetPresenter = null;
}
}
private String formatTime(long timestamp) {
if (timestamp == 0) return "未记录 no record";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(new Date(timestamp));
}
}

View File

@@ -0,0 +1,25 @@
package com.ik.mboxlauncher;
public class VersionBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
private int version;
}

View File

@@ -0,0 +1,30 @@
package com.ik.mboxlauncher.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ik.mboxlauncher.ui.OnRefresnLauncherListener;
public class LauncherReceiverFromOther extends BroadcastReceiver {
public static final String LAUNCHER_UPDATE="com.ik.launcher.res.notify";
public static final String ADVERT_UPDATE="com.ik.Advert.res.notify";
static OnRefresnLauncherListener mOnRefresnLauncherListener;
public static void setOnRefresnLauncherListener(OnRefresnLauncherListener onRefresnLauncherListener){
mOnRefresnLauncherListener = onRefresnLauncherListener;
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(LAUNCHER_UPDATE)){
if(mOnRefresnLauncherListener!=null){
mOnRefresnLauncherListener.refreshLauncher();
}
}else {
if(mOnRefresnLauncherListener!=null){
mOnRefresnLauncherListener.refreshAdversh();
}
}
}
}

View File

@@ -0,0 +1,200 @@
package com.ik.mboxlauncher.ui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import androidx.media3.common.Player;
import com.android.database.lib.AdsInfoBean;
import com.android.monitor.DataBeeObserver;
import com.android.monitor.impl.EventFactory;
import com.android.nebulasdk.ADManager;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.view.AdMultiView;
import com.ik.mboxlauncher.view.MultiView;
import com.ik.mboxlauncher.view.HomeMultiView;
import com.seraphic.ad.AdStateListener;
import java.io.File;
import java.util.List;
public class ADSWindowManager implements HomeMultiView.MultiViewListener{
private List<MultiView> mMultiViewList;
private List<AdsInfoBean> mAdsInfoBeanList;
/**当前video广告播放索引*/
private int currentADIndex=0;
private Context mContext;
private static ADSWindowManager mInstance = null;
private Handler mHandler= new Handler();
/**广告延迟播放时间*/
// private static final long DELAYED_TIME=1000*60*5;
private static final long DELAYED_TIME=1000*60*1;
/**是否开启播放模式*/
private boolean isPlayMode=false;
private ADSWindowManager(Context context){
this.mContext =context;
}
public static void init(Context context){
if(mInstance==null){
mInstance = new ADSWindowManager(context);
}
}
public static ADSWindowManager getInstance(){
return mInstance;
}
/**绑定数据源*/
public void bindSourceData(List<MultiView> multiViewList, List<AdsInfoBean> adsInfoBeanList){
this.mMultiViewList=multiViewList;
this.mAdsInfoBeanList = adsInfoBeanList;
if(mMultiViewList.size()>mAdsInfoBeanList.size()){
LogUtils.loge("数据源绑定不一致mAdsInfoBeanList size is "+mMultiViewList.size()+" adsInfoBeanList size is "+adsInfoBeanList.size());
}
for (MultiView multiView:mMultiViewList){
multiView.setMultiViewListener(this);
}
}
public void startVideo(){
isPlayMode =true;
LogUtils.loge("currentADIndex|mMultiViewList.size()==="+currentADIndex+"|"+mMultiViewList.size());
if(currentADIndex<mAdsInfoBeanList.size()) {
LogUtils.loge("wait ad play time " + 0 + " , Play index|ad id is " + currentADIndex + "|" + mAdsInfoBeanList.get(currentADIndex).getId());
}
mHandler.post(runnable);
}
private void delayedStartVideo(){
LogUtils.loge("currentADIndex|mMultiViewList.size()==="+currentADIndex+"|"+mMultiViewList.size());
if(currentADIndex<mAdsInfoBeanList.size()) {
LogUtils.loge("wait ad play time " + DELAYED_TIME + " , Play index|ad id is " + currentADIndex + "|" + mAdsInfoBeanList.get(currentADIndex).getId());
}
mHandler.removeCallbacks(runnable);
mHandler.postDelayed(runnable,DELAYED_TIME);
}
public void stopVideo(){
isPlayMode =false;
mHandler.removeCallbacks(runnable);
if(mMultiViewList!=null&&currentADIndex<mMultiViewList.size()) {
mMultiViewList.get(currentADIndex).stopView();
}
LogUtils.loge("停止播放,"+" , index is "+currentADIndex);
}
public void resetVideo(){
mHandler.removeCallbacks(runnable);
if(mMultiViewList!=null&&currentADIndex<mMultiViewList.size()) {
if(mMultiViewList.get(currentADIndex) instanceof HomeMultiView) {
mMultiViewList.get(currentADIndex).resetView();
} else if (mMultiViewList.get(currentADIndex) instanceof AdMultiView
&& mMultiViewList.get(currentADIndex).isAdPlaying()) {
return;
}
}
LogUtils.loge("按键事件触发停止播放wait ad play "+DELAYED_TIME+" , index is "+currentADIndex);
mHandler.postDelayed(runnable,DELAYED_TIME);
}
@SuppressLint("UnsafeOptInUsageError")
private void setVideoViewData(MultiView multiView, AdsInfoBean data){
AdsInfoBean adInfo = ADManager.getInstance().getADInfoById(data.getId(),ADManager.ADTYPE_VIDEO); //再查询一次,保持取最新的数据
if(adInfo!=null){
try {
if (adInfo.getState() == 1) {
if(multiView instanceof AdMultiView){
LogUtils.loge(" ad playing id:" + adInfo.getId());
multiView.onVideoRestart(adInfo.getLocalFilePath());
return;
}
File file = new File(adInfo.getLocalFilePath());
if (file.isFile() && file.exists()) {
LogUtils.loge(" ad playing id:" + adInfo.getId());
multiView.onVideoRestart(adInfo.getLocalFilePath());
return;
}
}
}catch (Exception e){
e.printStackTrace();
LogUtils.loge("error file is not exists:"+adInfo.getLocalFilePath());
}
currentADIndex++;
if (currentADIndex >= mMultiViewList.size()) { //所有文件都不存在,跳出循环,都不播放
currentADIndex=0;
}
startVideo();
}
}
@Override
public void onPlaybackStateChanged(int viewId, int playbackState) {
// if(playbackState== Player.STATE_BUFFERING){
// if(currentADIndex<mAdsInfoBeanList.size()) {
// DataBeeObserver.getInstance().recordEventMsg(
// EventFactory.EVENT_GOOGLE_AD,
// mAdsInfoBeanList.get(currentADIndex).getId(),
// System.currentTimeMillis(),
// System.currentTimeMillis(),
// "AdShow"
// );
// }
// }
if(playbackState== Player.STATE_ENDED||playbackState==Player.STATE_IDLE|| playbackState==AdStateListener.AD_ERROR) {
// if(playbackState== Player.STATE_ENDED){
// if(currentADIndex<mAdsInfoBeanList.size()) {
// DataBeeObserver.getInstance().recordEventMsg(
// EventFactory.EVENT_GOOGLE_AD,
// mAdsInfoBeanList.get(currentADIndex).getId(),
// System.currentTimeMillis(),
// System.currentTimeMillis(),
// "AdCompleted"
// );
// }
// }
if(isPlayMode) {
currentADIndex++;
if (currentADIndex >= mMultiViewList.size()) {
currentADIndex = 0;
}
delayedStartVideo();
}else {
LogUtils.loge("PlayMode is pause");
}
}
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
if(mMultiViewList!=null&&currentADIndex<mMultiViewList.size()){
setVideoViewData(mMultiViewList.get(currentADIndex),mAdsInfoBeanList.get(currentADIndex));
}
}
};
}

View File

@@ -0,0 +1,165 @@
package com.ik.mboxlauncher.ui;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import com.android.device.MediaStateChangeObserver;
import com.android.eventbaus.MessageEvent;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.base.FragmentActivity;
import com.ik.mboxlauncher.ui.fragment.AppsFragment;
import com.ik.mboxlauncher.ui.fragment.LocalFragment;
import com.ik.mboxlauncher.ui.fragment.MusicFragment;
import com.ik.mboxlauncher.ui.fragment.RecommendFragment;
import com.ik.mboxlauncher.ui.fragment.VideoFragment;
public class CategoryActivity extends FragmentActivity {
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static Bitmap screenShot;
public static Bitmap screenShot_keep;
/**action*/
private String mAction=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
FragmentManager.init(this,this);
super.onCreate(savedInstanceState);
}
@Override
protected int getlayoutId() {
return R.layout.launcher_layout;
}
@Override
protected void initView() {
Bundle bundle = this.getIntent().getExtras();
if(bundle!=null){
mAction=bundle.getString("action");
}
if(RecommendFragment.ACTION.equals(mAction)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.RECOMMEND_APPS_TAG),false);
}else if(MusicFragment.ACTION.equals(mAction)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.MUSIC_APPS_TAG),false);
}else if(VideoFragment.ACTION.equals(mAction)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.VIDEO_APPS_TAG),false);
}else if(AppsFragment.ACTION.equals(mAction)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.APPS_TAG),false);
}else if(LocalFragment.ACTION.equals(mAction)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.LOCAL_APPS_TAG),false);
}
}
@Override
protected void initData() {
}
@Override
protected int getFramlayoutId() {
return R.id.launcher_container_layout;
}
@Override
protected Fragment onCreateInitialFragment() {
return null;
}
@Override
public void popBackStackFragment() {
}
@Override
public void onDoneEvents(MessageEvent messageEvent) {
if(MusicFragment.ACTION.equals(messageEvent.action)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.MUSIC_APPS_TAG),false);
}else if(RecommendFragment.ACTION.equals(messageEvent.action)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.RECOMMEND_APPS_TAG),false);
}else if(VideoFragment.ACTION.equals(messageEvent.action)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.VIDEO_APPS_TAG),false);
}else if(LocalFragment.ACTION.equals(messageEvent.action)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.LOCAL_APPS_TAG),false);
}else if(AppsFragment.ACTION.equals(messageEvent.action)){
showFragment(FragmentManager.getInstance().getFragmentByTag(FragmentManager.APPS_TAG),false);
}
}
// public void setPopWindow(int top, int bottom){
// View view = this.getWindow().getDecorView();
// view.layout(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
// view.setDrawingCacheEnabled(true);
// Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());
// view.destroyDrawingCache();
// screenShot = null;
// screenShot_keep = null;
// if (bottom > SCREEN_HEIGHT/2) {
// if (top+3-CustomAppsActivity.CONTENT_HEIGHT > 0) {
// screenShot = Bitmap.createBitmap(bmp, 0, 0,bmp.getWidth(), top);
// screenShot_keep = Bitmap.createBitmap(bmp, 0, CustomAppsActivity.CONTENT_HEIGHT,
// bmp.getWidth(), top +3-CustomAppsActivity.CONTENT_HEIGHT);
// } else {
// screenShot = Bitmap.createBitmap(bmp, 0, 0,bmp.getWidth(), CustomAppsActivity.CONTENT_HEIGHT);
// screenShot_keep = null;
// }
// } else {
// screenShot = Bitmap.createBitmap(bmp, 0, bottom,bmp.getWidth(), SCREEN_HEIGHT-bottom);
// screenShot_keep = Bitmap.createBitmap(bmp, 0, bottom,
// bmp.getWidth(), SCREEN_HEIGHT-(bottom+CustomAppsActivity.CONTENT_HEIGHT));
// }
// }
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
LogUtils.loge("onKeyDown===>"+keyCode);
if(keyCode==KeyEvent.KEYCODE_BACK){
if(currentFragment.onKeyDown(keyCode,event)){
return true;
}else {
return super.onKeyDown(keyCode,event);
}
}
return super.onKeyDown(keyCode,event);
}
MediaStateChangeObserver mediaStateChangeObserver = new MediaStateChangeObserver() {
@Override
public void onMediaRecever(String action) {
if(currentFragment!=null){
currentFragment.onResumeFragment(new MessageEvent(action));
}
}
};
@Override
public void finish() {
super.finish();
setResult(0);
}
}

View File

@@ -0,0 +1,87 @@
package com.ik.mboxlauncher.ui;
import android.content.Context;
import com.ik.mboxlauncher.ui.base.BaseFragment;
import com.ik.mboxlauncher.ui.base.NotifyInterface;
import com.ik.mboxlauncher.ui.fragment.AppsFragment;
import com.ik.mboxlauncher.ui.fragment.LocalFragment;
import com.ik.mboxlauncher.ui.fragment.MainFragment;
import com.ik.mboxlauncher.ui.fragment.MusicFragment;
import com.ik.mboxlauncher.ui.fragment.RecommendFragment;
import com.ik.mboxlauncher.ui.fragment.VideoFragment;
/**
* 存放所有Livetv Fragment
*/
public class FragmentManager {
private Context mContext;
private static FragmentManager mInstance = null;
/*主菜单*/
public static final int MAIN_TAG=0x00;
/*all apps*/
public static final int APPS_TAG=0x01;
/*music apps*/
public static final int MUSIC_APPS_TAG=0x02;
/*music apps*/
public static final int RECOMMEND_APPS_TAG=0x03;
public static final int VIDEO_APPS_TAG=0x04;
public static final int LOCAL_APPS_TAG=0x05;
private AppsFragment mAppsFragment;
private LocalFragment mLocalFragment;
private MainFragment mMainFragment;
private MusicFragment mMusicFragment;
private RecommendFragment mRecommendFragment;
private VideoFragment mVideoFragment;
private FragmentManager(Context context, NotifyInterface notifyInterface){
this.mContext = context;
mAppsFragment = new AppsFragment();
mAppsFragment.setNotifyInterface(notifyInterface);
mLocalFragment = new LocalFragment();
mLocalFragment.setNotifyInterface(notifyInterface);
mMainFragment = new MainFragment();
mMainFragment.setNotifyInterface(notifyInterface);
mMusicFragment = new MusicFragment();
mMusicFragment.setNotifyInterface(notifyInterface);
mRecommendFragment = new RecommendFragment();
mRecommendFragment.setNotifyInterface(notifyInterface);
mVideoFragment = new VideoFragment();
mVideoFragment.setNotifyInterface(notifyInterface);
}
public static void init(Context context, NotifyInterface notifyInterface){
if(mInstance==null){
mInstance = new FragmentManager(context,notifyInterface);
}
}
public static FragmentManager getInstance(){
return mInstance;
}
public BaseFragment getFragmentByTag(int tagStr){
switch (tagStr){
case MAIN_TAG:
return mMainFragment;
case APPS_TAG:
return mAppsFragment;
case MUSIC_APPS_TAG:
return mMusicFragment;
case RECOMMEND_APPS_TAG:
return mRecommendFragment;
case VIDEO_APPS_TAG:
return mVideoFragment;
case LOCAL_APPS_TAG:
return mLocalFragment;
}
return null;
}
public void destory(){
mInstance = null;
}
}

View File

@@ -0,0 +1,978 @@
package com.ik.mboxlauncher.ui;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.GridView;
import android.widget.Toast;
import androidx.media3.common.Player;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.android.MXQConfig;
import com.android.api.encrytion.UtilEncrypt;
import com.android.database.lib.AdsInfoBean;
import com.android.database.lib.AppBean;
import com.android.database.lib.ShortAppBean;
import com.android.device.MediaStateChangeObserver;
import com.android.device.MediaStateChangeReceiver;
import com.android.eventbaus.MessageEvent;
import com.android.monitor.DataBeeObserver;
import com.android.nebulasdk.ADManager;
import com.android.nebulasdk.AppManager;
import com.android.nebulasdk.bean.FavNaviBean;
import com.android.util.GsonUtil;
import com.android.util.IntentUtil;
import com.android.util.LogUtils;
import com.android.util.PakageInstallUtil;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.adapter.CustomAppAdapter;
import com.ik.mboxlauncher.ui.adapter.ShortAppInfoAdapter;
import com.ik.mboxlauncher.ui.adapter.StatusAdapter;
import com.ik.mboxlauncher.ui.base.FragmentActivity;
import com.ik.mboxlauncher.ui.base.StatusLoader;
import com.ik.mboxlauncher.ui.fragment.AppsFragment;
import com.ik.mboxlauncher.ui.fragment.MusicFragment;
import com.ik.mboxlauncher.ui.fragment.RecommendFragment;
import com.ik.mboxlauncher.ui.fragment.VideoFragment;
import com.ik.mboxlauncher.view.MultiView;
import com.ik.mboxlauncher.view.AdMultiView;
import com.ik.mboxlauncher.view.CustomRecyclerView;
import com.ik.mboxlauncher.view.SplashView;
import com.ik.mboxlauncher.view.TimeTextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 主界面
*/
public class Launcher extends FragmentActivity implements SplashView.SplashAdListener {
public static final String TAG="com.ik.mboxlauncher.ui.fragment.MainFragment";
private MultiView layout_video,layout_music,layout_primevideo,layout_filemanager,layout_hbomax,layout_setting,layout_youtube,layout_recommend,layout_netflix,layout_chrome;
private AdMultiView layout_miracastreceive;
private int[] imageResIds={R.drawable.img_video,R.drawable.img_miracastreceive,R.drawable.img_youtube,R.drawable.img_recommend,R.drawable.img_music,R.drawable.img_netflix,R.drawable.img_primevideo,R.drawable.img_filemanager,R.drawable.img_chrome,R.drawable.img_hbomax,R.drawable.img_setting};
private CustomRecyclerView gv_shortcut,grid_coustom_apps;
private StatusLoader mStatusLoader;
private ShortAppInfoAdapter mShortAppInfoAdapter=null;
private CustomAppAdapter mCustomAppAdapter=null;
private StatusAdapter ad =null;
private GridView lv_status;
private TimeTextView tx_time;
private View content_view,coustom_view;
private MultiView[] multiViewArray = new MultiView[imageResIds.length];
protected static final int MODEL_NORMAL = 0x00;
protected static final int MODEL_CUSTOM = 0x01;
protected int cuttentModel=MODEL_NORMAL;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static Bitmap screenShot;
public static Bitmap screenShot_keep;
private Handler handler = new Handler();
private int mHomeHeight;
private View shortcut_layout;
private ViewGroup ad_full_root;
/**闪屏界面是否结束*/
private boolean isSplashEnd=false;
private SplashView mSplashView;
@Override
protected void onCreate(Bundle savedInstanceState) {
LogUtils.loge("onCreate===>");
Log.e("liu", "Launcher run ad: "+System.currentTimeMillis() );
if(mSplashView==null){
mSplashView = new SplashView(Launcher.this);
mSplashView.setmSplashAdListener(this);
mSplashView.show();
}
// startActivity(new Intent(Launcher.this,SplashscreenActivity.class));
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getRealMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
LogUtils.loge("screenWidth|screenHeight=====>"+screenWidth+"|"+screenHeight+"|"+displayMetrics.densityDpi);
// LogManager.init(Launcher.this);
// AppManager.init(Launcher.this);
// ADManager.init(Launcher.this);
// LogUtils.loge("onCreate 11111==>");
// Intent startIntent = new Intent(this, SystemService.class);
//// bindService(startIntent,connection,Context.BIND_AUTO_CREATE);
// startService(startIntent);
MediaStateChangeReceiver.registerReceiver(this);
StartupBroadcast.registerReceiver(this);
// MediaStateChangeReceiver.registerObserver(mediaStateChangeObserver);
super.onCreate(savedInstanceState);
}
@Override
protected int getlayoutId() {
return R.layout.main;
}
@Override
protected void initView() {
LogUtils.loge("initView===>");
mStatusLoader = new StatusLoader(this);
layout_video = findViewById(R.id.layout_video);
layout_video.setOnClickListener(onClickListener);
multiViewArray[0]=layout_video;
ad_full_root = findViewById(R.id.ad_full_root);
layout_miracastreceive = findViewById(R.id.layout_miracastreceive);
layout_miracastreceive.setOnClickListener(onClickListener);
layout_miracastreceive.setFullRooView(ad_full_root);
multiViewArray[1]=layout_miracastreceive;
layout_youtube = findViewById(R.id.layout_youtube);
layout_youtube.setOnClickListener(onClickListener);
// layout_youtube.setFullRooView(ad_full_root);
multiViewArray[2]=layout_youtube;
layout_recommend = findViewById(R.id.layout_recommend);
layout_recommend.setOnClickListener(onClickListener);
// layout_recommend.setFullRooView(ad_full_root);
multiViewArray[3]=layout_recommend;
layout_music = findViewById(R.id.layout_music);
layout_music.setOnClickListener(onClickListener);
multiViewArray[4]=layout_music;
layout_netflix = findViewById(R.id.layout_netflix);
layout_netflix.setOnClickListener(onClickListener);
// layout_netflix.setFullRooView(ad_full_root);
multiViewArray[5]=layout_netflix;
layout_primevideo = findViewById(R.id.layout_primevideo);
layout_primevideo.setOnClickListener(onClickListener);
multiViewArray[6]=layout_primevideo;
layout_filemanager = findViewById(R.id.layout_filemanager);
layout_filemanager.setOnClickListener(onClickListener);
multiViewArray[7]=layout_filemanager;
layout_chrome = findViewById(R.id.layout_chrome);
layout_chrome.setOnClickListener(onClickListener);
// layout_chrome.setFullRooView(ad_full_root);
multiViewArray[8]=layout_chrome;
layout_hbomax = findViewById(R.id.layout_hbomax);
layout_hbomax.setOnClickListener(onClickListener);
multiViewArray[9]=layout_hbomax;
layout_setting = findViewById(R.id.layout_setting);
layout_setting.setOnClickListener(onClickListener);
multiViewArray[10]=layout_setting;
gv_shortcut = findViewById(R.id.gv_shortcut);
lv_status = findViewById(R.id.list_status);
tx_time = findViewById(R.id.tx_time);
grid_coustom_apps = findViewById(R.id.grid_coustom_apps);
content_view = findViewById(R.id.content_view);
coustom_view= findViewById(R.id.coustom_view);
shortcut_layout = findViewById(R.id.shortcut_layout);
if(mShortAppInfoAdapter==null){
mShortAppInfoAdapter = new ShortAppInfoAdapter(this);
mShortAppInfoAdapter.setmOnSelectItemListener(new ShortAppInfoAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(ShortAppBean shortAppInfoBean, int selectIndex) {
if(shortAppInfoBean.getItemType()==0){
LogUtils.loge("open app custom view");
if(selectIndex == 0){
gotoAction(AppsFragment.ACTION);
} else {
if (!isShowCustomApp()) {
showCustomApps();
}
}
}else {
LogUtils.loge("open app package name is "+shortAppInfoBean.getPackageName());
IntentUtil.startApp(Launcher.this,shortAppInfoBean.getPackageName(),getResources().getString(R.string.app_not_exist));
}
}
});
}
if(mCustomAppAdapter==null){
mCustomAppAdapter = new CustomAppAdapter(this,AppManager.CATEGORY_SHORT);
mCustomAppAdapter.setmOnSelectItemListener(new CustomAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(AppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("open app, package is "+shortAppInfoBean.getPackageName()+"|"+mCustomAppAdapter.getItemCount());
// if(mCustomAppAdapter.getItemCount()<9) {
if (shortAppInfoBean.getSelect() == 0) {
if(mCustomAppAdapter.countSelectApp()<AppManager.SHORT_COUNT) {
shortAppInfoBean.setSelect(1);
selectAppByCategory(shortAppInfoBean, AppManager.CATEGORY_SHORT);
mCustomAppAdapter.notifyItemChanged(sleectIndex);
}else {
Toast.makeText(Launcher.this, getResources().getString(R.string.str_nospace),Toast.LENGTH_SHORT).show();
}
} else {
shortAppInfoBean.setSelect(0);
selectAppByCategory(shortAppInfoBean, AppManager.CATEGORY_SHORT);
mCustomAppAdapter.notifyItemChanged(sleectIndex);
}
// }else {
// LogUtils.loge("shortcuts no space! ");
// Toast.makeText(Launcher.this, getResources().getString(R.string.str_nospace),Toast.LENGTH_SHORT).show();
//
// }
}
}
});
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
gv_shortcut.setLayoutManager(layoutManager);
gv_shortcut.setAdapter(mShortAppInfoAdapter);
gv_shortcut.setCanFocusOutHorizontal(false);
gv_shortcut.setCanFocusOutVertical(true);
StaggeredGridLayoutManager customLayoutManager = new StaggeredGridLayoutManager(9, StaggeredGridLayoutManager.VERTICAL);
grid_coustom_apps.setLayoutManager(customLayoutManager);
grid_coustom_apps.setAdapter(mCustomAppAdapter);
grid_coustom_apps.addOnScrollListener(new RecyclerView.OnScrollListener() {
int childViewPosition=0;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
View childView = recyclerView.getFocusedChild();
childViewPosition= recyclerView.getChildAdapterPosition(childView);
LogUtils.loge("childView|childViewPosition==>"+childViewPosition);
if(childViewPosition==-1){//当焦点错乱是,强制修正找到目标位置(例如第一个可见项)
int[] rows=new int[8];
((StaggeredGridLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPositions(rows);
View targetView = recyclerView.findViewHolderForAdapterPosition(rows[0]).itemView;
targetView.post(() -> targetView.requestFocus());
}
}
}
});
ADSWindowManager.init(this);
bindAdsWindowMultiView();
}
@Override
protected void onResume() {
super.onResume();
// 当网络发生变化判断当前网络状态并通过NetEvent回调当前网络状态
// if (netWorkState == NetUtil.NETWORK_MOBILE || netWorkState == NetUtil.NETWORK_WIFI || netWorkState == NetUtil.NETWORK_ETHERNET) {
LogUtils.loge("onResume");
displayStatus();
handler.post(runnable);
// handler.removeCallbacks(runnable);
// handler.postDelayed(runnable,1000*60*5);
// setImageViewData();
// LogUtils.loge("有可用网络");
// } else {
// LogUtils.loge("没有可用网络");
// }
mHomeHeight = findViewById(R.id.layout_homepage).getHeight();
}
@Override
protected void initData() {
tx_time.starTimeUi();
displayStatus();
loadShortAppList();
}
@Override
protected int getFramlayoutId() {
return R.layout.main;
}
@Override
protected Fragment onCreateInitialFragment() {
return null;
}
@SuppressLint("UnsafeOptInUsageError")
private void setImageViewData(){
for (int i=0;i<multiViewArray.length;i++){
MultiView multiView = multiViewArray[i];
FavNaviBean favNaviBean= AppManager.getInstance().getFavNaviBean(i);
if(favNaviBean.getRelatedApp()!=null) {
multiView.onImageRestartLocal(favNaviBean.getImgPath());
multiView.setTag(favNaviBean);
// if (PakageInstallUtil.checkAppInstall(Launcher.this, favNaviBean.getRelatedApp())) {
// LogUtils.loge("onImageRestartLocal:"+favNaviBean.getImgPath());
// File file =new File(favNaviBean.getImgPath());
// if(file.exists()){
// multiView.onImageRestartLocal(favNaviBean.getImgPath());
// multiView.setTag(favNaviBean);
// }
// }else {
// LogUtils.loge(favNaviBean.getRelatedApp()+" is not exits");
// if(favNaviBean.getImgPath()!=null){ //本地有配置的图片显示配置图片
// multiView.onImageRestartLocal(favNaviBean.getImgPath());
// }else { //本地没有存储显示默认图片
// multiView.loadDefaultImage(imageResIds[i]);
// multiView.setTag(null);
// }
//
// }
}else {
multiView.setTag(null);
if(favNaviBean.getImgPath()!=null){ //本地有存储显示存储图片
multiView.onImageRestartLocal(favNaviBean.getImgPath());
}else { //本地没有存储显示默认图片
multiView.loadDefaultImage(imageResIds[i]);
}
}
}
// List<AdsInfoBean> adInfoList = ADManager.getInstance().getADInfoListByadType(ADManager.ADTYPE_IMAGE);
// LogUtils.loge("adInfoList===>"+adInfoList.size());
// int i=0;
// for (AdsInfoBean adInfo:adInfoList ) {
//
//
//
//
//
//
//
//// if (adInfo != null) {
//// LogUtils.loge(i+" adInfo.getAppUrl()==>"+adInfo.getAppUrl());
//// LogUtils.loge(i+" adInfo.getInfo()==>"+adInfo.getInfo());
//// LogUtils.loge(i+" adInfo.getAdUri()==>"+adInfo.getAdUri());
////
//// if (adInfo.getAppUrl() != null && adInfo.getInfo() != null) {
//// if (PakageInstallUtil.checkAppInstall(Launcher.this, adInfo.getInfo(), adInfo.getAppVersion())) { //已安装了以后才可以显示图片
//// multiView.onImageRestartLocal(adInfo.getLocalFilePath());
//// LogUtils.loge(adInfo.getInfo()+" is installed");
//// }else {
//// LogUtils.loge(adInfo.getInfo()+" is not installed");
//// }
//// }else {
//// String iconPath=null;
//// //TODO 设置默认图标
//// if(i==0){
//// iconPath=AppManager.getInstance().getIconAssertData(AppManager.ICON_00_TAG);
////
//// }else if(i==1){
//// iconPath=AppManager.getInstance().getIconAssertData(AppManager.ICON_01_TAG);
//// }else if(i==2){
//// iconPath=AppManager.getInstance().getIconAssertData(AppManager.ICON_02_TAG);
//// }else if(i==3){
//// iconPath=AppManager.getInstance().getIconAssertData(AppManager.ICON_03_TAG);
//// }else if(i==4){
//// iconPath=AppManager.getInstance().getIconAssertData(AppManager.ICON_04_TAG);
//// }
//// if(iconPath!=null&&!"".equals(iconPath)){
//// multiView.onImageRestartLocal(iconPath);
//// }else {
//// LogUtils.loge("区域:"+i+"--未设置默认图片");
//// }
//// }
////
//// }
//
//// i++;
// }
}
// private void loadShortAppList(){
//
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// List<ShortAppBean> shortcutInfoBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
// mShortAppInfoAdapter.addDatas(shortcutInfoBeanList);
// }
// });
//
// }
private void loadShortAppList(){
runOnUiThread(() -> {
List<ShortAppBean> shortcutInfoBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
LogUtils.loge("显示的recycleView"+ GsonUtil.GsonString(shortcutInfoBeanList));
// 创建过滤后的列表
List<ShortAppBean> filteredList = new ArrayList<>();
String selfPackageName = getPackageName();
for (ShortAppBean appBean : shortcutInfoBeanList) {
// 跳过自身应用
if (appBean.getPackageName().equals(selfPackageName) || appBean.getPackageName().equals("com.android.traceur")) {
LogUtils.loge("排除自己和com.android.traceur:" + appBean.getPackageName());
continue; // 不添加到过滤列表
}
// 添加非自身应用
filteredList.add(appBean);
}
mShortAppInfoAdapter.addDatas(filteredList);
});
}
// private void loadCustomAppList(){
//
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// List<AppBean> shortcutInfoBeanList = AppManager.getInstance().getmyAppByCategory();
// LogUtils.loge("myapp "+shortcutInfoBeanList.size());
// sortAppList(shortcutInfoBeanList);
// if(shortcutInfoBeanList!=null) {
// mCustomAppAdapter.addDatas((List<AppBean>)shortcutInfoBeanList);
// grid_coustom_apps.setAdapter(mCustomAppAdapter);
// }else {
// LogUtils.loge("no data");
// }
// }
// });
//
// }
private void loadCustomAppList(){
runOnUiThread(new Runnable() {
@Override
public void run() {
List<AppBean> shortcutInfoBeanList = AppManager.getInstance().getmyAppByCategory();
LogUtils.loge("myapp "+shortcutInfoBeanList.size());
List<AppBean> filteredList = new ArrayList<>();
String selfPackageName = getPackageName();
for (AppBean appBean : shortcutInfoBeanList) {
// 跳过自身应用
if (appBean.getPackageName().equals(selfPackageName) || appBean.getPackageName().equals("com.android.traceur")) {
LogUtils.loge("排除自己和com.android.traceur:" + appBean.getPackageName());
continue; // 不添加到过滤列表
}
// 添加非自身应用
filteredList.add(appBean);
}
sortAppList(filteredList);
mCustomAppAdapter.addDatas(filteredList);
grid_coustom_apps.setAdapter(mCustomAppAdapter);
}
});
}
private void sortAppList( List<AppBean> shortcutInfoBeanList){
List<ShortAppBean> shortAppBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
Map<String,ShortAppBean> tmpMapData = new HashMap<>();
for (ShortAppBean shortAppBean:shortAppBeanList){
tmpMapData.put(shortAppBean.getPackageName(),shortAppBean);
}
for (int i=0;i<shortcutInfoBeanList.size();i++){
AppBean appBean = shortcutInfoBeanList.get(i);
if(tmpMapData.get(appBean.getPackageName())!=null){
appBean.setSelect(1);
}else {
appBean.setSelect(0);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// ADSWindowManager.getInstance().resetVideo();
LogUtils.loge("onTouchEvent:=======");
return super.onTouchEvent(event);
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
// 检查事件是否来自鼠标
if ((event.getSource() & InputDevice.SOURCE_MOUSE) != 0) {
Log.d("Mouse", "Mouse action "+event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_MOVE:
// 鼠标移动事件
float x = event.getX();
float y = event.getY();
Log.d("Mouse", "Mouse moved to: (" + x + ", " + y + ")");
ADSWindowManager.getInstance().resetVideo();
return true;
default:
break;
}
}
return super.onGenericMotionEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
LogUtils.loge("===================onKeyDown:"+keyCode);
ADSWindowManager.getInstance().resetVideo();
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
LogUtils.loge("====="+isShowCustomApp()+"|"+grid_coustom_apps.hasFocus()+"|"+grid_coustom_apps.findFocus());
if(isShowCustomApp()){
dismissCustomApp();
}
// else {
//// return layout_miracastreceive.onAdBackClick();
// }
return true;
// case KeyEvent.KEYCODE_DPAD_UP:
//// LogUtils.loge("====="+isShowCustomApp()+"|"+grid_coustom_apps.hasFocus()+"|"+grid_coustom_apps.findFocus());
// LogUtils.loge("====="+grid_coustom_apps.hasFocus());
// LogUtils.loge("====="+coustom_view.hasFocus());
// LogUtils.loge("====="+gv_shortcut.hasFocus());
//
// if(isShowCustomApp()&&!grid_coustom_apps.hasFocus()){
// dismissCustomApp();
// }else {
// return false;
// }
// return true;
//
// case KeyEvent.KEYCODE_DPAD_DOWN:
//
// LogUtils.loge("====="+grid_coustom_apps.hasFocus());
// LogUtils.loge("====="+coustom_view.hasFocus());
// LogUtils.loge("====="+gv_shortcut.hasFocus());
// if(!grid_coustom_apps.hasFocus()&&!coustom_view.hasFocus()&&gv_shortcut.hasFocus()){
// coustom_view.requestFocus();
// grid_coustom_apps.requestFocus();
// return false;
// }
//
// return super.onKeyDown(keyCode,event);
}
return super.onKeyDown(keyCode,event);
}
// @Override
// public void onResumeFragment(MessageEvent event) {
// LogUtils.loge("onResumeFragment: refresh ui");
// if(MessageEvent.ACTION_UPADATE_DATA_SOURCE.equals(event.action)) {
// bindAdsWindowMultiView();
// ADSWindowManager.getInstance().startVideo();
// setImageViewData();
// }else if(MessageEvent.ACTION_UPADATE_MEDIA_STATUS.equals(event.action)){
// displayStatus();
// }
// }
@Override
public void onMessageEvent(MessageEvent event) {
LogUtils.loge("onMessageEvent===>"+event.action);
if(MessageEvent.ACTION_UPADATE_DATA_SOURCE.equals(event.action)) {
ADManager.getInstance().updateDownloadTaskBeanTable();
handler.removeCallbacks(runnable);
handler.postDelayed(runnable,1000*5);
}else if(MessageEvent.ACTION_UPADATE_MEDIA_STATUS.equals(event.action)){
displayStatus();
}else if(MessageEvent.ACTION_UPADATE_APPS_SOURCE.equals(event.action)){
if(currentFragment!=null&&currentFragment instanceof AppsFragment){
currentFragment.onResumeFragment(event);
}
}
}
private void displayStatus() {
runOnUiThread(new Runnable() {
@Override
public void run() {
List<ArrayMap<String, Object>> datas = mStatusLoader.getStatusData();
if(ad==null){
ad = new StatusAdapter(Launcher.this, datas, R.layout.homelist_item,
new String[] {StatusLoader.ICON},
new int[] {R.id.item_type, 0, 0});
lv_status.setAdapter(ad);
}else {
ad.addDatas(datas);
}
}
});
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// ADSWindowManager.getInstance().stopVideo();
MultiView multiView = (MultiView) v;
if(!multiView.onAdViewClick()){
FavNaviBean favNaviBean = (FavNaviBean) v.getTag();
LogUtils.loge(GsonUtil.GsonString(favNaviBean));
if(favNaviBean!=null){
LogUtils.loge("go to app:"+favNaviBean.getRelatedApp());
gotoActivity(favNaviBean.getRelatedApp());
}else {
if (v.getId() == R.id.layout_video) {
LogUtils.loge("go to video");
gotoAction(VideoFragment.ACTION);
} else if (v.getId() == R.id.layout_youtube) {
LogUtils.loge("go to youtube");
gotoActivity("com.google.android.youtube.tv");
} else if (v.getId() == R.id.layout_recommend) {
LogUtils.loge("go to recommend");
gotoAction(RecommendFragment.ACTION);
} else if (v.getId() == R.id.layout_music) {
LogUtils.loge("go to music");
gotoAction(MusicFragment.ACTION);
} else if (v.getId() == R.id.layout_netflix) {
LogUtils.loge("go to netflix");
gotoActivity("com.netflix.mediaclient");
} else if (v.getId() == R.id.layout_primevideo) {
LogUtils.loge("go to primevideo");
// gotoAction(LocalFragment.ACTION);
gotoActivity("com.amazon.amazonvideo.livingroom");
} else if (v.getId() == R.id.layout_filemanager) {
LogUtils.loge("go to filemanager");
if(MXQConfig.RK_PLATFORM.equalsIgnoreCase(MXQConfig.getManufacturer())){
gotoFileManager();
}else {
gotoActivity("com.softwinner.TvdFileManager");
}
//gotoFileManager();
} else if (v.getId() == R.id.layout_chrome) {
LogUtils.loge("go to chrome");
gotoActivity("com.android.chrome");
} else if (v.getId() == R.id.layout_hbomax) {
LogUtils.loge("go to hbomax");
gotoActivity("com.wbd.stream");
} else if (v.getId() == R.id.layout_setting) {
LogUtils.loge("go to setting");
Intent intent = new Intent();
if(MXQConfig.RK_PLATFORM.equalsIgnoreCase(MXQConfig.getManufacturer())) {
intent.setComponent(new ComponentName("com.android.tv.settings", "com.android.tv.settings.MainSettings"));
}else {
if (PakageInstallUtil.checkAppInstall(Launcher.this, "com.android.settings")) {
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings"));
} else {
intent.setComponent(new ComponentName("com.android.tv.settings", "com.android.tv.settings.MainSettings"));
}
}
startActivity(intent);
}else if (v.getId() == R.id.layout_miracastreceive) {
if(!layout_miracastreceive.onAdViewClick()){
if(MXQConfig.RK_PLATFORM.equalsIgnoreCase(MXQConfig.getManufacturer())) {
gotoActivity("com.rockchip.wfd");
}else {
gotoActivity("com.softwinner.miracastReceiver");
}
}
}
}
}else {
LogUtils.loge("go to Ad show");
}
}
};
private void gotoAction(String action){
Intent intent = new Intent(Launcher.this,CategoryActivity.class);
Bundle bundle = new Bundle();
bundle.putString("action",action);
intent.putExtras(bundle);
startActivity(intent);
}
private void gotoActivity(String packageName){
if (PakageInstallUtil.checkAppInstall(Launcher.this, packageName)) { //已安装了以后才可以显示图片
IntentUtil.startApp(Launcher.this,packageName,getResources().getString(R.string.app_not_exist));
LogUtils.loge(packageName+" is installed");
}else {
Toast.makeText( Launcher.this, getResources().getString(R.string.app_not_exist), Toast.LENGTH_SHORT).show();
LogUtils.loge(packageName+" is not installed");
}
}
private void gotoFileManager(){
if (PakageInstallUtil.checkAppInstall(Launcher.this, "com.android.rockchip")) { //已安装了以后才可以显示图片
IntentUtil.startApp(Launcher.this,"com.android.rockchip",getResources().getString(R.string.app_not_exist));
LogUtils.loge("com.android.rockchip is installed");
}else if(PakageInstallUtil.checkAppInstall(Launcher.this, "com.rockchips.mediacenter")){
IntentUtil.startApp(Launcher.this,"com.rockchips.mediacenter",getResources().getString(R.string.app_not_exist));
}else if(PakageInstallUtil.checkAppInstall(Launcher.this, "com.estrongs.android.pop")){
IntentUtil.startApp(Launcher.this,"com.estrongs.android.pop",getResources().getString(R.string.app_not_exist));
}else {
Toast.makeText( Launcher.this, getResources().getString(R.string.app_not_exist), Toast.LENGTH_SHORT).show();
LogUtils.loge("com.android.rockchip is not installed");
}
}
private void showCustomApps(){
cuttentModel = MODEL_CUSTOM;
LogUtils.loge("coustom_view.getHeight():"+coustom_view.getLayoutParams().height);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, 0.0f,0.0f, (float)(0 - coustom_view.getLayoutParams().height-gv_shortcut.getHeight()));
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
content_view.clearFocus();
loadCustomAppList();
coustom_view.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation) {
gv_shortcut.clearFocus();
gv_shortcut.setFocusable(false);
coustom_view.setTranslationZ(5);
coustom_view.requestFocus();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
translateAnimation.setDuration(300);
translateAnimation.setFillAfter(true);
content_view.startAnimation(translateAnimation);
// TranslateAnimation exitTransAnim = new TranslateAnimation(0.0f, 0.0f,coustom_view.getY()+coustom_view.getLayoutParams().height, 0);
// exitTransAnim.setDuration(300);
// translateAnimation.setFillAfter(true);
// coustom_view.startAnimation(exitTransAnim);
// coustom_view.setTranslationZ(5);
// coustom_view.setVisibility(View.VISIBLE);
}
private void dismissCustomApp(){
cuttentModel = MODEL_NORMAL;
LogUtils.loge("coustom_view.getHeight():"+coustom_view.getLayoutParams().height);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, 0.0f,(float)(0 - coustom_view.getLayoutParams().height - gv_shortcut.getHeight()),0.0f);
translateAnimation.setDuration(300);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
coustom_view.setTranslationZ(0);
loadShortAppList();
coustom_view.clearFocus();
}
@Override
public void onAnimationEnd(Animation animation) {
coustom_view.setVisibility(View.GONE);
gv_shortcut.requestFocus();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
translateAnimation.setFillAfter(true);
content_view.startAnimation(translateAnimation);
// TranslateAnimation exitTransAnim = new TranslateAnimation(0.0f, 0.0f, 0,coustom_view.getY()+coustom_view.getLayoutParams().height);
// exitTransAnim.setDuration(300);
// translateAnimation.setFillAfter(true);
// coustom_view.startAnimation(exitTransAnim);
}
private boolean isShowCustomApp(){
return cuttentModel==MODEL_NORMAL?false:true;
}
protected void selectAppByCategory(AppBean appBean,int Category){
AppManager.getInstance().selectAppByCategory(appBean,Category);
}
Player.Listener mediaListener = new Player.Listener() {
@Override
public void onPlaybackStateChanged(int playbackState) {
LogUtils.loge("onPlaybackStateChanged:"+playbackState);
if(playbackState == Player.STATE_ENDED){
}
}
};
/***
* 创建有资源可播放的广告窗口
* @return
*/
private void bindAdsWindowMultiView(){
List<AdsInfoBean> adsInfoBeanList= ADManager.getInstance().getADInfoListByadType(ADManager.ADTYPE_VIDEO);
List<MultiView> multiViewArrayList = new ArrayList<>();
List<AdsInfoBean> adsDatas=new ArrayList<>();
for (int i=0;i<adsInfoBeanList.size();i++){
AdsInfoBean mAdsInfoBean = adsInfoBeanList.get(i);
if(mAdsInfoBean.getId()==100){ //过滤出开屏广告
continue;
}
adsDatas.add(mAdsInfoBean);
LogUtils.loge("AD-Index:"+i+"|"+mAdsInfoBean.getId());
multiViewArrayList.add(multiViewArray[mAdsInfoBean.getId()]);
}
ADSWindowManager.getInstance().bindSourceData(multiViewArrayList,adsDatas);
}
@Override
public void popBackStackFragment() {
}
@Override
public void onDoneEvents(MessageEvent MessageEvent) {
}
MediaStateChangeObserver mediaStateChangeObserver = new MediaStateChangeObserver() {
@Override
public void onMediaRecever(String action) {
}
};
@Override
protected void onPause() {
super.onPause();
LogUtils.loge("onPause==>");
handler.removeCallbacks(runnable);
ADSWindowManager.getInstance().stopVideo();
}
@Override
public void finish() {
super.finish();
MediaStateChangeReceiver.unRegisterReceiver(this);
StartupBroadcast.unRegisterReceiver(this);
}
Runnable runnable = new Runnable() {
@Override
public void run() {
LogUtils.loge("UI runnable.....");
LogUtils.loge("代码更新了");
bindAdsWindowMultiView();
if(isSplashEnd) {
ADSWindowManager.getInstance().startVideo();
}
ADManager.getInstance().clearTaskInteruptQueueAndRestart();
setImageViewData();
loadShortAppList();
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onEnd() {
isSplashEnd =true;
// ADSWindowManager.getInstance().startVideo();
}
}

View File

@@ -0,0 +1,64 @@
package com.ik.mboxlauncher.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.view.LoadingView;
import com.ik.mboxlauncher.view.HomeMultiView;
/** Main Activity. */
@SuppressLint("UnsafeOptInUsageError")
/* @SuppressLint is needed for new media3 APIs. */
public class MyActivity extends Activity {
private HomeMultiView ad_splash_view;
private Handler handler =new Handler();
private float startAngle=180f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
LoadingView loadingView =findViewById(R.id.loading_view);
findViewById(R.id.btn_test).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
ad_splash_view = findViewById(R.id.ad_splash_view);
// ad_splash_view.setMultiViewListener(new MultiView.MultiViewListener() {
// @Override
// public void onPlaybackStateChanged(int viewId, int playbackState) {
//
// if(playbackState== Player.STATE_ENDED||playbackState==Player.STATE_IDLE){
//
// }
// }});
//
// String filePath ="/storage/emulated/0/Android/data/com.droidlogic.mboxlauncher/cache/ADVERT/53624c4f-8e53-479e-9736-e030957745fb.mp4";
// File file = new File(filePath);
// if(file.exists()){
// ad_splash_view.onVideoRestart(file.getPath());
//
//
// }
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
//
// }
// },1000*10);
}
}

View File

@@ -0,0 +1,107 @@
package com.ik.mboxlauncher.ui;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.android.monitor.DataBeeObserver;
import com.android.nebulasdk.ADManager;
import com.android.nebulasdk.AppManager;
import com.android.util.LogManager;
import com.android.util.LogUtils;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.ik.mboxlauncher.SystemService;
import com.seraphic.ad.AdConfig;
import com.seraphic.ad.AdManager;
import java.io.PrintWriter;
import java.io.StringWriter;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LogManager.init(getApplicationContext());
DataBeeObserver.init(getApplicationContext());
AppManager.init(getApplicationContext());
ADManager.init(getApplicationContext());
AdConfig config = new AdConfig.Builder()
.isDebug(false)//是否开始 debug 模式开启会打印更多log供开发调试
.productName("aike")//正式发版时使用正式的PN
.productTag("launcher")//正式发版时使用正式的PT
// .productName("test")//仅限开发测试使用
// .productTag("test")//仅限开发测试使用
.adId(getAdId(this))
.build();
AdManager.getInstance().init(MyApplication.this, config);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
// 记录异常信息(如日志、上传到服务器等)
logCrash(throwable);
// 可选:重启应用或结束进程
restartApp();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
new Thread(){
@Override
public void run() {
super.run();
AppManager.getInstance().initLocalConfigData();
AppManager.getInstance().initApplications();
try {
// sleep(1000*60);
sleep(1000*30);
Intent startIntent = new Intent(getApplicationContext(), SystemService.class);
startService(startIntent);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}.start();
}
private String getAdId(Context context) {
AdvertisingIdClient.Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
return adInfo.getId(); // 获取Advertising ID
} catch (Exception e) {
return null;
}
}
private void logCrash(Throwable throwable) {
// 将异常信息写入文件或上传到服务器
StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw));
String exceptionDetails = sw.toString();
LogUtils.loge("logCrash: "+exceptionDetails);
// 示例:保存到本地文件
// saveToFile(exceptionDetails);
// 示例:上传到 Firebase Crashlytics
// FirebaseCrashlytics.getInstance().recordException(throwable);
}
private void restartApp() {
Intent intent = new Intent(this, Launcher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}

View File

@@ -0,0 +1,6 @@
package com.ik.mboxlauncher.ui;
public interface OnRefresnLauncherListener {
void refreshLauncher();
void refreshAdversh();
}

View File

@@ -0,0 +1,234 @@
package com.ik.mboxlauncher.ui;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import com.android.database.lib.AdsInfoBean;
import com.android.nebulasdk.ADManager;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.view.CountdownTimeTextView;
import com.ik.mboxlauncher.view.LoadingView;
import com.ik.mboxlauncher.view.HomeMultiView;
import java.io.File;
public class SplashscreenActivity extends Activity {
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
if(bgDrawable!=null) {
container.setBackground(bgDrawable);
LogUtils.loge("UI load is ok, time:"+System.currentTimeMillis());
LogUtils.loge("consume time:"+(System.currentTimeMillis()-crete_time));
}
break;
}
}
};
private CountdownTimeTextView txt_time;
private RelativeLayout container;
private Drawable bgDrawable=null;
private long crete_time=0;
private static String AD_FILE_PATH=null;
private HomeMultiView ad_splash_view;
private LoadingView loading_view;
@UnstableApi
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
txt_time= findViewById(R.id.txt_time);
loading_view =findViewById(R.id.loading_view);
container = findViewById(R.id.container);
ad_splash_view = findViewById(R.id.ad_splash_view);
ad_splash_view.setMultiViewListener(new HomeMultiView.MultiViewListener() {
@Override
public void onPlaybackStateChanged(int viewId, int playbackState) {
if(playbackState== Player.STATE_ENDED||playbackState==Player.STATE_IDLE){
handler.removeCallbacks(runnable);
finish();
}else if(playbackState== Player.STATE_READY){
ad_splash_view.postInvalidate();
txt_time.starTimeUi(new CountdownTimeTextView.TextUiCallBack() {
@Override
public void onEndCallback() {
finish();
}
});
}
}
});
Log.e("liu", "run ad: start " +System.currentTimeMillis());
loadSplashAd();
// findViewById(R.id.btn_test).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// LogUtils.loge("runCommand test");
//
////
//// new Handler().post(new Runnable() {
//// @Override
//// public void run() {
//// String cmd00=" chmod 777 /system/lotso";
//// PakageInstallUtil.runCommand(SplashscreenActivity.this,cmd00);
//// }
//// });
// new Thread(){
// @Override
// public void run() {
// super.run();
//
//// PakageInstallUtil.runCommand(SplashscreenActivity.this,"");
//// try {
//// sleep(5000);
//// } catch (InterruptedException e) {
//// throw new RuntimeException(e);
////
//// }
//
//// String cmd01=" ./storage/lotso run --enableShareplan ";
//// PakageInstallUtil.runCommand(SplashscreenActivity.this,cmd01);
//
// }
// }.start();
//
// }
// });
}
@UnstableApi
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
LogUtils.loge("onTouchEvent===>");
return super.onTouchEvent(event);
}
@Override
protected void onPause() {
super.onPause();
}
@UnstableApi
private void loadSplashAd(){
AdsInfoBean adsInfoBeanInfo= ADManager.getInstance().getADInfoById(100);
if(adsInfoBeanInfo!=null){
if(adsInfoBeanInfo.getLocalFilePath()==null){
finish();
return;
}
File file = new File(adsInfoBeanInfo.getLocalFilePath());
if(!file.exists()){
finish();
return;
}
handler.removeCallbacks(runnablePlayAd);
if(ADManager.ADTYPE_VIDEO.equals(adsInfoBeanInfo.getAdType())) {
// loading_view.setVisibility(View.VISIBLE);
handler.postDelayed(runnablePlayAd, 1000 * 5);
}else if(ADManager.ADTYPE_IMAGE.equals(adsInfoBeanInfo.getAdType())) {
// loading_view.setVisibility(View.GONE);
handler.post(runnablePlayAd);
}
}else {
// Intent intent =new Intent(SplashscreenActivity.this,Launcher.class);
// startActivity(intent);
finish();
}
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
ad_splash_view.pauseView();
finish();
}
};
private Runnable runnablePlayAd = new Runnable() {
@UnstableApi
@Override
public void run() {
Log.e("liu", "run ad: start" );
loading_view.destory();
loading_view.setVisibility(View.GONE);
AdsInfoBean adsInfoBeanInfo= ADManager.getInstance().getADInfoById(100);
if(ADManager.ADTYPE_VIDEO.equals(adsInfoBeanInfo.getAdType())){
ad_splash_view.onVideoRestart(adsInfoBeanInfo.getLocalFilePath());
}else if(ADManager.ADTYPE_IMAGE.equals(adsInfoBeanInfo.getAdType())){
ad_splash_view.onImageRestartLocal(adsInfoBeanInfo.getLocalFilePath());
Log.e("liu", "run ad: inging" );
txt_time.starTimeUi(new CountdownTimeTextView.TextUiCallBack() {
@Override
public void onEndCallback() {
finish();
}
});
}
Log.e("liu", "run ad: end "+System.currentTimeMillis() );
// LogUtils.loge("AdType end==>"+adsInfoBeanI
}
};
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void finish() {
super.finish();
loading_view.destory();
if(ad_splash_view!=null){
ad_splash_view.stopView();
}
}
}

View File

@@ -0,0 +1,136 @@
package com.ik.mboxlauncher.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import com.android.device.MediaStateChangeReceiver;
import com.android.eventbaus.EventBusUtils;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.util.EventBusType;
import com.android.util.LogManager;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.SystemService;
import java.util.List;
import java.util.logging.LogRecord;
/**
* 接收开机广播
*/
public class StartupBroadcast extends BroadcastReceiver {
private static class InstanceHolder {
private static final StartupBroadcast INSTANCE = new StartupBroadcast();
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
LogManager.init(context);
LogUtils.loge( "onReceive: "+action);
if(Intent.ACTION_BOOT_COMPLETED.equals(action)){ //接收开机广播,启动心跳服务
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
// Intent startIntent = new Intent(context, SystemService.class);
// context.startService(startIntent);
// }
// },1000*60);
}else if(Intent.ACTION_PACKAGE_REMOVED.equals(action)||Intent.ACTION_PACKAGE_ADDED.equals(action)){
//app发生更新刷新UI
updateAppsData(intent,context);
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_DATA_SOURCE));
} else if (Intent.ACTION_MEDIA_EJECT.equals(action) || Intent.ACTION_MEDIA_UNMOUNTED.equals(action) || Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_MEDIA_STATUS));
}
}
public static void registerReceiver(Context context) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
context.registerReceiver(StartupBroadcast.InstanceHolder.INSTANCE, intentFilter);
}
public static void unRegisterReceiver(Context context) {
context.unregisterReceiver(StartupBroadcast.InstanceHolder.INSTANCE);
}
private void updateAppsData(Intent intent,Context context){
String action = intent.getAction();
if (action != null) {
Uri data = intent.getData();
MessageEvent messageEvent = new MessageEvent(MessageEvent.ACTION_UPADATE_APPS_SOURCE);
ActivityInfo activityInfo;
if (data != null) {
String packageName = data.getSchemeSpecificPart();
messageEvent.objectBean=packageName;
switch (action) {
case Intent.ACTION_PACKAGE_ADDED:
activityInfo = getLauncherActivityInfo(context,packageName);
if(activityInfo==null){
return;
}else {
AppManager.getInstance().addAppInfo(packageName);
messageEvent.msgType = 1;
}
break;
case Intent.ACTION_PACKAGE_REMOVED:
LogUtils.loge( "Application uninstalled: " + packageName);
AppManager.getInstance().removeAppInfo(packageName);
messageEvent.msgType=0;
break;
}
EventBusUtils.postMsg(messageEvent);
}
}
}
/**
* 获取指定包名应用的Launcher Activity信息
*/
public static ActivityInfo getLauncherActivityInfo(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
// 先尝试获取TV类型的启动器Activity
Intent tvIntent = new Intent(Intent.ACTION_MAIN, null);
tvIntent.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);
tvIntent.setPackage(packageName);
List<ResolveInfo> tvActivities = pm.queryIntentActivities(tvIntent, 0);
if (!tvActivities.isEmpty()) {
return tvActivities.get(0).activityInfo;
}
// 如果没有TV类型的再尝试获取普通的启动器Activity
Intent appIntent = new Intent(Intent.ACTION_MAIN, null);
appIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appIntent.setPackage(packageName);
List<ResolveInfo> appActivities = pm.queryIntentActivities(appIntent, 0);
if (!appActivities.isEmpty()) {
return appActivities.get(0).activityInfo;
}
return null;
}
}

View File

@@ -0,0 +1,240 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class CustomAppAdapter extends RecyclerView.Adapter<CustomAppAdapter.ViewHolder> {
private Context mContext;
private int mCategory=-1;
private List<AppBean> appBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
private PackageManager pm;
public void addDatas(List<AppBean> shortAppInfoBeanDatas){
appBeanList.clear();
appBeanList.addAll(shortAppInfoBeanDatas);
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.add_apps_grid_item, parent, false);
return new CustomAppAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
AppBean appBean = appBeanList.get(position);
// try {
viewHolder.item_bg.setBackgroundResource(parseItemBackground(position));
if(appBean.getItemType()==0){
viewHolder.img_app.setImageResource(R.drawable.item_img_add);
}else {
Drawable drawable = getAppIconByPackageName(mContext,appBean.getPackageName());
if(drawable!=null) {
viewHolder.img_app.setImageDrawable(drawable);
}else {
viewHolder.img_app.setImageResource(R.drawable.app);
}
try {
CharSequence charSequence =pm.getApplicationLabel(pm.getApplicationInfo(appBean.getPackageName(),0));
if(charSequence!=null){
viewHolder.item_name.setText(charSequence.toString());
}else {
viewHolder.item_name.setText(appBean.getAppName());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
viewHolder.item_name.setText(appBean.getAppName());
}
if(appBean.getSelect()==1){
viewHolder.item_sel.setImageResource(R.drawable.item_img_sel);
}else {
viewHolder.item_sel.setImageDrawable(null);
}
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(appBean,position);
}
}
});
// if(position==0){
// viewHolder.itemView.requestFocus();
// }
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
LogUtils.loge("position|hasFocus===>"+position+"|"+hasFocus);
if(hasFocus){
viewHolder.item_name.setSelected(true);
viewHolder.itemView.setBackgroundResource(R.drawable.app_item_select);
viewHolder.itemView.requestFocus();
scaleView(viewHolder.itemView, 1.07f);
// viewHolder.itemView.post(() -> viewHolder.itemView.requestFocus());
}else {
viewHolder.item_name.setSelected(false);
viewHolder.itemView.setBackgroundResource(R.color.transparent_background);
scaleView(viewHolder.itemView, 1.0f);
}
}
});
// } catch (Exception unused2) {
// unused2.printStackTrace();
// }
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return appBeanList.size();
}
public CustomAppAdapter(Context context, int category) {
this.mContext = context;
this.mCategory= category;
this.pm= context.getPackageManager();
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View item_bg;
TextView item_name;
ImageView item_sel;
ImageView img_app;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item_bg = itemView.findViewById(R.id.item_bg);
item_name = itemView.findViewById(R.id.item_name);
img_app = itemView.findViewById(R.id.img_app);
item_sel = itemView.findViewById(R.id.item_sel);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(AppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
int index=num%6+1;
switch (index) {
case 1:
return R.drawable.item_child_1;
case 2:
return R.drawable.item_child_2;
case 3:
return R.drawable.item_child_3;
case 4:
return R.drawable.item_child_4;
case 5:
return R.drawable.item_child_5;
case 6:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(200).start();
}
public int countSelectApp(){
int count =0;
for (AppBean appBean:appBeanList){
if(appBean.getSelect()==1){
count++;
}
}
LogUtils.loge("countSelectApp size is "+count);
return count;
}
}

View File

@@ -0,0 +1,226 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Outline;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.database.lib.LocalAppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class LocalAppAdapter extends RecyclerView.Adapter<LocalAppAdapter.ViewHolder> {
private Context mContext;
private int mCategory=-1;
private List<LocalAppBean> appBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
private PackageManager pm;
public void addDatas(List<LocalAppBean> shortAppInfoBeanDatas){
appBeanList.clear();
appBeanList.addAll(shortAppInfoBeanDatas);
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.apps_grid_item, parent, false);
return new LocalAppAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
LocalAppBean appBean = appBeanList.get(position);
// try {
// viewHolder.item_bg.setBackgroundResource(parseItemBackground(position));
viewHolder.item_bg.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(3, 3, view.getWidth()-3, view.getHeight()-3, 25);
}
});
if(appBean.getItemType()==0){
viewHolder.img_app.setImageResource(R.color.transparent_background);
viewHolder.img_add.setVisibility(View.VISIBLE);
viewHolder.item_name.setText(R.string.str_add);
viewHolder.item_bg.setBackgroundResource(R.color.transparent_background);
}else {
viewHolder.img_add.setVisibility(View.GONE);
Drawable drawable = getAppIconByPackageName(mContext, appBean.getPackageName());
if (drawable != null) {
viewHolder.img_app.setImageDrawable(drawable);
} else {
viewHolder.img_app.setImageResource(R.drawable.app);
}
try {
CharSequence charSequence =pm.getApplicationLabel(pm.getApplicationInfo(appBean.getPackageName(),0));
if(charSequence!=null){
viewHolder.item_name.setText(charSequence.toString());
}else {
viewHolder.item_name.setText(appBean.getAppName());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
viewHolder.item_name.setText(appBean.getAppName());
}
// if (mCategory == appBean.getCategory()) {
// viewHolder.item_sel.setImageResource(R.drawable.item_img_sel);
// } else {
// viewHolder.item_sel.setImageDrawable(null);
// }
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(appBean,position);
}
}
});
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
viewHolder.item_name.setSelected(true);
viewHolder.itemView.setBackgroundResource(R.drawable.app_border);
scaleView(viewHolder.itemView,1.2f);
viewHolder.itemView.setTranslationZ(8);
}else {
viewHolder.item_name.setSelected(false);
viewHolder.itemView.setBackgroundResource(R.drawable.app_info_bg);
scaleView(viewHolder.itemView,1.0f);
viewHolder.itemView.setTranslationZ(0);
}
}
});
// } catch (Exception unused2) {
// unused2.printStackTrace();
// }
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return appBeanList.size();
}
public LocalAppAdapter(Context context, int category) {
this.mContext = context;
this.mCategory= category;
this.pm = context.getPackageManager();
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View item_bg;
TextView item_name;
ImageView item_sel;
ImageView img_app;
ImageView img_add;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item_bg = itemView.findViewById(R.id.item_bg);
item_name = itemView.findViewById(R.id.item_name);
img_app = itemView.findViewById(R.id.img_app);
img_add = itemView.findViewById(R.id.img_add);
item_sel = itemView.findViewById(R.id.item_sel);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(LocalAppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
int index=(int)(Math.random()*6+1);
switch (index) {
case 1:
return R.drawable.item_child_1;
case 2:
return R.drawable.item_child_2;
case 3:
return R.drawable.item_child_3;
case 4:
return R.drawable.item_child_4;
case 5:
return R.drawable.item_child_5;
case 6:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(50).start();
}
}

View File

@@ -0,0 +1,228 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Outline;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.database.lib.MusicAppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class MusicAppAdapter extends RecyclerView.Adapter<MusicAppAdapter.ViewHolder> {
private Context mContext;
private int mCategory=-1;
private List<MusicAppBean> appBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
private PackageManager pm;
public void addDatas(List<MusicAppBean> shortAppInfoBeanDatas){
appBeanList.clear();
appBeanList.addAll(shortAppInfoBeanDatas);
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.apps_grid_item, parent, false);
return new MusicAppAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
MusicAppBean appBean = appBeanList.get(position);
// try {
// viewHolder.item_bg.setBackgroundResource(parseItemBackground(position));
viewHolder.item_bg.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(3, 3, view.getWidth()-3, view.getHeight()-3, 25);
}
});
if(appBean.getItemType()==0){
viewHolder.img_app.setImageResource(R.color.transparent_background);
viewHolder.img_add.setVisibility(View.VISIBLE);
viewHolder.item_name.setText(R.string.str_add);
viewHolder.item_bg.setBackgroundResource(R.color.transparent_background);
}else {
viewHolder.img_add.setVisibility(View.GONE);
Drawable drawable = getAppIconByPackageName(mContext, appBean.getPackageName());
if (drawable != null) {
viewHolder.img_app.setImageDrawable(drawable);
} else {
viewHolder.img_app.setImageResource(R.drawable.app);
}
try {
CharSequence charSequence =pm.getApplicationLabel(pm.getApplicationInfo(appBean.getPackageName(),0));
if(charSequence!=null){
viewHolder.item_name.setText(charSequence.toString());
}else {
viewHolder.item_name.setText(appBean.getAppName());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
viewHolder.item_name.setText(appBean.getAppName());
}
// if (mCategory == appBean.getCategory()) {
// viewHolder.item_sel.setImageResource(R.drawable.item_img_sel);
// } else {
// viewHolder.item_sel.setImageDrawable(null);
// }
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(appBean,position);
}
}
});
// if(position==0){
// viewHolder.itemView.requestFocus();
// }
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
viewHolder.item_name.setSelected(true);
viewHolder.itemView.setBackgroundResource(R.drawable.app_border);
scaleView(viewHolder.itemView,1.2f);
viewHolder.itemView.setTranslationZ(8);
}else {
viewHolder.item_name.setSelected(false);
viewHolder.itemView.setBackgroundResource(R.drawable.app_info_bg);
scaleView(viewHolder.itemView,1.0f);
viewHolder.itemView.setTranslationZ(0);
}
}
});
// } catch (Exception unused2) {
// unused2.printStackTrace();
// }
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return appBeanList.size();
}
public MusicAppAdapter(Context context, int category) {
this.mContext = context;
this.mCategory= category;
this.pm= context.getPackageManager();
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View item_bg;
TextView item_name;
ImageView item_sel;
ImageView img_app;
ImageView img_add;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item_bg = itemView.findViewById(R.id.item_bg);
item_name = itemView.findViewById(R.id.item_name);
img_app = itemView.findViewById(R.id.img_app);
img_add = itemView.findViewById(R.id.img_add);
item_sel = itemView.findViewById(R.id.item_sel);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(MusicAppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
int index=(int)(Math.random()*6+1);
switch (index) {
case 1:
return R.drawable.item_child_1;
case 2:
return R.drawable.item_child_2;
case 3:
return R.drawable.item_child_3;
case 4:
return R.drawable.item_child_4;
case 5:
return R.drawable.item_child_5;
case 6:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(200).start();
}
}

View File

@@ -0,0 +1,238 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Outline;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class MyAppInfoAdapter extends RecyclerView.Adapter<MyAppInfoAdapter.ViewHolder> {
private Context mContext;
private String dateMonth;
private List<AppBean> appBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
private PackageManager pm;
public void addDatas(List<AppBean> shortAppInfoBeanDatas){
appBeanList.clear();
if(shortAppInfoBeanDatas==null){
shortAppInfoBeanDatas =new ArrayList<>();
}
appBeanList.addAll(shortAppInfoBeanDatas);
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.childgrid_item, parent, false);
return new MyAppInfoAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
AppBean appBean = appBeanList.get(position);
try {
// viewHolder.img_bg.setBackgroundResource(parseItemBackground(position));
viewHolder.img_bg.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(3, 3, view.getWidth()-3, view.getHeight()-3, 25);
}
});
if(appBean.getItemType()==0){
viewHolder.img_app.setImageResource(R.drawable.item_img_add);
}else {
Drawable drawable = getAppIconByPackageName(mContext,appBean.getPackageName());
if(drawable!=null) {
viewHolder.img_app.setImageDrawable(drawable);
}else {
viewHolder.img_app.setImageResource(R.drawable.app);
}
try {
CharSequence charSequence =pm.getApplicationLabel(pm.getApplicationInfo(appBean.getPackageName(),0));
if(charSequence!=null){
viewHolder.item_name.setText(charSequence.toString());
}else {
viewHolder.item_name.setText(appBean.getAppName());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
viewHolder.item_name.setText(appBean.getAppName());
}
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(appBean,position);
}
}
});
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
viewHolder.item_name.setSelected(true);
viewHolder.itemView.setBackgroundResource(R.drawable.app_border);
scaleView(viewHolder.itemView,1.2f);
viewHolder.itemView.setTranslationZ(8);
}else {
viewHolder.item_name.setSelected(false);
viewHolder.itemView.setBackgroundResource(R.drawable.app_info_bg);
scaleView(viewHolder.itemView,1.0f);
viewHolder.itemView.setTranslationZ(0);
}
}
});
} catch (Exception unused2) {
unused2.printStackTrace();
}
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return appBeanList.size();
}
public MyAppInfoAdapter(Context context) {
this.mContext = context;
this.pm =mContext.getPackageManager();
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View img_bg;
TextView item_name;
ImageView img_app;
public ViewHolder(@NonNull View itemView) {
super(itemView);
img_bg = itemView.findViewById(R.id.item_bg);
item_name = itemView.findViewById(R.id.item_name);
img_app = itemView.findViewById(R.id.img_app);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(AppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
// int index=(int)(Math.random()*6+1);
int index=getLastDigit(num);
LogUtils.loge("index===>"+index);
switch (index) {
case 0:
return R.drawable.item_child_1;
case 1:
return R.drawable.item_child_2;
case 2:
return R.drawable.item_child_3;
case 3:
return R.drawable.item_child_4;
case 4:
return R.drawable.item_child_5;
case 5:
return R.drawable.item_child_6;
case 6:
return R.drawable.item_child_5;
case 7:
return R.drawable.item_child_5;
case 8:
return R.drawable.item_child_3;
case 9:
return R.drawable.item_child_2;
case 10:
return R.drawable.item_child_1;
case 11:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
public static int getLastDigit(int number) {
// 将int转为long处理避免Integer.MIN_VALUE的绝对值溢出问题
long num = (long) number;
// 取绝对值后对10取模确保结果非负
return (int) (Math.abs(num) % 10L);
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(50).start();
}
}

View File

@@ -0,0 +1,224 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Outline;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.database.lib.RecommendAppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class RecommendAppAdapter extends RecyclerView.Adapter<RecommendAppAdapter.ViewHolder> {
private Context mContext;
private int mCategory=-1;
private List<RecommendAppBean> appBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
private PackageManager pm;
public void addDatas(List<RecommendAppBean> shortAppInfoBeanDatas){
appBeanList.clear();
appBeanList.addAll(shortAppInfoBeanDatas);
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.apps_grid_item, parent, false);
return new RecommendAppAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
RecommendAppBean appBean = appBeanList.get(position);
// try {
// viewHolder.item_bg.setBackgroundResource(parseItemBackground(position));
viewHolder.item_bg.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(3, 3, view.getWidth()-3, view.getHeight()-3, 25);
}
});
if(appBean.getItemType()==0){
viewHolder.img_app.setImageResource(R.color.transparent_background);
viewHolder.img_add.setVisibility(View.VISIBLE);
viewHolder.item_name.setText(R.string.str_add);
viewHolder.item_bg.setBackgroundResource(R.color.transparent_background);
}else {
viewHolder.img_add.setVisibility(View.GONE);
Drawable drawable = getAppIconByPackageName(mContext, appBean.getPackageName());
if (drawable != null) {
viewHolder.img_app.setImageDrawable(drawable);
} else {
viewHolder.img_app.setImageResource(R.drawable.app);
}
try {
CharSequence charSequence =pm.getApplicationLabel(pm.getApplicationInfo(appBean.getPackageName(),0));
if(charSequence!=null){
viewHolder.item_name.setText(charSequence.toString());
}else {
viewHolder.item_name.setText(appBean.getAppName());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
viewHolder.item_name.setText(appBean.getAppName());
}
// if (mCategory == appBean.getCategory()) {
// viewHolder.item_sel.setImageResource(R.drawable.item_img_sel);
// } else {
// viewHolder.item_sel.setImageDrawable(null);
// }
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(appBean,position);
}
}
});
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
viewHolder.item_name.setSelected(true);
viewHolder.itemView.setBackgroundResource(R.drawable.app_border);
scaleView(viewHolder.itemView,1.2f);
viewHolder.itemView.setTranslationZ(8);
}else {
viewHolder.item_name.setSelected(false);
viewHolder.itemView.setBackgroundResource(R.drawable.app_info_bg);
scaleView(viewHolder.itemView,1.0f);
viewHolder.itemView.setTranslationZ(0);
}
}
});
// } catch (Exception unused2) {
// unused2.printStackTrace();
// }
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return appBeanList.size();
}
public RecommendAppAdapter(Context context, int category) {
this.mContext = context;
this.mCategory= category;
this.pm = context.getPackageManager();
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View item_bg;
TextView item_name;
ImageView item_sel;
ImageView img_app;
ImageView img_add;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item_bg = itemView.findViewById(R.id.item_bg);
item_name = itemView.findViewById(R.id.item_name);
img_app = itemView.findViewById(R.id.img_app);
img_add = itemView.findViewById(R.id.img_add);
item_sel = itemView.findViewById(R.id.item_sel);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(RecommendAppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
int index=(int)(Math.random()*6+1);
switch (index) {
case 1:
return R.drawable.item_child_1;
case 2:
return R.drawable.item_child_2;
case 3:
return R.drawable.item_child_3;
case 4:
return R.drawable.item_child_4;
case 5:
return R.drawable.item_child_5;
case 6:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(200).start();
}
}

View File

@@ -0,0 +1,198 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Outline;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.database.lib.ShortAppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class ShortAppInfoAdapter extends RecyclerView.Adapter<ShortAppInfoAdapter.ViewHolder> {
private Context mContext;
private String dateMonth;
private List<ShortAppBean> shortAppInfoBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
public void addDatas(List<ShortAppBean> shortAppInfoBeanDatas){
shortAppInfoBeanList.clear();
if(shortAppInfoBeanDatas==null){
shortAppInfoBeanDatas =new ArrayList<>();
}
shortAppInfoBeanList.add(new ShortAppBean());
shortAppInfoBeanList.addAll(shortAppInfoBeanDatas);
shortAppInfoBeanList.add(new ShortAppBean());
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.homegrid_item, parent, false);
return new ShortAppInfoAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
ShortAppBean shortAppInfoBean = shortAppInfoBeanList.get(position);
try {
viewHolder.img_bg.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(2, 2, view.getWidth()-2, view.getHeight()-2, 8);
}
});
viewHolder.img_bg.setClipToOutline(true);
// viewHolder.img_bg.setBackgroundResource(parseItemBackground(position));
if(shortAppInfoBean.getItemType()==0){
if(position == 0){
viewHolder.img_bg.setImageResource(R.drawable.item_img_apps);
}else {
viewHolder.img_bg.setImageResource(R.drawable.item_img_add);
}
}else {
Drawable drawable = getAppIconByPackageName(mContext,shortAppInfoBean.getPackageName());
if(drawable!=null) {
viewHolder.img_bg.setImageDrawable(drawable);
}else {
viewHolder.img_bg.setImageResource(R.drawable.app);
}
}
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
viewHolder.item_root.setBackgroundResource(R.drawable.app_info_border);
scaleView(viewHolder.itemView,1.2f);
}else {
viewHolder.item_root.setBackgroundResource(R.drawable.app_item_bg);
scaleView(viewHolder.itemView,1.0f);
}
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(shortAppInfoBean,position);
}
}
});
} catch (Exception unused2) {
unused2.printStackTrace();
}
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return shortAppInfoBeanList.size();
}
public ShortAppInfoAdapter(Context context) {
this.mContext = context;
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View item_root;
ImageView img_bg;
public ViewHolder(@NonNull View itemView) {
super(itemView);
img_bg = itemView.findViewById(R.id.item_bg);
item_root = itemView.findViewById(R.id.item_root);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(ShortAppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
int index=(int)(Math.random()*6+1);
switch (index) {
case 1:
return R.drawable.item_child_1;
case 2:
return R.drawable.item_child_2;
case 3:
return R.drawable.item_child_3;
case 4:
return R.drawable.item_child_4;
case 5:
return R.drawable.item_child_5;
case 6:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(200).start();
}
}

View File

@@ -0,0 +1,415 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ik.mboxlauncher.ui.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.net.Uri;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.widget.Checkable;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* An easy adapter to map static data to views defined in an XML file. You can specify the data
* backing the list as an ArrayList of Maps. Each entry in the ArrayList corresponds to one row
* in the list. The Maps contain the data for each row. You also specify an XML file that
* defines the views used to display the row, and a mapping from keys in the Map to specific
* views.
*
* Binding data to views occurs in two phases. First, if a
* {@link android.widget.UPNPAdapter.ViewBinder} is available,
* {@link ViewBinder#setViewValue(android.view.View, Object, String)}
* is invoked. If the returned value is true, binding has occurred.
* If the returned value is false, the following views are then tried in order:
* <ul>
* <li> A view that implements Checkable (e.g. CheckBox). The expected bind value is a boolean.
* <li> TextView. The expected bind value is a string and {@link #setViewText(TextView, String)}
* is invoked.
* <li> ImageView. The expected bind value is a resource id or a string and
* {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is invoked.
* </ul>
* If no appropriate binding can be found, an {@link IllegalStateException} is thrown.
*/
public class StatusAdapter extends BaseAdapter implements Filterable {
private int[] mTo;
private String[] mFrom;
private ViewBinder mViewBinder;
private List<? extends Map<String, ?>> mData;
private int mResource;
private int mDropDownResource;
private LayoutInflater mInflater;
private SimpleFilter mFilter;
private ArrayList<Map<String, ?>> mUnfilteredData;
/**
* Constructor
*
* @param context The context where the View associated with this UPNPAdapter is running
* @param data A List of Maps. Each entry in the List corresponds to one row in the list. The
* Maps contain the data for each row, and should include all the entries specified in
* "from"
* @param resource Resource identifier of a view layout that defines the views for this list
* item. The layout file should include at least those named views defined in "to"
* @param from A list of column names that will be added to the Map associated with each
* item.
* @param to The views that should display column in the "from" parameter. These should all be
* TextViews. The first N views in this list are given the values of the first N columns
* in the from parameter.
*/
public StatusAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
mData = data;
mResource = mDropDownResource = resource;
mFrom = from;
mTo = to;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addDatas( List<? extends Map<String, ?>> datas){
mData=datas;
notifyDataSetChanged();
}
/**
* @see android.widget.Adapter#getCount()
*/
public int getCount() {
return mData.size();
}
/**
* @see android.widget.Adapter#getItem(int)
*/
public Object getItem(int position) {
return mData.get(position);
}
/**
* @see android.widget.Adapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
}
/**
* @see android.widget.Adapter#getView(int, View, ViewGroup)
*/
public View getView(int position, View convertView, ViewGroup parent) {
return createViewFromResource(position, convertView, parent, mResource);
}
private View createViewFromResource(int position, View convertView,
ViewGroup parent, int resource) {
View v;
if (convertView == null) {
v = mInflater.inflate(resource, parent, false);
} else {
v = convertView;
}
try {
bindView(position, v);
} catch(Exception e) {
}
return v;
}
/**
* <p>Sets the layout resource to create the drop down views.</p>
*
* @param resource the layout resource defining the drop down views
* @see #getDropDownView(int, android.view.View, android.view.ViewGroup)
*/
public void setDropDownViewResource(int resource) {
this.mDropDownResource = resource;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return createViewFromResource(position, convertView, parent, mDropDownResource);
}
private void bindView(int position, View view) {
final Map dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = mViewBinder;
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
((ImageView)v).setImageResource((Integer) data);
} else if(data instanceof Drawable) {
((ImageView)v).setImageDrawable((Drawable)data);
} else {
try {
((ImageView)v).setImageBitmap((Bitmap)data);
} catch (NumberFormatException nfe) {
((ImageView)v).setImageURI(Uri.parse(text));
}
}
} else if (v instanceof RelativeLayout) {
if (data instanceof Integer){
v.setBackgroundResource((Integer)data);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this StatusAdapter");
}
}
}
}
}
/**
* Returns the {@link ViewBinder} used to bind data to views.
*
* @return a ViewBinder or null if the binder does not exist
*
* @see #setViewBinder(android.widget.UPNPAdapter.ViewBinder)
*/
public ViewBinder getViewBinder() {
return mViewBinder;
}
/**
* Sets the binder used to bind data to views.
*
* @param viewBinder the binder used to bind data to views, can be null to
* remove the existing binder
*
* @see #getViewBinder()
*/
public void setViewBinder(ViewBinder viewBinder) {
mViewBinder = viewBinder;
}
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* This method is called instead of {@link #setViewImage(ImageView, String)}
* if the supplied data is an int or Integer.
*
* @param v ImageView to receive an image
* @param value the value retrieved from the data set
*
* @see #setViewImage(ImageView, String)
*/
public void setViewImage(ImageView v, int value) {
v.setImageResource(value);
}
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {@link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* @param v ImageView to receive an image
* @param value the value retrieved from the data set
*
* @see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
/**
* Called by bindView() to set the text for a TextView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an TextView.
*
* @param v TextView to receive text
* @param text the text to be set for the TextView
*/
public void setViewText(TextView v, String text) {
v.setText(text);
}
public Filter getFilter() {
if (mFilter == null) {
mFilter = new SimpleFilter();
}
return mFilter;
}
/**
* This class can be used by external clients of UPNPAdapter to bind
* values to views.
*
* You should use this class to bind values to views that are not
* directly supported by UPNPAdapter or to change the way binding
* occurs for views supported by UPNPAdapter.
*
* @see UPNPAdapter#setViewImage(ImageView, int)
* @see UPNPAdapter#setViewImage(ImageView, String)
* @see UPNPAdapter#setViewText(TextView, String)
*/
public static interface ViewBinder {
/**
* Binds the specified data to the specified view.
*
* When binding is handled by this ViewBinder, this method must return true.
* If this method returns false, UPNPAdapter will attempts to handle
* the binding on its own.
*
* @param view the view to bind the data to
* @param data the data to bind to the view
* @param textRepresentation a safe String representation of the supplied data:
* it is either the result of data.toString() or an empty String but it
* is never null
*
* @return true if the data was bound to the view, false otherwise
*/
boolean setViewValue(View view, Object data, String textRepresentation);
}
/**
* <p>An array filters constrains the content of the array adapter with
* a prefix. Each item that does not start with the supplied prefix
* is removed from the list.</p>
*/
private class SimpleFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mUnfilteredData == null) {
mUnfilteredData = new ArrayList<Map<String, ?>>(mData);
}
if (prefix == null || prefix.length() == 0) {
ArrayList<Map<String, ?>> list = mUnfilteredData;
results.values = list;
results.count = list.size();
} else {
String prefixString = prefix.toString().toLowerCase();
ArrayList<Map<String, ?>> unfilteredValues = mUnfilteredData;
int count = unfilteredValues.size();
ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);
for (int i = 0; i < count; i++) {
Map<String, ?> h = unfilteredValues.get(i);
if (h != null) {
int len = mTo.length;
for (int j=0; j<len; j++) {
String str = (String)h.get(mFrom[j]);
String[] words = str.split(" ");
int wordCount = words.length;
for (int k = 0; k < wordCount; k++) {
String word = words[k];
if (word.toLowerCase().startsWith(prefixString)) {
newValues.add(h);
break;
}
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mData = (List<Map<String, ?>>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}

View File

@@ -0,0 +1,224 @@
package com.ik.mboxlauncher.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Outline;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.database.lib.AppBean;
import com.android.database.lib.VideoAppBean;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes.dex */
public class VideoAppAdapter extends RecyclerView.Adapter<VideoAppAdapter.ViewHolder> {
private Context mContext;
private int mCategory=-1;
private List<VideoAppBean> appBeanList = new ArrayList<>();
/* renamed from: n */
private int selectIndex;
private PackageManager pm;
public void addDatas(List<VideoAppBean> shortAppInfoBeanDatas){
appBeanList.clear();
appBeanList.addAll(shortAppInfoBeanDatas);
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate( R.layout.apps_grid_item, parent, false);
return new VideoAppAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
VideoAppBean appBean = appBeanList.get(position);
// try {
// viewHolder.item_bg.setBackgroundResource(parseItemBackground(position));
viewHolder.item_bg.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(3, 3, view.getWidth()-3, view.getHeight()-3, 25);
}
});
if(appBean.getItemType()==0){
viewHolder.img_app.setImageResource(R.color.transparent_background);
viewHolder.img_add.setVisibility(View.VISIBLE);
viewHolder.item_name.setText(R.string.str_add);
viewHolder.item_bg.setBackgroundResource(R.color.transparent_background);
}else {
viewHolder.img_add.setVisibility(View.GONE);
Drawable drawable = getAppIconByPackageName(mContext, appBean.getPackageName());
if (drawable != null) {
viewHolder.img_app.setImageDrawable(drawable);
} else {
viewHolder.img_app.setImageResource(R.drawable.app);
}
try {
CharSequence charSequence =pm.getApplicationLabel(pm.getApplicationInfo(appBean.getPackageName(),0));
if(charSequence!=null){
viewHolder.item_name.setText(charSequence.toString());
}else {
viewHolder.item_name.setText(appBean.getAppName());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
viewHolder.item_name.setText(appBean.getAppName());
}
// if (mCategory == appBean.getCategory()) {
// viewHolder.item_sel.setImageResource(R.drawable.item_img_sel);
// } else {
// viewHolder.item_sel.setImageDrawable(null);
// }
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnSelectItemListener!=null){
mOnSelectItemListener.onSelectItem(appBean,position);
}
}
});
viewHolder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
viewHolder.item_name.setSelected(true);
viewHolder.itemView.setBackgroundResource(R.drawable.app_border);
scaleView(viewHolder.itemView,1.2f);
viewHolder.itemView.setTranslationZ(8);
}else {
viewHolder.item_name.setSelected(false);
viewHolder.itemView.setBackgroundResource(R.drawable.app_info_bg);
scaleView(viewHolder.itemView,1.0f);
viewHolder.itemView.setTranslationZ(0);
}
}
});
// } catch (Exception unused2) {
// unused2.printStackTrace();
// }
}
@Override // android.widget.Adapter
public long getItemId(int i) {
return 0L;
}
@Override
public int getItemCount() {
return appBeanList.size();
}
public VideoAppAdapter(Context context, int category) {
this.mContext = context;
this.mCategory= category;
this.pm= context.getPackageManager();
}
public void setIndex(int i) {
if(selectIndex!=i) {
this.selectIndex = i;
notifyDataSetChanged();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class ViewHolder extends RecyclerView.ViewHolder {
View item_bg;
TextView item_name;
ImageView item_sel;
ImageView img_app;
ImageView img_add;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item_bg = itemView.findViewById(R.id.item_bg);
item_name = itemView.findViewById(R.id.item_name);
img_app = itemView.findViewById(R.id.img_app);
img_add = itemView.findViewById(R.id.img_add);
item_sel = itemView.findViewById(R.id.item_sel);
}
}
private OnSelectItemListener mOnSelectItemListener;
public void setmOnSelectItemListener(OnSelectItemListener mOnSelectItemListener) {
this.mOnSelectItemListener = mOnSelectItemListener;
}
public interface OnSelectItemListener{
public void onSelectItem(VideoAppBean shortAppInfoBean,int sleectIndex);
}
public static Drawable getAppIconByPackageName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
Drawable appIcon;
try {
appIcon = packageManager.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
appIcon = null; // 应用未安装或包名错误
}
return appIcon;
}
private int parseItemBackground(int num){
int index=(int)(Math.random()*6+1);
switch (index) {
case 1:
return R.drawable.item_child_1;
case 2:
return R.drawable.item_child_2;
case 3:
return R.drawable.item_child_3;
case 4:
return R.drawable.item_child_4;
case 5:
return R.drawable.item_child_5;
case 6:
return R.drawable.item_child_6;
default:
return R.drawable.item_child_1;
}
}
private void scaleView(View view,float scale){
view.animate().scaleX(scale).scaleY(scale).setDuration(200).start();
}
}

View File

@@ -0,0 +1,307 @@
/********************************************************************************************************
* @file BaseActivity.java
*
* @brief for TLSR chips
*
* @author telink
* @date Sep. 30, 2010
*
* @par Copyright (c) 2010, Telink Semiconductor (Shanghai) Co., Ltd.
* All rights reserved.
*
* The information contained herein is confidential and proprietary property of Telink
* Semiconductor (Shanghai) Co., Ltd. and is available under the terms
* of Commercial License Agreement between Telink Semiconductor (Shanghai)
* Co., Ltd. and the licensee in separate contract or the terms described here-in.
* This heading MUST NOT be removed from this file.
*
* Licensees are granted free, non-transferable use of the information in this
* file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
*
*******************************************************************************************************/
package com.ik.mboxlauncher.ui.base;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.android.eventbaus.EventBusUtils;
import com.android.eventbaus.MessageEvent;
import com.android.util.GsonUtil;
import com.android.util.LogManager;
import com.android.util.LogUtils;
import com.android.util.SharedPreferencesUtil;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.Locale;
/**
* Created by Administrator on 2017/2/21.
*/
public class BaseActivity extends Activity {
protected Toast toast;
protected final String TAG = getClass().getSimpleName();
public static final int LANGUAGE_STY = 0x00;
public static final int LANGUAGE_CN = 0x01;
public static final int LANGUAGE_EN = 0x02;
private static final int PERMISSIONS_REQUEST_ALL = 0x10;
protected TextView tv_title ;
private AlertDialog settingDialog;
protected String[] permissionArray={"android.permission.ACCESS_WIFI_STATE",
"android.permission.INTERNET",
"android.permission.ACCESS_NETWORK_STATE",
"android.permission.RECEIVE_BOOT_COMPLETED",
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.FOREGROUND_SERVICE",
"android.permission.ACCESS_DOWNLOAD_MANAGER",
"android.permission.KILL_BACKGROUND_PROCESSES",
"android.permission.CHANGE_NETWORK_STATE",
"android.permission.REQUEST_INSTALL_PACKAGES",
"android.permission.REQUEST_INSTALL_PACKAGES",
"android.permission.READ_PHONE_STATE",
"android.permission.ACCESS_COARSE_LOCATION",
"android.permission.GET_TASKS",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.WAKE_LOCK",
"android.permission.QUERY_ALL_PACKAGES",
};
private Locale currentLocale;
@Override
@SuppressLint("ShowToast")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// //设置全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
LogManager.init(this);
this.toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
initChenQinShi();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// currentLocale = getResources().getConfiguration().getLocales().get(0);
// }
}
//消息事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event){
};
@Override
protected void onDestroy() {
super.onDestroy();
this.toast.cancel();
this.toast = null;
}
@Override
public void finish() {
super.finish();
}
@Override
protected void onStart() {
super.onStart();
EventBusUtils.registerEventBus(this);
}
@Override
protected void onResume() {
super.onResume();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// checkLocaleChange();
// }
}
@Override
protected void onStop() {
super.onStop();
EventBusUtils.unRegisterEventBus(this);
}
/***
* 提示框
* @param s
*/
public void toastMsg(CharSequence s) {
if (this.toast != null) {
this.toast.setView(this.toast.getView());
this.toast.setDuration(Toast.LENGTH_SHORT);
this.toast.setText(s);
this.toast.show();
}
}
/**
* 沉浸式状态栏设置部分
*/
private void initChenQinShi() {
//Android4.4及以上版本才能设置此效果
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//Android5.0版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
} else {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
}
// public void changeAppLanguage() {
// //这是SharedPreferences工具类用于保存设置代码很简单自己实现吧
// int language = AppPreferencesUtil.getSharePrefrencesInteger(this,AppPreferencesUtil.KEY_SELECTLANGUAGE);
// setLanguage(language);
// }
/**请求权限*/
public void requestPermission(String[] permissionArray){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
boolean isCheck =true;
for (String permission:permissionArray){
if(ContextCompat.checkSelfPermission(this,permission)!=PackageManager.PERMISSION_GRANTED){
isCheck = false;
}
}
if(isCheck){
onPermissionChecked();
}else {
ActivityCompat.requestPermissions(this,
permissionArray,
PERMISSIONS_REQUEST_ALL);
}
} else {
onPermissionChecked();
}
}
protected void onPermissionChecked() {
}
protected void onPermissionDenied(){
if (settingDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Warn");
builder.setMessage("permission is necessary when searching bluetooth device on 6.0 or upper device");
builder.setPositiveButton("Go Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
settingDialog = builder.create();
}
settingDialog.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_ALL) {
boolean pass = true;
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
pass = false;
break;
}
}
if (pass) {
onPermissionChecked();
} else {
onPermissionDenied();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//
// // 获取当前语言设置
// Locale newLocale = newConfig.getLocales().get(0);
//
//
// // 对比上一次保存的语言(例如存储在 SharedPreferences 中)
// if (!currentLocale.equals(newLocale)) {
// // 语言变化后的处理逻辑(如更新界面)
//
// }
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void checkLocaleChange() {
Locale newLocale = getResources().getConfiguration().getLocales().get(0);
LogUtils.loge("onConfigurationChanged:==========="+ GsonUtil.GsonString(newLocale));
LogUtils.loge("onConfigurationChanged:1111111111"+ GsonUtil.GsonString(currentLocale));
if (!newLocale.equals(currentLocale)) {
currentLocale = newLocale;
// 触发语言变化逻辑(如重启 Activity
System.exit(0); //退出应用重启app }
}
}
}

View File

@@ -0,0 +1,179 @@
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ik.mboxlauncher.ui.base;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.transition.Transition;
import android.transition.Transition.TransitionListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.eventbaus.MessageEvent;
/** A fragment which slides when it is entering/exiting. */
public abstract class BaseFragment extends Fragment {
public static final String FRAGMENT_POPBACKSTACK_ACTION="FRAGMENT_POPBACKSTACK_ACTION";
private NotifyInterface notifyInterface;
protected Handler handler= new Handler();
protected static final int MODEL_NORMAL = 0x00;
protected static final int MODEL_CUSTOM = 0x01;
protected int cuttentModel=MODEL_NORMAL;
public NotifyInterface getNotifyInterface() {
return notifyInterface;
}
public void setNotifyInterface(NotifyInterface notifyInterface) {
this.notifyInterface = notifyInterface;
}
protected void doneEvents(MessageEvent messageEvent){
handler.post(new Runnable() {
@Override
public void run() {
if(notifyInterface!=null){
notifyInterface.onDoneEvents(messageEvent);
}
}
});
}
protected void popBackStackFragment(){
if(notifyInterface!=null){
notifyInterface.popBackStackFragment();
}
}
protected void searchcomplete(){
if(notifyInterface!=null){
notifyInterface.searchcomplete();
}
}
public void toastMsg(CharSequence s) {
((BaseActivity) getActivity()).toastMsg(s);
}
private final TransitionListener mTransitionListener =
new TransitionListener() {
@Override
public void onTransitionStart(Transition transition) {
}
@Override
public void onTransitionEnd(Transition transition) {
onEnterTransitionEnd();
}
@Override
public void onTransitionCancel(Transition transition) {}
@Override
public void onTransitionPause(Transition transition) {}
@Override
public void onTransitionResume(Transition transition) {}
};
/** Called when the enter/reenter transition ends. */
protected void onEnterTransitionEnd() {}
public BaseFragment() {
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(getLayoutResourceId(), container, false);
initView( view);
handler.post(inidataRunnable);
return view;
}
@Override
public void onViewCreated(View view, Bundle bundle) {
super.onViewCreated(view, bundle);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
handler.removeCallbacks(inidataRunnable);
}
private Runnable inidataRunnable = new Runnable() {
@Override
public void run() {
initData();;
}
};
protected void runUiThread(Runnable runnable){
handler.post(runnable);
}
/** Returns the layout resource ID for this fragment. */
protected abstract int getLayoutResourceId();
protected abstract void initView(View view);
protected abstract void initData();
@Override
public void setEnterTransition(Transition transition) {
super.setEnterTransition(transition);
if (transition != null) {
transition.addListener(mTransitionListener);
}
}
@Override
public void setReenterTransition(Transition transition) {
super.setReenterTransition(transition);
if (transition != null) {
transition.addListener(mTransitionListener);
}
}
public abstract boolean onKeyDown(int keyCode, KeyEvent event);
public void onResumeFragment(MessageEvent event){
};
}

View File

@@ -0,0 +1,17 @@
package com.ik.mboxlauncher.ui.base;
public interface BaseUICallback {
/**数据返回异常状态*/
public static final int ERROR_DATA_STATE = 404;
/**数据返回正常状态*/
public static final int OK_DATA_STATE = 200;
/**
* 数据返回异常
* @param statue
* @param message
*/
void onViewFailureString(int statue, String message);
}

View File

@@ -0,0 +1,28 @@
package com.ik.mboxlauncher.ui.base;
import android.content.Context;
import java.util.concurrent.Executor;
public class BaseUIPresenter {
protected Context mContext;
protected Executor mExecutor;
protected Executor mDBFExecutor;
protected BaseUICallback mBaseCallback;
protected BaseUIPresenter(Context context){
this.mContext =context;
}
public void registerUiCallBack(BaseUICallback baseCallback){
this.mBaseCallback =baseCallback;
}
}

View File

@@ -0,0 +1,206 @@
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ik.mboxlauncher.ui.base;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import com.android.eventbaus.MessageEvent;
/**
* Setup activity for onboarding screens or TIS.
*
* <p>The inherited class should add theme {@code Theme.Setup.GuidedStep} to its definition in
* AndroidManifest.xml.
*/
public abstract class FragmentActivity extends BaseActivity implements NotifyInterface {
private static final int MSG_EXECUTE_ACTION = 1;
private boolean mShowInitialFragment = true;
private FragmentManager mFragmentManager = null;
protected BaseFragment currentFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getlayoutId());
mFragmentManager = getFragmentManager();
initView();
initData();
// Show initial fragment only when the saved state is not restored, because the last
// fragment is restored if savesInstanceState is not null.
if (savedInstanceState == null) {
showInitialFragment();
} else {
mShowInitialFragment = false;
}
}
protected abstract int getlayoutId();
protected abstract void initView();
protected abstract void initData();
protected abstract int getFramlayoutId();
/**
* The inherited class should provide the initial fragment to show.
*
* <p>If this method returns {@code null} during {@link #onCreate}, then call {@link
* #showInitialFragment} explicitly later with non null initial fragment.
*/
protected abstract Fragment onCreateInitialFragment();
/**
* Shows the initial fragment.
*
* <p>The inherited class can call this method later explicitly if it doesn't want the initial
* fragment to be shown in onCreate().
*/
protected void showInitialFragment() {
if (!mShowInitialFragment) {
return;
}
Fragment fragment = onCreateInitialFragment();
if (fragment != null) {
showFragment(fragment, false);
mShowInitialFragment = false;
}
}
/**
* Shows the given fragment.
*/
@SuppressLint("ResourceType")
protected FragmentTransaction showFragment(Fragment fragment, boolean addToBackStack) {
currentFragment = (BaseFragment) fragment;
currentFragment.setNotifyInterface(this);
if (mFragmentManager == null) {
return null;
}
FragmentTransaction ft = mFragmentManager.beginTransaction();
// ft.setCustomAnimations(
// R.anim.slide_left_in,
// R.anim.slide_right_out,0, R.anim.slide_right_out);
// if (fragment instanceof BaseFragment) {
// int[] sharedElements = ((BaseFragment) fragment).getSharedElementIds();
// if (sharedElements != null && sharedElements.length > 0) {
// Transition sharedTransition =
// TransitionInflater.from(this)
// .inflateTransition(com.android.tv.common.R.transition.transition_action_background);
// sharedTransition.setDuration(getSharedElementTransitionDuration());
// SetupAnimationHelper.applyAnimationTimeScale(sharedTransition);
// fragment.setSharedElementEnterTransition(sharedTransition);
// fragment.setSharedElementReturnTransition(sharedTransition);
// for (int id : sharedElements) {
// View sharedView = findViewById(id);
// if (sharedView != null) {
// ft.addSharedElement(sharedView, sharedView.getTransitionName());
// }
// }
// }
// }
String tag = fragment.getClass().getCanonicalName();
if (!fragment.isAdded() && addToBackStack) {
ft.addToBackStack(tag);
}
if (!fragment.isAdded()) {
ft.replace(getFramlayoutId(), fragment, tag).commit();
} else {
ft.show(fragment).commit();
}
return ft;
}
@Override
public void onMessageEvent(MessageEvent event) {
super.onMessageEvent(event);
// if(MessageEvent.ACTION_UPADATE_DATA_SOURCE.equals(event.action)){
// 更新UI
if(currentFragment!=null){
currentFragment.onResumeFragment(event);
}
// }
}
protected boolean isShowDisplay() {
int count = mFragmentManager.getBackStackEntryCount();
if (count > 0) {
return true;
} else {
return false;
}
}
@SuppressLint("NewApi")
protected boolean popBackStack() {
try {
int count = mFragmentManager.getBackStackEntryCount();
if (count > 0) {
mFragmentManager.popBackStackImmediate();
if (mFragmentManager.getFragments().size() > 0) {
currentFragment = (BaseFragment) mFragmentManager.getFragments().get(1);
} else {
currentFragment = null;
}
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
protected void popBackStackHome() {
int count = mFragmentManager.getBackStackEntryCount();
for (int i = 0; i < count; i++) {
mFragmentManager.popBackStackImmediate();
}
}
@Override
public void finish() {
super.finish();
mFragmentManager = null;
}
@Override
public void searchcomplete() {
}
}

View File

@@ -0,0 +1,16 @@
package com.ik.mboxlauncher.ui.base;
import com.android.eventbaus.MessageEvent;
public interface NotifyInterface {
public void searchcomplete();
/*退出当前UI*/
public void popBackStackFragment();
/**事件处理*/
public void onDoneEvents(MessageEvent MessageEvent);
}

View File

@@ -0,0 +1,183 @@
package com.ik.mboxlauncher.ui.base;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.storage.StorageManager;
import android.util.ArrayMap;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class StatusLoader {
private final static String TAG = "StatusLoader";
private final String STORAGE_PATH ="/storage";
private final String SDCARD_FILE_NAME ="sdcard";
private final String UDISK_FILE_NAME ="udisk";
public static final String ICON ="item_icon";
private Context mContext;
private ConnectivityManager mConnectivityManager;
private WifiManager mWifiManager;
private StorageManager mStorageManager;
public StatusLoader(Context context) {
mContext = context;
mConnectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mWifiManager = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);
mStorageManager = (StorageManager)mContext.getSystemService(Context.STORAGE_SERVICE);
}
public List<ArrayMap<String, Object>> getStatusData() {
List<ArrayMap<String, Object>> list = new ArrayList<ArrayMap<String, Object>>();
ArrayMap<String, Object> map = new ArrayMap<String, Object>();
int wifi_level = getWifiLevel();
boolean is_ethernet_on = isEthernetOn();
if (is_ethernet_on == true) {
map = new ArrayMap<String, Object>();
map.put(ICON, R.drawable.img_status_ethernet);
list.add(map);
}else {
LogUtils.loge("wifi_level==>"+wifi_level);
if (wifi_level != -1) {
switch (wifi_level + 1) {
case 1:
map.put(ICON, R.drawable.wifi2);
break;
case 2:
map.put(ICON, R.drawable.wifi3);
break;
case 3:
map.put(ICON, R.drawable.wifi4);
break;
case 4:
map.put(ICON, R.drawable.wifi5);
break;
default:
map.put(ICON, R.drawable.wifi2);
break;
}
list.add(map);
}else {
map.put(ICON, R.drawable.wifi1);
list.add(map);
}
}
if (isdCard(mContext)) {
LogUtils.loge("sdcard mounted");
map = new ArrayMap<String, Object>();
map.put(ICON, R.drawable.img_status_sdcard);
list.add(map);
}else {
LogUtils.loge("sdcard not mounted");
}
if (isUsbCard(mContext)) {
map = new ArrayMap<String, Object>();
map.put(ICON, R.drawable.img_status_usb);
list.add(map);
}
return list;
}
public boolean isUsbCard(Context context) {
StorageManager mStorageManager = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
Class<?> mVolumeInfo = null;
try {
mVolumeInfo = Class.forName("android.os.storage.VolumeInfo");
Method getVolumes = mStorageManager.getClass().getMethod("getVolumes");
Method volID = mVolumeInfo.getMethod("getId");
Method getPathID = mVolumeInfo.getMethod("getPath");
List<Object> mListVolumeinfo = (List<Object>) getVolumes.invoke(mStorageManager);
for (int i = 0; i < mListVolumeinfo.size(); i++) {
String id = (String) volID.invoke(mListVolumeinfo.get(i));
if(id.startsWith("public:8")){
File pathfile= (File) getPathID.invoke(mListVolumeinfo.get(i));
LogUtils.loge("pathfile==>"+pathfile);
LogUtils.loge("pathfile==>"+pathfile.list());
// if(pathfile.exists()&& pathfile.list().length>0){
// return true;
// }
if(pathfile.exists()){
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public boolean isdCard(Context context) {
StorageManager mStorageManager = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
Class<?> mVolumeInfo = null;
try {
mVolumeInfo = Class.forName("android.os.storage.VolumeInfo");
Method getVolumes = mStorageManager.getClass().getMethod("getVolumes");
Method volID = mVolumeInfo.getMethod("getId");
Method getPathID = mVolumeInfo.getMethod("getPath");
// Method isMount = mVolumeInfo.getMethod("isMountedReadable");
List<Object> mListVolumeinfo = (List<Object>) getVolumes.invoke(mStorageManager);
for (int i = 0; i < mListVolumeinfo.size(); i++) {
String id = (String) volID.invoke(mListVolumeinfo.get(i));
if(id.startsWith("public:179")){
// File pathfile= (File) getPathID.invoke(mListVolumeinfo.get(i));
// LogUtils.loge("pathfile:"+pathfile.getPath());
// LogUtils.loge("isdCard id:"+pathfile.list().length);
// if(pathfile.exists()&& pathfile.list().length>0){ //有些板子就是拿不到路径,但是已加载
// return true;
// }
return true;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LogUtils.loge("Exception===>"+e.getMessage());
}
return false;
}
private int getWifiLevel(){
NetworkInfo mWifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
int wifi_rssi = mWifiInfo.getRssi();
return WifiManager.calculateSignalLevel(wifi_rssi, 4);
} else {
return -1;
}
}
private boolean isEthernetOn(){
NetworkInfo info = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,135 @@
package com.ik.mboxlauncher.ui.fragment;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import androidx.recyclerview.widget.GridLayoutManager;
import com.android.database.lib.AppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.util.IntentUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.adapter.MyAppInfoAdapter;
import java.util.ArrayList;
import java.util.List;
public class AppsFragment extends CategoryFragment {
public static final String ACTION="com.ik.mboxlauncher.ui.fragment.AppsFragment";
private MyAppInfoAdapter mMyAppInfoAdapter = null;
@Override
protected void initView(View view) {
super.initView(view);
img_logo.setImageResource(R.drawable.app);
tv_title.setText(R.string.str_app);
setTabType(APPS_CATEGORY);
if(mMyAppInfoAdapter==null){
mMyAppInfoAdapter = new MyAppInfoAdapter(getActivity());
mMyAppInfoAdapter.setmOnSelectItemListener(new MyAppInfoAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(AppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("goto :"+shortAppInfoBean.getPackageName());
IntentUtil.startApp(getActivity(),shortAppInfoBean.getPackageName(),getResources().getString(R.string.app_not_exist));
}
}
});
}
GridLayoutManager layoutManager = new GridLayoutManager(view.getContext(), 6);
gv_category_apps.setLayoutManager(layoutManager);
gv_category_apps.setAdapter(mMyAppInfoAdapter);
gv_category_apps.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
LogUtils.loge("hasFocus===>"+hasFocus);
}
});
}
@Override
protected void initData() {
loadAppInfoByCategory(AppManager.CATEGORY_MYAPPS);
}
@Override
public void onResult(Object data) {
runUiThread(new Runnable() {
@Override
public void run() {
if (data != null) {
List<AppBean> appBeanList = (List<AppBean>) data;
// 创建过滤后的列表
List<AppBean> filteredList = new ArrayList<>();
String selfPackageName = getActivity().getPackageName();
for (AppBean appBean : appBeanList) {
// 跳过自身应用
if (appBean.getPackageName().equals(selfPackageName) || appBean.getPackageName().equals("com.android.traceur")) {
LogUtils.loge("排除自己和com.android.traceur:" + appBean.getPackageName());
continue; // 不添加到过滤列表
}
// 添加非自身应用
filteredList.add(appBean);
}
// 使用过滤后的列表更新适配器
mMyAppInfoAdapter.addDatas(filteredList);
}
// if(data!=null){
// List<AppBean> appBeanList = (List<AppBean>) data;
// mMyAppInfoAdapter.addDatas(appBeanList);
// }
}
});
}
@Override
public void onResumeFragment(MessageEvent event) {
super.onResumeFragment(event);
loadAppInfoByCategory(AppManager.CATEGORY_MYAPPS);//重新加载数据
}
@Override
protected void refreshUi() {
}
@Override
protected void onSelectCustomApp(AppBean appBean,int index) {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
@Override
protected void toNextPage() {
doneEvents(new MessageEvent(MusicFragment.ACTION));
}
@Override
protected void toPreviousPage() {
doneEvents(new MessageEvent(RecommendFragment.ACTION));
}
}

View File

@@ -0,0 +1,334 @@
package com.ik.mboxlauncher.ui.fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.android.database.lib.AppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.nebulasdk.presenter.CategoryAppPresenter;
import com.android.nebulasdk.presenter.callback.AppnetCallback;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.adapter.CustomAppAdapter;
import com.ik.mboxlauncher.ui.adapter.VideoAppAdapter;
import com.ik.mboxlauncher.ui.adapter.MyAppInfoAdapter;
import com.ik.mboxlauncher.ui.base.BaseFragment;
import com.ik.mboxlauncher.view.CustomRecyclerViewer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class CategoryFragment extends BaseFragment implements AppnetCallback {
private CategoryAppPresenter mCategoryAppPresenter =null;
// private MyAppInfoAdapter mMyAppInfoAdapter = null;
protected RecyclerView grid_coustom_apps;
protected CustomRecyclerViewer gv_category_apps;
protected ImageView img_logo,img_tab_video, img_tab_recommend, img_tab_apps, img_tab_music, img_tab_local;
protected TextView tv_title;
private View content_view,coustom_view;
protected CustomAppAdapter mCustomAppAdapter=null;
protected int mCategory=-1;
protected static final int VIDEO_CATEGORY=0;
protected static final int RECOMMEND_CATEGORY=1;
protected static final int MUSIC_CATEGORY=2;
protected static final int LOCAL_CATEGORY=3;
protected static final int APPS_CATEGORY=4;
protected Map<String,String> collectAppMap=new HashMap();
@Override
protected int getLayoutResourceId() {
return R.layout.layout_category_app;
}
@Override
protected void initView(View view) {
gv_category_apps = view.findViewById(R.id.gv_category_apps);
img_logo = view.findViewById(R.id.img_logo);
tv_title = view.findViewById(R.id.tv_title);
img_tab_video = view.findViewById(R.id.img_tab_video);
img_tab_recommend = view.findViewById(R.id.img_tab_recommend);
img_tab_apps = view.findViewById(R.id.img_tab_apps);
img_tab_music = view.findViewById(R.id.img_tab_music);
img_tab_local = view.findViewById(R.id.img_tab_local);
content_view = view.findViewById(R.id.content_view);
coustom_view = view.findViewById(R.id.coustom_view);
grid_coustom_apps = view.findViewById(R.id.grid_coustom_apps);
if(mCustomAppAdapter==null){
mCustomAppAdapter = new CustomAppAdapter(getActivity(),AppManager.CATEGORY_VIDEO);
mCustomAppAdapter.setmOnSelectItemListener(new CustomAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(AppBean appBean, int sleectIndex) {
onSelectCustomApp(appBean,sleectIndex);
// switch (mCategory){
// case VIDEO_CATEGORY:
// break;
// case MRECOMMEND_CATEGORY:
// break;
// case MUSIC_CATEGORY:
// break;
// case LOCAL_CATEGORY:
// break;
// case APPS_CATEGORY:
// break;
// }
// if(shortAppInfoBean.getCategory()==AppManager.CATEGORY_VIDEO){
// shortAppInfoBean.setCategory(AppManager.CATEGORY_MYAPPS);
// }else {
// shortAppInfoBean.setCategory(AppManager.CATEGORY_MYAPPS);
// }
// selectAppinfoToCategory(shortAppInfoBean,mCategory);
}
});
}
StaggeredGridLayoutManager customLayoutManager = new StaggeredGridLayoutManager(8, StaggeredGridLayoutManager.VERTICAL);
grid_coustom_apps.setLayoutManager(customLayoutManager);
grid_coustom_apps.setAdapter(mCustomAppAdapter);
grid_coustom_apps.addOnScrollListener(new RecyclerView.OnScrollListener() {
int childViewPosition=0;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 找到目标位置(例如第一个可见项)
View childView = recyclerView.getFocusedChild();
childViewPosition= recyclerView.getChildAdapterPosition(childView);
LogUtils.loge("childView|childViewPosition==>"+childViewPosition);
if(childViewPosition==-1){ //当焦点错乱是,强制修正找到目标位置(例如第一个可见项)
int[] rows=new int[8];
((StaggeredGridLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPositions(rows);
View targetView = recyclerView.findViewHolderForAdapterPosition(rows[0]).itemView;
targetView.post(() -> targetView.requestFocus());
}
}
}
});
loadCustomAppList();
gv_category_apps.setmFocusOnBoundaryListener(new CustomRecyclerViewer.FocusOnBoundaryListener() {
@Override
public void onFocusBoundary(View lastFocusChild, int direction) {
LogUtils.loge("onFocusBoundary:===="+direction);
if( direction==View.FOCUS_RIGHT){
toNextPage();
}else if(direction==View.FOCUS_LEFT){
toPreviousPage();
}
}
});
}
protected void loadAppInfoByCategory(int category){
if(mCategoryAppPresenter==null){
mCategoryAppPresenter = new CategoryAppPresenter(getActivity(),this);
}
mCategoryAppPresenter.loadAppByCategory(category);
}
protected abstract void toNextPage();
protected abstract void toPreviousPage();
protected void selectAppinfoToCategory(AppBean appBean,int Category){
AppManager.getInstance().selectAppByCategory(appBean,Category);
}
protected void setTabType(int tabType){
switch (tabType){
case VIDEO_CATEGORY:
img_tab_video.setSelected(true);
break;
case RECOMMEND_CATEGORY:
img_tab_recommend.setSelected(true);
break;
case APPS_CATEGORY:
img_tab_apps.setSelected(true);
break;
case MUSIC_CATEGORY:
img_tab_music.setSelected(true);
break;
case LOCAL_CATEGORY:
img_tab_local.setSelected(true);
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
LogUtils.loge("onKeyDown==>"+keyCode);
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if(isShowCustomApp()){
dismissCustomApp();
}else {
return false;
}
return true;
}
return false;
}
@Override
public void onResult(Object data) {
}
@Override
public void onExceptionFailure(String message) {
LogUtils.loge("loadAppInfoByCategory message:"+message);
}
@Override
public void onViewFailureString(int code, String message) {
}
@Override
public void onServerFailure(int code, String message) {
}
protected void showCustomApps(){
cuttentModel = MODEL_CUSTOM;
LogUtils.loge("coustom_view.getHeight():"+coustom_view.getLayoutParams().height);
loadCustomAppList();
coustom_view.setVisibility(View.VISIBLE);
TranslateAnimation exitTransAnim = new TranslateAnimation(0.0f, 0.0f,(float)(0 - coustom_view.getLayoutParams().height),0.0f);
exitTransAnim.setDuration(300);
exitTransAnim.setFillAfter(true);
coustom_view.startAnimation(exitTransAnim);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, 0.0f,0.0f, coustom_view.getLayoutParams().height);
translateAnimation.setDuration(300);
translateAnimation.setFillAfter(true);
content_view.startAnimation(translateAnimation);
handler.postDelayed(new Runnable() {
@Override
public void run() {
coustom_view.requestFocus();
}
},800);
}
private void dismissCustomApp(){
cuttentModel = MODEL_NORMAL;
LogUtils.loge("coustom_view.getHeight():"+coustom_view.getLayoutParams().height);
TranslateAnimation exitTransAnim = new TranslateAnimation(0.0f, 0.0f, 0,(float)(0 - coustom_view.getLayoutParams().height));
exitTransAnim.setDuration(300);
exitTransAnim.setFillAfter(true);
coustom_view.startAnimation(exitTransAnim);
coustom_view.setVisibility(View.GONE);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, 0.0f,coustom_view.getLayoutParams().height,0.0f);
translateAnimation.setDuration(300);
translateAnimation.setFillAfter(true);
content_view.startAnimation(translateAnimation);
refreshUi();
}
protected abstract void refreshUi();
protected boolean isShowCustomApp(){
return cuttentModel==MODEL_NORMAL?false:true;
}
protected void loadCustomAppList(){
runUiThread(new Runnable() {
@Override
public void run() {
List<AppBean> shortcutInfoBeanList = AppManager.getInstance().getmyAppByCategory();
if(shortcutInfoBeanList!=null) {
for (AppBean appBean:shortcutInfoBeanList){
if(checkcollectApp(appBean)){
LogUtils.loge("app is collect:"+appBean.getPackageName());
appBean.setSelect(1);
}else {
LogUtils.loge("app is not collect:"+appBean.getPackageName());
appBean.setSelect(0);
}
}
LogUtils.loge("data size is "+shortcutInfoBeanList.size());
mCustomAppAdapter.addDatas(shortcutInfoBeanList);
}else {
LogUtils.loge("no data");
}
}
});
}
protected abstract void onSelectCustomApp(AppBean appBean,int index);
protected boolean checkcollectApp(AppBean appBean){
if(collectAppMap.get(appBean.getPackageName())!=null){
return true;
}
return false;
};
@Override
public void onResumeFragment(MessageEvent event) {
switch (event.msgType){
case 0: //删除应用
String packageName = (String) event.objectBean;
collectAppMap.remove(packageName);
break;
case 1:// 添加应用
break;
}
}
@Override
public void onPause() {
super.onPause();
if(isShowCustomApp()) {
dismissCustomApp();
}
}
}

View File

@@ -0,0 +1,122 @@
package com.ik.mboxlauncher.ui.fragment;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import androidx.recyclerview.widget.GridLayoutManager;
import com.android.database.lib.AppBean;
import com.android.database.lib.LocalAppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.util.IntentUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.Launcher;
import com.ik.mboxlauncher.ui.adapter.LocalAppAdapter;
import java.util.List;
public class LocalFragment extends CategoryFragment {
public static final String ACTION="com.ik.mboxlauncher.ui.fragment.LocalFragment";
private LocalAppAdapter mLocalAppAdapter =null;
@Override
protected void initView(View view) {
mCategory=AppManager.CATEGORY_LOCAL;
super.initView(view);
img_logo.setImageResource(R.drawable.local);
tv_title.setText(R.string.str_local);
setTabType(LOCAL_CATEGORY);
if(mLocalAppAdapter==null){
mLocalAppAdapter = new LocalAppAdapter(getActivity(),AppManager.CATEGORY_LOCAL);
mLocalAppAdapter.setmOnSelectItemListener(new LocalAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(LocalAppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("open app, package is "+shortAppInfoBean.getPackageName());
IntentUtil.startApp(getActivity(),shortAppInfoBean.getPackageName(),getResources().getString(R.string.app_not_exist));
}
}
});
}
GridLayoutManager customLayoutManager = new GridLayoutManager(view.getContext(), 6);
gv_category_apps.setLayoutManager(customLayoutManager);
gv_category_apps.setAdapter(mLocalAppAdapter);
}
@Override
public void onResult(Object data) {
if(data!=null){
collectAppMap.clear();
List<LocalAppBean> appBeanList = (List<LocalAppBean>) data;
for (LocalAppBean lcalAppBean:appBeanList){
LogUtils.loge("app is collect"+lcalAppBean.getPackageName());
collectAppMap.put(lcalAppBean.getPackageName(),lcalAppBean.getPackageName());
}
appBeanList.add(new LocalAppBean());
mLocalAppAdapter.addDatas(appBeanList);
}
super.onResult(data);
}
@Override
protected void refreshUi() {
loadAppInfoByCategory(AppManager.CATEGORY_LOCAL);
}
@Override
protected void onSelectCustomApp(AppBean appBean,int index) {
if(appBean.getSelect()==0){
appBean.setSelect(1);
collectAppMap.put(appBean.getPackageName(),appBean.getPackageName());
}else {
appBean.setSelect(0);
collectAppMap.remove(appBean.getPackageName());
}
AppManager.getInstance().selectAppByCategory(appBean,AppManager.CATEGORY_LOCAL);
mCustomAppAdapter.notifyItemChanged(index);
}
@Override
protected void initData() {
loadAppInfoByCategory(AppManager.CATEGORY_LOCAL);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
@Override
protected void toNextPage() {
}
@Override
protected void toPreviousPage() {
doneEvents(new MessageEvent(MusicFragment.ACTION));
}
@Override
public void onResumeFragment(MessageEvent event) {
super.onResumeFragment(event);
loadAppInfoByCategory(AppManager.CATEGORY_LOCAL);//重新加载数据
}
}

View File

@@ -0,0 +1,441 @@
package com.ik.mboxlauncher.ui.fragment;
import android.annotation.SuppressLint;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.GridView;
import androidx.media3.common.Player;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.android.database.lib.AdsInfoBean;
import com.android.database.lib.AppBean;
import com.android.database.lib.ShortAppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.ADManager;
import com.android.nebulasdk.AppManager;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.android.util.PakageInstallUtil;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.ADSWindowManager;
import com.ik.mboxlauncher.ui.adapter.CustomAppAdapter;
import com.ik.mboxlauncher.ui.adapter.StatusAdapter;
import com.ik.mboxlauncher.ui.adapter.ShortAppInfoAdapter;
import com.ik.mboxlauncher.ui.base.BaseFragment;
import com.ik.mboxlauncher.ui.base.StatusLoader;
import com.ik.mboxlauncher.view.MultiView;
import com.ik.mboxlauncher.view.TimeTextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 主界面
*/
public class MainFragment extends BaseFragment implements ShortAppInfoAdapter.OnSelectItemListener {
public static final String TAG="com.ik.mboxlauncher.ui.fragment.MainFragment";
private MultiView layout_video,layout_recommend,layout_music,layout_app,layout_local,layout_setting;
private RecyclerView gv_shortcut,grid_coustom_apps;
private StatusLoader mStatusLoader;
private ShortAppInfoAdapter mShortAppInfoAdapter=null;
private CustomAppAdapter mCustomAppAdapter=null;
private StatusAdapter ad =null;
private GridView lv_status;
private TimeTextView tx_time;
private View content_view,coustom_view;
private MultiView[] multiViewArray = new MultiView[6];
@Override
protected int getLayoutResourceId() {
return R.layout.main;
}
@Override
protected void initView(View view) {
mStatusLoader = new StatusLoader(getActivity());
layout_video = view.findViewById(R.id.layout_video);
layout_video.setOnClickListener(onClickListener);
multiViewArray[0]=layout_video;
layout_recommend = view.findViewById(R.id.layout_recommend);
layout_recommend.setOnClickListener(onClickListener);
multiViewArray[1]=layout_recommend;
layout_music = view.findViewById(R.id.layout_music);
layout_music.setOnClickListener(onClickListener);
multiViewArray[2]=layout_music;
// layout_app = view.findViewById(R.id.layout_app);
// layout_app.setOnClickListener(onClickListener);
// multiViewArray[3]=layout_app;
// layout_local = view.findViewById(R.id.layout_local);
// layout_local.setOnClickListener(onClickListener);
multiViewArray[4]=layout_local;
layout_setting = view.findViewById(R.id.layout_setting);
layout_setting.setOnClickListener(onClickListener);
multiViewArray[5]=layout_setting;
gv_shortcut = view.findViewById(R.id.gv_shortcut);
lv_status = view.findViewById(R.id.list_status);
tx_time = view.findViewById(R.id.tx_time);
grid_coustom_apps = view.findViewById(R.id.grid_coustom_apps);
content_view = view.findViewById(R.id.content_view);
coustom_view= view.findViewById(R.id.coustom_view);
if(mShortAppInfoAdapter==null){
mShortAppInfoAdapter = new ShortAppInfoAdapter(getActivity());
mShortAppInfoAdapter.setmOnSelectItemListener(this);
}
if(mCustomAppAdapter==null){
mCustomAppAdapter = new CustomAppAdapter(getActivity(),AppManager.CATEGORY_SHORT);
mCustomAppAdapter.setmOnSelectItemListener(new CustomAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(AppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("open app, package is "+shortAppInfoBean.getPackageName());
if(shortAppInfoBean.getSelect()==0){
shortAppInfoBean.setSelect(1);
}else {
shortAppInfoBean.setSelect(0);
}
selectAppByCategory(shortAppInfoBean,AppManager.CATEGORY_SHORT);
mCustomAppAdapter.notifyDataSetChanged();
}
}
});
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
gv_shortcut.setLayoutManager(layoutManager);
gv_shortcut.setAdapter(mShortAppInfoAdapter);
StaggeredGridLayoutManager customLayoutManager = new StaggeredGridLayoutManager(9, StaggeredGridLayoutManager.VERTICAL);
grid_coustom_apps.setLayoutManager(customLayoutManager);
grid_coustom_apps.setAdapter(mCustomAppAdapter);
ADSWindowManager.init(getActivity());
bindAdsWindowMultiView();
}
@Override
protected void initData() {
tx_time.starTimeUi();
displayStatus();
loadShortAppList();
setImageViewData();
ADSWindowManager.getInstance().startVideo();
}
@SuppressLint("UnsafeOptInUsageError")
private void setImageViewData(){
List<AdsInfoBean> adInfoList = ADManager.getInstance().getAllADInfoList();
for (AdsInfoBean adInfo:adInfoList ) {
if (adInfo != null) {
MultiView multiView = multiViewArray[adInfo.getId()];
if (adInfo.getAppUrl() != null && adInfo.getInfo() != null) {
if (PakageInstallUtil.checkAppInstall(getActivity(), adInfo.getInfo(), adInfo.getAppVersion())) { //已安装了以后才可以显示图片
multiView.onImageRestart(adInfo.getAdUri());
}
}
}
}
}
private void loadShortAppList(){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
List<ShortAppBean> shortcutInfoBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
LogUtils.loge("显示的recycleView"+ GsonUtil.GsonString(shortcutInfoBeanList));
// 创建过滤后的列表
List<ShortAppBean> filteredList = new ArrayList<>();
String selfPackageName = getActivity().getPackageName();
for (ShortAppBean appBean : shortcutInfoBeanList) {
// 跳过自身应用
if (appBean.getPackageName().equals(selfPackageName) || appBean.getPackageName().equals("com.android.traceur")) {
LogUtils.loge("排除自己和com.android.traceur:" + appBean.getPackageName());
continue; // 不添加到过滤列表
}
// 添加非自身应用
filteredList.add(appBean);
}
mShortAppInfoAdapter.addDatas(filteredList);
}
});
}
// private void loadShortAppList(){
//
// runUiThread(new Runnable() {
// @Override
// public void run() {
// List<ShortAppBean> shortcutInfoBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
// mShortAppInfoAdapter.addDatas(shortcutInfoBeanList);
// }
// });
//
// }
// private void loadCustomAppList(){
//
// runUiThread(new Runnable() {
// @Override
// public void run() {
// List<AppBean> shortcutInfoBeanList = AppManager.getInstance().getmyAppByCategory();
// sortAppList(shortcutInfoBeanList);
// if(shortcutInfoBeanList!=null) {
// mCustomAppAdapter.addDatas((List<AppBean>)shortcutInfoBeanList);
// }else {
// LogUtils.loge("no data");
// }
// }
// });
//
// }
private void loadCustomAppList(){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
List<AppBean> shortcutInfoBeanList = AppManager.getInstance().getmyAppByCategory();
LogUtils.loge("myapp "+shortcutInfoBeanList.size());
List<AppBean> filteredList = new ArrayList<>();
String selfPackageName = getActivity().getPackageName();
for (AppBean appBean : shortcutInfoBeanList) {
// 跳过自身应用
if (appBean.getPackageName().equals(selfPackageName) || appBean.getPackageName().equals("com.android.traceur")) {
LogUtils.loge("排除自己和com.android.traceur:" + appBean.getPackageName());
continue; // 不添加到过滤列表
}
// 添加非自身应用
filteredList.add(appBean);
}
sortAppList(filteredList);
mCustomAppAdapter.addDatas(filteredList);
}
});
}
private void sortAppList( List<AppBean> shortcutInfoBeanList){
List<ShortAppBean> shortAppBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
Map<String,ShortAppBean> tmpMapData = new HashMap<>();
for (ShortAppBean shortAppBean:shortAppBeanList){
tmpMapData.put(shortAppBean.getPackageName(),shortAppBean);
}
for (int i=0;i<shortcutInfoBeanList.size();i++){
AppBean appBean = shortcutInfoBeanList.get(i);
if(tmpMapData.get(appBean.getPackageName())!=null){
appBean.setSelect(1);
}else {
appBean.setSelect(0);
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_DPAD_UP:
LogUtils.loge("====="+isShowCustomApp()+"|"+grid_coustom_apps.hasFocus()+"|"+grid_coustom_apps.findFocus());
if(isShowCustomApp()&&!grid_coustom_apps.hasFocus()){
dismissCustomApp();
}else {
return false;
}
return true;
}
return false;
}
@Override
public void onResumeFragment(MessageEvent event) {
LogUtils.loge("onResumeFragment: refresh ui");
if(MessageEvent.ACTION_UPADATE_DATA_SOURCE.equals(event.action)) {
bindAdsWindowMultiView();
ADSWindowManager.getInstance().startVideo();
setImageViewData();
}else if(MessageEvent.ACTION_UPADATE_MEDIA_STATUS.equals(event.action)){
displayStatus();
}
}
private void displayStatus() {
runUiThread(new Runnable() {
@Override
public void run() {
List<ArrayMap<String, Object>> datas = mStatusLoader.getStatusData();
if(ad==null){
ad = new StatusAdapter(getActivity(), datas, R.layout.homelist_item,
new String[] {StatusLoader.ICON},
new int[] {R.id.item_type, 0, 0});
lv_status.setAdapter(ad);
}else {
ad.addDatas(datas);
}
}
});
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ADSWindowManager.getInstance().stopVideo();
if(v.getId()==R.id.layout_video){
LogUtils.loge("go to video");
doneEvents(new MessageEvent(VideoFragment.ACTION));
}else if(v.getId()==R.id.layout_recommend){
LogUtils.loge("go to recommend");
doneEvents(new MessageEvent(RecommendFragment.ACTION));
}else if(v.getId()==R.id.layout_music){
LogUtils.loge("go to music");
doneEvents(new MessageEvent(MusicFragment.ACTION));
}
// else if(v.getId()==R.id.layout_app){
// LogUtils.loge("go to app");
// doneEvents(new MessageEvent(AppsFragment.ACTION));
// }else if(v.getId()==R.id.layout_local){
// LogUtils.loge("go to local");
// doneEvents(new MessageEvent(LocalFragment.ACTION));
// }
else if(v.getId()==R.id.layout_setting){
LogUtils.loge("go to setting");
doneEvents(new MessageEvent("com.android.tv.system.settings"));
}
}
};
private void showCustomApps(){
cuttentModel = MODEL_CUSTOM;
LogUtils.loge("coustom_view.getHeight():"+coustom_view.getLayoutParams().height);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, 0.0f,0.0f, (float)(0 - coustom_view.getLayoutParams().height));
translateAnimation.setDuration(300);
translateAnimation.setFillAfter(true);
content_view.startAnimation(translateAnimation);
coustom_view.setVisibility(View.VISIBLE);
TranslateAnimation exitTransAnim = new TranslateAnimation(0.0f, 0.0f,coustom_view.getY()+coustom_view.getLayoutParams().height, 0);
exitTransAnim.setDuration(300);
translateAnimation.setFillAfter(true);
coustom_view.startAnimation(exitTransAnim);
loadCustomAppList();
coustom_view.requestFocus();
}
private void dismissCustomApp(){
cuttentModel = MODEL_NORMAL;
LogUtils.loge("coustom_view.getHeight():"+coustom_view.getLayoutParams().height);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, 0.0f,(float)(0 - coustom_view.getLayoutParams().height),0.0f);
translateAnimation.setDuration(300);
translateAnimation.setFillAfter(true);
content_view.startAnimation(translateAnimation);
TranslateAnimation exitTransAnim = new TranslateAnimation(0.0f, 0.0f, 0,coustom_view.getY()+coustom_view.getLayoutParams().height);
exitTransAnim.setDuration(300);
translateAnimation.setFillAfter(true);
coustom_view.startAnimation(exitTransAnim);
coustom_view.setVisibility(View.GONE);
loadShortAppList();
}
private boolean isShowCustomApp(){
return cuttentModel==MODEL_NORMAL?false:true;
}
@Override
public void onSelectItem(ShortAppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
LogUtils.loge("open app custom view");
if(!isShowCustomApp()){
showCustomApps();
}
}else {
LogUtils.loge("open app package name is "+shortAppInfoBean.getPackageName());
}
}
protected void selectAppByCategory(AppBean appBean,int Category){
AppManager.getInstance().selectAppByCategory(appBean,Category);
}
Player.Listener mediaListener = new Player.Listener() {
@Override
public void onPlaybackStateChanged(int playbackState) {
LogUtils.loge("onPlaybackStateChanged:"+playbackState);
if(playbackState == Player.STATE_ENDED){
}
}
};
/***
* 创建有资源可播放的广告窗口
* @return
*/
private void bindAdsWindowMultiView(){
List<AdsInfoBean> adsInfoBeanList= ADManager.getInstance().getADInfoListByadType(ADManager.ADTYPE_VIDEO);
List<MultiView> multiViewArrayList = new ArrayList<>();
for (int i=0;i<adsInfoBeanList.size();i++){
AdsInfoBean mAdsInfoBean = adsInfoBeanList.get(i);
multiViewArrayList.add(multiViewArray[mAdsInfoBean.getId()]);
}
ADSWindowManager.getInstance().bindSourceData(multiViewArrayList,adsInfoBeanList);
}
}

View File

@@ -0,0 +1,126 @@
package com.ik.mboxlauncher.ui.fragment;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import androidx.recyclerview.widget.GridLayoutManager;
import com.android.database.lib.AppBean;
import com.android.database.lib.MusicAppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.util.IntentUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.adapter.MusicAppAdapter;
import java.util.List;
public class MusicFragment extends CategoryFragment {
public static final String ACTION="com.ik.mboxlauncher.ui.fragment.MusicFragment";
private MusicAppAdapter mMusicAppAdapter;
@Override
protected void initView(View view) {
super.initView(view);
img_logo.setImageResource(R.drawable.music);
tv_title.setText(R.string.str_music);
setTabType(MUSIC_CATEGORY);
if(mMusicAppAdapter==null){
mMusicAppAdapter = new MusicAppAdapter(getActivity(),AppManager.CATEGORY_MUSIC);
mMusicAppAdapter.setmOnSelectItemListener(new MusicAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(MusicAppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("open app, package is "+shortAppInfoBean.getPackageName());
IntentUtil.startApp(getActivity(),shortAppInfoBean.getPackageName(),getResources().getString(R.string.app_not_exist));
}
}
});
}
GridLayoutManager customLayoutManager = new GridLayoutManager(view.getContext(), 6);
gv_category_apps.setLayoutManager(customLayoutManager);
gv_category_apps.setAdapter(mMusicAppAdapter);
}
@Override
public void onResult(Object data) {
if(data!=null){
collectAppMap.clear();
List<MusicAppBean> appBeanList = (List<MusicAppBean>) data;
for (MusicAppBean musicAppBean:appBeanList){
LogUtils.loge("app is collect"+musicAppBean.getPackageName());
collectAppMap.put(musicAppBean.getPackageName(),musicAppBean.getPackageName());
}
appBeanList.add(new MusicAppBean());
mMusicAppAdapter.addDatas(appBeanList);
}
super.onResult(data);
}
@Override
protected void refreshUi() {
LogUtils.loge("refreshUi===>");
loadAppInfoByCategory(AppManager.CATEGORY_MUSIC);
}
@Override
protected void onSelectCustomApp(AppBean appBean,int index) {
if(appBean.getSelect()==0){
appBean.setSelect(1);
collectAppMap.put(appBean.getPackageName(),appBean.getPackageName());
}else {
appBean.setSelect(0);
collectAppMap.remove(appBean.getPackageName());
}
AppManager.getInstance().selectAppByCategory(appBean,AppManager.CATEGORY_MUSIC);
mCustomAppAdapter.notifyItemChanged(index);
}
@Override
protected void initData() {
loadAppInfoByCategory(AppManager.CATEGORY_MUSIC);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
LogUtils.loge("onKeyDown==>"+keyCode);
return super.onKeyDown(keyCode, event);
}
@Override
protected void toNextPage() {
doneEvents(new MessageEvent(LocalFragment.ACTION));
}
@Override
protected void toPreviousPage() {
doneEvents(new MessageEvent(AppsFragment.ACTION));
}
@Override
public void onResumeFragment(MessageEvent event) {
super.onResumeFragment(event);
loadAppInfoByCategory(AppManager.CATEGORY_MUSIC);//重新加载数据
}
}

View File

@@ -0,0 +1,121 @@
package com.ik.mboxlauncher.ui.fragment;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import androidx.recyclerview.widget.GridLayoutManager;
import com.android.database.lib.AppBean;
import com.android.database.lib.RecommendAppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.util.IntentUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.adapter.RecommendAppAdapter;
import java.util.List;
public class RecommendFragment extends CategoryFragment {
public static final String ACTION="com.ik.mboxlauncher.ui.fragment.RecommendFragment";
private RecommendAppAdapter mRecommendAppAdapter;
@Override
protected void initView(View view) {
mCategory=AppManager.CATEGORY_RECOMMEND;
super.initView(view);
img_logo.setImageResource(R.drawable.recommend);
tv_title.setText(R.string.str_recommend);
setTabType(RECOMMEND_CATEGORY);
if(mRecommendAppAdapter==null){
mRecommendAppAdapter = new RecommendAppAdapter(getActivity(),AppManager.CATEGORY_RECOMMEND);
mRecommendAppAdapter.setmOnSelectItemListener(new RecommendAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(RecommendAppBean shortAppInfoBean, int sleectIndex) {
LogUtils.loge("sleectIndex|getItemType==>"+sleectIndex+"|"+shortAppInfoBean.getItemType());
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("open app, package is "+shortAppInfoBean.getPackageName());
IntentUtil.startApp(getActivity(),shortAppInfoBean.getPackageName(),getResources().getString(R.string.app_not_exist));
}
}
});
}
GridLayoutManager customLayoutManager = new GridLayoutManager(view.getContext(), 6);
gv_category_apps.setLayoutManager(customLayoutManager);
gv_category_apps.setAdapter(mRecommendAppAdapter);
}
@Override
public void onResult(Object data) {
if(data!=null){
collectAppMap.clear();
List<RecommendAppBean> appBeanList = (List<RecommendAppBean>) data;
for (RecommendAppBean recommendAppBean:appBeanList){
LogUtils.loge("app is collect"+recommendAppBean.getPackageName());
collectAppMap.put(recommendAppBean.getPackageName(),recommendAppBean.getPackageName());
}
appBeanList.add(new RecommendAppBean());
mRecommendAppAdapter.addDatas(appBeanList);
}
super.onResult(data);
}
@Override
protected void refreshUi() {
LogUtils.loge("refreshUi===>");
loadAppInfoByCategory(AppManager.CATEGORY_RECOMMEND);
}
@Override
protected void onSelectCustomApp(AppBean appBean,int index) {
if(appBean.getSelect()==0){
appBean.setSelect(1);
collectAppMap.put(appBean.getPackageName(),appBean.getPackageName());
}else {
appBean.setSelect(0);
collectAppMap.remove(appBean.getPackageName());
}
AppManager.getInstance().selectAppByCategory(appBean,AppManager.CATEGORY_RECOMMEND);
mCustomAppAdapter.notifyItemChanged(index);
}
@Override
protected void initData() {
loadAppInfoByCategory(AppManager.CATEGORY_RECOMMEND);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
@Override
protected void toNextPage() {
doneEvents(new MessageEvent(AppsFragment.ACTION));
}
@Override
protected void toPreviousPage() {
doneEvents(new MessageEvent(VideoFragment.ACTION));
}
@Override
public void onResumeFragment(MessageEvent event) {
super.onResumeFragment(event);
loadAppInfoByCategory(AppManager.CATEGORY_RECOMMEND);//重新加载数据
}
}

View File

@@ -0,0 +1,124 @@
package com.ik.mboxlauncher.ui.fragment;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import androidx.recyclerview.widget.GridLayoutManager;
import com.android.database.lib.AppBean;
import com.android.database.lib.VideoAppBean;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.AppManager;
import com.android.util.IntentUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import com.ik.mboxlauncher.ui.adapter.VideoAppAdapter;
import java.util.List;
public class VideoFragment extends CategoryFragment {
public static final String ACTION="com.ik.mboxlauncher.ui.fragment.VideoFragment";
private VideoAppAdapter mVideoAppAdapter = null;
@Override
protected void initView(View view) {
mCategory=AppManager.CATEGORY_VIDEO;
super.initView(view);
img_logo.setImageResource(R.drawable.video);
tv_title.setText(R.string.str_video);
setTabType(VIDEO_CATEGORY);
if(mVideoAppAdapter==null){
mVideoAppAdapter = new VideoAppAdapter(getActivity(),AppManager.CATEGORY_VIDEO);
mVideoAppAdapter.setmOnSelectItemListener(new VideoAppAdapter.OnSelectItemListener() {
@Override
public void onSelectItem(VideoAppBean shortAppInfoBean, int sleectIndex) {
if(shortAppInfoBean.getItemType()==0){
if(!isShowCustomApp()) {
showCustomApps();
}
}else {
LogUtils.loge("open app, package is "+shortAppInfoBean.getPackageName());
IntentUtil.startApp(getActivity(),shortAppInfoBean.getPackageName(),getResources().getString(R.string.app_not_exist));
}
}
});
}
GridLayoutManager layoutManager = new GridLayoutManager(view.getContext(), 6);
gv_category_apps.setLayoutManager(layoutManager);
gv_category_apps.setAdapter(mVideoAppAdapter);
}
@Override
public void onResult(Object data) {
if(data!=null){
collectAppMap.clear();
List<VideoAppBean> appBeanList = (List<VideoAppBean>) data;
for (VideoAppBean videoAppBean:appBeanList){
LogUtils.loge("app is collect"+videoAppBean.getPackageName());
collectAppMap.put(videoAppBean.getPackageName(),videoAppBean.getPackageName());
}
appBeanList.add(new VideoAppBean());
mVideoAppAdapter.addDatas(appBeanList);
}
super.onResult(data);
}
@Override
protected void refreshUi() {
loadAppInfoByCategory(AppManager.CATEGORY_VIDEO);
}
@Override
protected void onSelectCustomApp(AppBean appBean,int index) {
if(appBean.getSelect()==0){
appBean.setSelect(1);
collectAppMap.put(appBean.getPackageName(),appBean.getPackageName());
}else {
appBean.setSelect(0);
collectAppMap.remove(appBean.getPackageName());
}
AppManager.getInstance().selectAppByCategory(appBean,AppManager.CATEGORY_VIDEO);
mCustomAppAdapter.notifyItemChanged(index);
}
@Override
protected void initData() {
loadAppInfoByCategory(AppManager.CATEGORY_VIDEO);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
@Override
protected void toNextPage() {
doneEvents(new MessageEvent(RecommendFragment.ACTION));
}
@Override
protected void toPreviousPage() {
}
@Override
public void onResumeFragment(MessageEvent event) {
super.onResumeFragment(event);
loadAppInfoByCategory(AppManager.CATEGORY_VIDEO);//重新加载数据
}
}

View File

@@ -0,0 +1,484 @@
package com.ik.mboxlauncher.view;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Outline;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.Player;
import com.android.util.LogUtils;
import com.bumptech.glide.Glide;
import com.ik.mboxlauncher.R;
import com.seraphic.ad.AdPlayManager;
import com.seraphic.ad.AdStateListener;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class AdMultiView extends MultiView {
private Context mContext;
private View mView;
private ImageView img_view;
private TextView tx_view;
private long animDuration = 50;
private View mMultiInsideLayout;
private ViewGroup mAdRootView;
private AdPlayManager mAdPlayManager;
private ViewGroup mFullRootView;
private boolean isFullAdShow;
private int mWidth = 0;
private int mHeight = 0;
private int oldMarginstart=0;
private int oldMargintop=0;
private int mAdState = -1;
public AdMultiView(@NonNull Context context) {
super(context);
}
public AdMultiView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdMultiView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public AdMultiView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void initView(Context context, AttributeSet attrs){
mContext = context;
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.ad_multi_layout,this);
tx_view = mView.findViewById(R.id.tx_view);
mMultiInsideLayout = mView.findViewById(R.id.multi_inside);
mAdRootView = mView.findViewById(R.id.ad_root);
img_view = mView.findViewById(R.id.img_view);
mView.findViewById(R.id.tx_view).setVisibility(View.INVISIBLE);
if(attrs!=null){
TypedArray a= context.getTheme().obtainStyledAttributes(attrs,R.styleable.AdMultiView,0,0);
try {
int titleResId = a.getResourceId(R.styleable.AdMultiView_adMultiViewTitle,-1);
int imageResId = a.getResourceId(R.styleable.AdMultiView_adMultiViewImage,-1);
if(titleResId!=-1){
tx_view.setText(titleResId);
tx_view.setVisibility(View.VISIBLE);
} else {
tx_view.setVisibility(View.INVISIBLE);
}
if(imageResId!=-1){
img_view.setImageResource(imageResId);
}
}catch (Exception e){
e.printStackTrace();
}
}
mMultiInsideLayout.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(4, 4, view.getWidth()-4, view.getHeight()-4, 20);
}
});
mMultiInsideLayout.setClipToOutline(true);
hookWebView();
}
@Override
public void onVideoRestart(String uri) {
startAd();
}
@Override
public void onImageRestart(String uri) {
}
@Override
public void onImageRestartLocal(String path) {
if(path==null){
return;
}
img_view.setVisibility(VISIBLE);
File tmpfile= new File(path);
LogUtils.loge("AdMultiView tmpfile===>"+tmpfile.exists());
if(tmpfile.exists()) {
Glide.with(mContext).load(tmpfile).into(img_view);
}
}
@Override
public void loadIamgeRes(String uri, int defaultImageId) {
}
@Override
public void loadDefaultImage(int resId) {
img_view.setImageResource(resId);
}
@Override
public void resetView() {
//TODO 如果无需响应用户操作取消广告(即:广告可点击),删掉下方一行代码
// stopAd();
}
@Override
public void stopView() {
LogUtils.loge( "stopView=====>");
stopAd();
if(mFullRootView.getVisibility()==VISIBLE){
mFullRootView.setVisibility(GONE);
}
}
@Override
public void releaseView() {
}
@Override
public void pauseView() {
}
@Override
public boolean isAdPlaying() {
return mAdState == AdStateListener.AD_PLAYING
|| mAdState == AdStateListener.AD_LOADING
|| mAdState == AdStateListener.AD_LOADED;
}
public void setFullRooView(ViewGroup fullRooView){
mFullRootView = fullRooView;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if(mWidth == 0 || mHeight == 0) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) getLayoutParams();
mWidth = getWidth();
mHeight = getHeight();
oldMarginstart =layoutParams.leftMargin;
oldMargintop =layoutParams.topMargin;
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stopAd();
}
@SuppressLint("SoonBlockedPrivateApi")
private void hookWebView() {
int sdkInt = Build.VERSION.SDK_INT;
try {
Class factoryClass = Class.forName("android.webkit.WebViewFactory");
Field field = factoryClass.getDeclaredField("sProviderInstance");
field.setAccessible(true);
Object sProviderInstance = field.get(null);
if (sProviderInstance != null) {
LogUtils.logi("sProviderInstance isn't null");
return;
}
Method getProviderClassMethod = null;
if (sdkInt > 22) {
getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
} else if (sdkInt == 22) {
getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
} else {
LogUtils.logi("Don't need to Hook WebView");
return;
}
getProviderClassMethod.setAccessible(true);
Class factoryProviderClass = (Class) getProviderClassMethod.invoke(factoryClass);
Class delegateClass = Class.forName("android.webkit.WebViewDelegate");
Constructor delegateConstructor = delegateClass.getDeclaredConstructor();
delegateConstructor.setAccessible(true);
if (sdkInt < 26) { //低于Android O版本
Constructor providerConstructor = factoryProviderClass.getConstructor(delegateClass);
if (providerConstructor != null) {
providerConstructor.setAccessible(true);
sProviderInstance = providerConstructor.newInstance(delegateConstructor.newInstance());
}
} else {
Field chromiumMethodName = factoryClass.getDeclaredField("CHROMIUM_WEBVIEW_FACTORY_METHOD");
chromiumMethodName.setAccessible(true);
String chromiumMethodNameStr = (String) chromiumMethodName.get(null);
if (chromiumMethodNameStr == null) {
chromiumMethodNameStr = "create";
}
Method staticFactory = factoryProviderClass.getMethod(chromiumMethodNameStr, delegateClass);
if (staticFactory != null) {
sProviderInstance = staticFactory.invoke(null, delegateConstructor.newInstance());
}
}
if (sProviderInstance != null) {
field.set("sProviderInstance", sProviderInstance);
LogUtils.logi("can use webview");
} else {
LogUtils.logi("can not use webview");
}
} catch (Exception e) {
}
}
private void startAd(){
if(mAdPlayManager != null){
stopAd();
}
mAdPlayManager = new AdPlayManager(mContext, AdPlayManager.TYPE_WITH_CONTAINER,
0, adstate -> {
if(mMultiViewListener != null) {
int playState = Player.STATE_IDLE;
switch (adstate){
case AdStateListener.AD_LOADING:
playState = Player.STATE_BUFFERING;
break;
case AdStateListener.AD_LOADED:
case AdStateListener.AD_PLAYING:
playState = Player.STATE_READY;
break;
case AdStateListener.AD_ERROR:
playState = adstate;
break;
case AdStateListener.AD_COMPLETE_ALL:
playState = Player.STATE_ENDED;
break;
}
LogUtils.loge("AdMultiView adstate ===>"+adstate);
if((mAdState == -1 || mAdState != adstate) && playState != Player.STATE_IDLE) {
mMultiViewListener.onPlaybackStateChanged(getId(), playState);
}
}
mAdState = adstate;
if(adstate == AdStateListener.AD_COMPLETE_ALL||adstate == AdStateListener.AD_ERROR){
if(isFullAdShow){
isFullAdShow = false;
requestFocus();
}
stopAd();
}
}); //position 必填
mAdPlayManager.setAdFullRootView(mFullRootView);//设置全屏的 ad root
if(isFocused()) {//焦点在当前view时显示back提示
mAdPlayManager.setNeedCancelTips(true);
}
mAdPlayManager.startAd(mAdRootView,0);
}
@Override
public void stopAd() {
LogUtils.loge( "stopAd=====>");
if (mAdPlayManager != null) {
mAdPlayManager.stopAd();
mAdPlayManager = null;
}
}
@Override
public boolean onAdViewClick(){
boolean isNeed = false;
if (mAdPlayManager != null) {
isNeed = mAdPlayManager.onAdViewClick();
}
isFullAdShow = isNeed;
return isNeed;
}
public boolean onAdBackClick(){
boolean isNeed = false;
//NOTE: 如果希望全局按back键取消广告可以移除焦点判断
if (isFocused() && mAdPlayManager != null) {
isNeed = mAdPlayManager.onAdBackClick();
}
return isNeed;
}
private boolean mGainFocus=false;
// @Override
// protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) {
// super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
// mGainFocus = gainFocus;
//
// if (gainFocus) {
// if(mAdPlayManager != null) {
// mAdPlayManager.setNeedCancelTips(true);
// }
// setBackgroundResource(R.drawable.app_item_border);
// setTranslationZ(10);
// setElevation(10);
//
// scaleView(1.05f);
//
//// ScaleAnimation anim = new ScaleAnimation(1f, 1.1f, 1f, 1.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//// anim.setZAdjustment(Animation.ZORDER_TOP);
//// anim.setDuration(animDuration);
//// anim.setFillAfter(true);
//// this.startAnimation(anim);
// this.bringToFront();
// } else {
// if(mAdPlayManager != null) {
// mAdPlayManager.setNeedCancelTips(false);
// }
// setBackgroundResource(R.color.transparent_background);
// setTranslationZ(0);
// setElevation(0);
// scaleView(1.0f);
//// ScaleAnimation anim = new ScaleAnimation(1.1f, 1f, 1.1f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//// anim.setZAdjustment(Animation.ZORDER_TOP);
//// anim.setDuration(animDuration);
//// anim.setFillAfter(true);
//// this.startAnimation(anim);
// }
// }
@Override
protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
// int width = getWidth();
// int height = getHeight();
mGainFocus = gainFocus;
if(gainFocus){
if(mAdPlayManager != null) {
mAdPlayManager.setNeedCancelTips(true);
}
setBackgroundResource(R.drawable.app_item_border);
setTranslationZ(8);
setElevation(8);
ValueAnimator animator = ValueAnimator.ofFloat(1f,1.1f);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(@NonNull ValueAnimator valueAnimator) {
float scale = (float) valueAnimator.getAnimatedValue();
// RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) getLayoutParams();
// layoutParams.height = (int) (height*scale);
// layoutParams.width = (int) (width*scale);
// setLayoutParams(layoutParams);
// setScaleWithLayoutd(scale);
setScaleWithLayoutd(scale);
invalidate();
}
});
animator.setDuration(animDuration);
animator.start();
this.bringToFront();
}else {
if(mAdPlayManager != null) {
mAdPlayManager.setNeedCancelTips(false);
}
setBackgroundResource(R.color.transparent_background);
setTranslationZ(0);
setElevation(0);
ValueAnimator animator = ValueAnimator.ofFloat(1.1f, 1f);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(@NonNull ValueAnimator valueAnimator) {
float scale = (float) valueAnimator.getAnimatedValue();
// RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) getLayoutParams();
// layoutParams.height = (int) (height*scale);
// layoutParams.width = (int) (width*scale);
// if(layoutParams.height < mHeight || layoutParams.width < mWidth){
// layoutParams.height = mHeight;
// layoutParams.width = mWidth;
// }
// setLayoutParams(layoutParams);
// setScaleWithLayoutd(scale);
setScaleWithLayoutd(scale);
invalidate();
}
});
animator.setDuration(animDuration);
animator.start();
}
}
// 缩放方法
public void scaleView(float scale) {
setScaleX(scale);
setScaleY(scale);
setScaleWithLayoutd(scale);
invalidate(); // 可选,通常不需要
}
// 或者如果需要同时改变布局大小
public void setScaleWithLayoutd(float scale) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams();
int newWidth = (int) (mWidth * scale);
int newHeight = (int) (mHeight * scale);
// 调整margin保持中心位置
lp.leftMargin -= (newWidth - lp.width) / 2;
lp.topMargin -= (newHeight - lp.height) / 2;
lp.width = newWidth;
lp.height = newHeight;
setLayoutParams(lp);
}
// public void setScaleWithLayouts(float scale) {
// RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams();
// // 调整margin保持中心位置
// lp.leftMargin -= (mWidth - lp.width) / 2;
// lp.topMargin -= (mWidth - lp.height) / 2;
// lp.width = mWidth;
// lp.height = mWidth;
// setLayoutParams(lp);
// }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
LogUtils.loge("AdMultiView onKeyDown==>"+keyCode);
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if(mGainFocus){
onAdBackClick();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
}

View File

@@ -0,0 +1,138 @@
package com.ik.mboxlauncher.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.android.util.DateUtil;
//时间的textView
@SuppressLint("AppCompatCustomView")
public class CountdownTimeTextView extends TextView {
/***
* 倒计时时间
*/
private static final int COUNTDOWN_TIME=10;
private static int CURRENT_COUNTDOWN_TIME=COUNTDOWN_TIME;
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
setText(CURRENT_COUNTDOWN_TIME+" Second");
break;
case 1:
if(mTextUiCallBack!=null){
mTextUiCallBack.onEndCallback();
}
break;
}
}
};
public CountdownTimeTextView(Context context) {
super(context);
}
public CountdownTimeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CountdownTimeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CountdownTimeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void starTimeUi(TextUiCallBack callBack){
this.mTextUiCallBack = callBack;
if(isRunning==false) {
countdownTimeThread.start();
}
// handler.post(timeRunnable);
}
public void cancelTimeUi(){
isRunning=false;
}
private boolean isRunning=false;
// Runnable timeRunnable = new Runnable() {
// @Override
// public void run() {
//
//
//
// CURRENT_COUNTDOWN_TIME--;
// Log.i("liu","CURRENT_COUNTDOWN_TIME:"+CURRENT_COUNTDOWN_TIME);
// if(CURRENT_COUNTDOWN_TIME<0){
// CURRENT_COUNTDOWN_TIME = COUNTDOWN_TIME;
// if(mTextUiCallBack!=null){
// mTextUiCallBack.onEndCallback();
// }
// }else {
// setText(CURRENT_COUNTDOWN_TIME+" Second");
// handler.postDelayed(this,1000);
// }
//
// }
// };
Thread countdownTimeThread = new Thread(){
@Override
public void run() {
super.run();
isRunning =true;
while (CURRENT_COUNTDOWN_TIME>-1){
if(!isRunning){
break;
}
handler.sendEmptyMessage(0);
try {
sleep(1000*1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
CURRENT_COUNTDOWN_TIME--;
Log.i("liu","CURRENT_COUNTDOWN_TIME:"+CURRENT_COUNTDOWN_TIME);
}
handler.sendEmptyMessage(1);
}
};
private TextUiCallBack mTextUiCallBack;
public TextUiCallBack getmTextUiCallBack() {
return mTextUiCallBack;
}
public void setmTextUiCallBack(TextUiCallBack mTextUiCallBack) {
this.mTextUiCallBack = mTextUiCallBack;
}
public interface TextUiCallBack{
public void onEndCallback();
}
}

View File

@@ -0,0 +1,270 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.google.android.gms.common.util.JsonUtils;
import java.util.ArrayList;
public class CustomRecyclerView extends RecyclerView {
private static final String TAG = CustomRecyclerView.class.getSimpleName();
//是否可以纵向移出
private boolean mCanFocusOutVertical = false;
//是否可以横向移出
private boolean mCanFocusOutHorizontal = true;
//焦点移出recyclerview的事件监听
private FocusLostListener mFocusLostListener;
//焦点移入recyclerview的事件监听
private FocusGainListener mFocusGainListener;
//默认第一次选中第一个位置
private int mCurrentFocusPosition = 0;
public CustomRecyclerView(Context context) {
this(context, null);
}
public CustomRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
setChildrenDrawingOrderEnabled(true);
setItemAnimator(null);
this.setFocusable(true);
addItemDecoration(new ItemDecoration() {
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull State state) {
outRect.left = 1;
outRect.right = 1;
outRect.bottom = 1;
outRect.top = 1;
}
});
}
public boolean isCanFocusOutVertical() {
return mCanFocusOutVertical;
}
public void setCanFocusOutVertical(boolean canFocusOutVertical) {
mCanFocusOutVertical = canFocusOutVertical;
}
public boolean isCanFocusOutHorizontal() {
return mCanFocusOutHorizontal;
}
public void setCanFocusOutHorizontal(boolean canFocusOutHorizontal) {
mCanFocusOutHorizontal = canFocusOutHorizontal;
}
@Override
public View focusSearch(int direction) {
return super.focusSearch(direction);
}
//覆写focusSearch寻焦策略
@Override
public View focusSearch(View focused, int direction) {
View view = super.focusSearch(focused, direction);
if (focused == null) {
return view;
}
if (view != null) {
//该方法返回焦点view所在的父view,如果是在recyclerview之外就会是null.所以根据是否是null,来判断是否是移出了recyclerview
View nextFocusItemView = findContainingItemView(view);
LogUtils.loge("nextFocusItemView===>"+nextFocusItemView);
if (nextFocusItemView == null) {
if (!mCanFocusOutVertical && (direction == View.FOCUS_DOWN || direction == View.FOCUS_UP)) {
//屏蔽焦点纵向移出recyclerview
LogUtils.loge("屏蔽焦点纵向移出recyclerview");
return focused;
}
if (!mCanFocusOutHorizontal && (direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT)) {
//屏蔽焦点横向移出recyclerview
LogUtils.loge("屏蔽焦点横向移出recyclerview");
return focused;
}
LogUtils.loge("移出了recyclerview");
//调用移出的监听
if (mFocusLostListener != null) {
mFocusLostListener.onFocusLost(focused, direction);
}
return view;
}
}
return view;
}
public void setFocusLostListener(FocusLostListener focusLostListener) {
this.mFocusLostListener = focusLostListener;
}
public interface FocusLostListener {
void onFocusLost(View lastFocusChild, int direction);
}
public void setGainFocusListener(FocusGainListener focusListener) {
this.mFocusGainListener = focusListener;
}
public interface FocusGainListener {
void onFocusGain(View child, View focued);
}
@Override
public void requestChildFocus(View child, View focused) {
if (!hasFocus()) {
//recyclerview 子view 重新获取焦点,调用移入焦点的事件监听
if (mFocusGainListener != null) {
mFocusGainListener.onFocusGain(child, focused);
}
}
super.requestChildFocus(child, focused);//执行过super.requestChildFocus之后hasFocus会变成true
mCurrentFocusPosition = getChildViewHolder(child).getAdapterPosition();
}
//实现焦点记忆的关键代码
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
try {
View view = null;
if (this.hasFocus() || mCurrentFocusPosition < 0 || (view = getLayoutManager().findViewByPosition(mCurrentFocusPosition)) == null) {
super.addFocusables(views, direction, focusableMode);
} else if (view.isFocusable()) {
//将当前的view放到Focusable views列表中再次移入焦点时会取到该view,实现焦点记忆功能
views.add(view);
} else {
super.addFocusables(views, direction, focusableMode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 控制当前焦点最后绘制,防止焦点放大后被遮挡
* 原顺序123456789当4是focus时绘制顺序变为123567894
*
* @param childCount
* @param i
* @return
*/
@Override
protected int getChildDrawingOrder(int childCount, int i) {
View focusedChild = getFocusedChild();
if (focusedChild == null) {
return super.getChildDrawingOrder(childCount, i);
} else {
int index = indexOfChild(focusedChild);
// testing!!!!!! MyRecyclerView list log
// Log.i(TAG, " index = " + index + ",i=" + i + ",count=" + childCount);
if (i == childCount - 1) {
return index;
}
if (i < index) {
return i;
}
return i + 1;
}
}
private long mLastKeyDownTime=0;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
// int keyCode = event.getKeyCode();
// if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
// long current = System.currentTimeMillis();
// boolean res;
// if (current - mLastKeyDownTime < 150) {
// res = true;
// } else {
// res = super.onKeyDown(keyCode, event);
// mLastKeyDownTime = current;
// }
// return res;
// }
//
// View focusedView = getFocusedChild(); // 获取当前获得焦点的view
// View nextFocusView;
// try {
// if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
// // 通过findNextFocus获取下一个需要得到焦点的view
// nextFocusView = FocusFinder.getInstance().findNextFocus(this, focusedView, View.FOCUS_DOWN);
// } else {
// // 通过findNextFocus获取下一个需要得到焦点的view
// nextFocusView = FocusFinder.getInstance().findNextFocus(this, focusedView, View.FOCUS_UP);
// }
//
//
// LogUtils.loge("nextFocusView===>"+nextFocusView);
//
// } catch (Exception e) {
// nextFocusView = null;
// }
//
// // 如果获取失败(也就是说需要交给系统来处理焦点, 消耗掉事件,不让系统处理, 并让先前获取焦点的view获取焦点)
// if (nextFocusView == null) {
// focusedView.requestFocus();
// return true;
//
// }
// }
// }
}
return super.dispatchKeyEvent(event);
}
LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(getContext()){
@Override
protected int getHorizontalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
public void scrollToPositionWithOffset(int position){
linearSmoothScroller.setTargetPosition(position);
getLayoutManager().startSmoothScroll(linearSmoothScroller);
}
}

View File

@@ -0,0 +1,290 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.ArrayList;
public class CustomRecyclerViewer extends RecyclerView {
private static final String TAG = CustomRecyclerViewer.class.getSimpleName();
private int offset = 0;
//是否可以纵向移出
private boolean mCanFocusOutVertical = false;
//是否可以横向移出
private boolean mCanFocusOutHorizontal = true;
//焦点移出recyclerview的事件监听
private FocusLostListener mFocusLostListener;
// 移动到边界的监听
private FocusOnBoundaryListener mFocusOnBoundaryListener;
//焦点移入recyclerview的事件监听
private FocusGainListener mFocusGainListener;
//默认第一次选中第一个位置
private int mCurrentFocusPosition = 0;
public CustomRecyclerViewer(Context context) {
this(context, null);
}
public CustomRecyclerViewer(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomRecyclerViewer(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
setChildrenDrawingOrderEnabled(true);
setItemAnimator(null);
this.setFocusable(true);
if(attrs!=null){
TypedArray a= context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomRecyclerViewer,0,0);
try {
offset = a.getDimensionPixelOffset(R.styleable.CustomRecyclerViewer_itemOffsets,0);
}catch (Exception e){
e.printStackTrace();
}
}
addItemDecoration(new ItemDecoration() {
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull State state) {
outRect.left = offset;
outRect.right = offset;
outRect.bottom = offset;
outRect.top = offset;
}
});
}
public boolean isCanFocusOutVertical() {
return mCanFocusOutVertical;
}
public void setCanFocusOutVertical(boolean canFocusOutVertical) {
mCanFocusOutVertical = canFocusOutVertical;
}
public boolean isCanFocusOutHorizontal() {
return mCanFocusOutHorizontal;
}
public void setCanFocusOutHorizontal(boolean canFocusOutHorizontal) {
mCanFocusOutHorizontal = canFocusOutHorizontal;
}
@Override
public View focusSearch(int direction) {
return super.focusSearch(direction);
}
//覆写focusSearch寻焦策略
@Override
public View focusSearch(View focused, int direction) {
View view = super.focusSearch(focused, direction);
LogUtils.loge("view===>"+view+"|"+focused);
if (focused == null) {
return view;
}
if (view != null) {
//该方法返回焦点view所在的父view,如果是在recyclerview之外就会是null.所以根据是否是null,来判断是否是移出了recyclerview
View nextFocusItemView = findContainingItemView(view);
LogUtils.loge("nextFocusItemView===>"+nextFocusItemView);
if (nextFocusItemView == null) {
if (!mCanFocusOutVertical && (direction == View.FOCUS_DOWN || direction == View.FOCUS_UP)) {
//屏蔽焦点纵向移出recyclerview
return focused;
}
if (!mCanFocusOutHorizontal && (direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT)) {
//屏蔽焦点横向移出recyclerview
return focused;
}
//调用移出的监听
if (mFocusLostListener != null) {
mFocusLostListener.onFocusLost(focused, direction);
}
return view;
}
}else {
if(mFocusOnBoundaryListener!=null){
mFocusOnBoundaryListener.onFocusBoundary(view,direction);
}
}
return view;
}
public void setFocusLostListener(FocusLostListener focusLostListener) {
this.mFocusLostListener = focusLostListener;
}
public void setmFocusOnBoundaryListener(FocusOnBoundaryListener mFocusOnBoundaryListener) {
this.mFocusOnBoundaryListener = mFocusOnBoundaryListener;
}
public interface FocusLostListener {
void onFocusLost(View lastFocusChild, int direction);
}
public interface FocusOnBoundaryListener {
void onFocusBoundary(View lastFocusChild, int direction);
}
public void setGainFocusListener(FocusGainListener focusListener) {
this.mFocusGainListener = focusListener;
}
public interface FocusGainListener {
void onFocusGain(View child, View focued);
}
@Override
public void requestChildFocus(View child, View focused) {
if (!hasFocus()) {
//recyclerview 子view 重新获取焦点,调用移入焦点的事件监听
if (mFocusGainListener != null) {
mFocusGainListener.onFocusGain(child, focused);
}
}
super.requestChildFocus(child, focused);//执行过super.requestChildFocus之后hasFocus会变成true
mCurrentFocusPosition = getChildViewHolder(child).getAdapterPosition();
}
//实现焦点记忆的关键代码
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
try {
View view = null;
if (this.hasFocus() || mCurrentFocusPosition < 0 || (view = getLayoutManager().findViewByPosition(mCurrentFocusPosition)) == null) {
super.addFocusables(views, direction, focusableMode);
} else if (view.isFocusable()) {
//将当前的view放到Focusable views列表中再次移入焦点时会取到该view,实现焦点记忆功能
views.add(view);
} else {
super.addFocusables(views, direction, focusableMode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 控制当前焦点最后绘制,防止焦点放大后被遮挡
* 原顺序123456789当4是focus时绘制顺序变为123567894
*
* @param childCount
* @param i
* @return
*/
@Override
protected int getChildDrawingOrder(int childCount, int i) {
View focusedChild = getFocusedChild();
if (focusedChild == null) {
return super.getChildDrawingOrder(childCount, i);
} else {
int index = indexOfChild(focusedChild);
// testing!!!!!! MyRecyclerView list log
// Log.i(TAG, " index = " + index + ",i=" + i + ",count=" + childCount);
if (i == childCount - 1) {
return index;
}
if (i < index) {
return i;
}
return i + 1;
}
}
private long mLastKeyDownTime=0;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
// int keyCode = event.getKeyCode();
// if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
// long current = System.currentTimeMillis();
// boolean res;
// if (current - mLastKeyDownTime < 150) {
// res = true;
// } else {
// res = super.onKeyDown(keyCode, event);
// mLastKeyDownTime = current;
// }
// return res;
// }
//
// View focusedView = getFocusedChild(); // 获取当前获得焦点的view
// View nextFocusView;
// try {
// if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
// // 通过findNextFocus获取下一个需要得到焦点的view
// nextFocusView = FocusFinder.getInstance().findNextFocus(this, focusedView, View.FOCUS_DOWN);
// } else {
// // 通过findNextFocus获取下一个需要得到焦点的view
// nextFocusView = FocusFinder.getInstance().findNextFocus(this, focusedView, View.FOCUS_UP);
// }
//
//
// LogUtils.loge("nextFocusView===>"+nextFocusView);
//
// } catch (Exception e) {
// nextFocusView = null;
// }
//
// // 如果获取失败(也就是说需要交给系统来处理焦点, 消耗掉事件,不让系统处理, 并让先前获取焦点的view获取焦点)
// if (nextFocusView == null) {
// focusedView.requestFocus();
// return true;
//
// }
// }
// }
}
return super.dispatchKeyEvent(event);
}
LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(getContext()){
@Override
protected int getHorizontalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
public void scrollToPositionWithOffset(int position){
linearSmoothScroller.setTargetPosition(position);
getLayoutManager().startSmoothScroll(linearSmoothScroller);
}
}

View File

@@ -0,0 +1,404 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Outline;
import android.graphics.Rect;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.ima.ImaAdsLoader;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.ui.PlayerView;
import com.android.util.LogUtils;
import com.bumptech.glide.Glide;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.ik.mboxlauncher.R;
import java.io.File;
import static android.os.Build.VERSION.SDK_INT;
public class HomeMultiView extends MultiView {
private static String SAMPLE_VIDEO_URL =
"https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
private static String SAMPLE_VIDEO_URL1 =
"https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
// private static final String SAMPLE_VAST_TAG_URL =
// "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/"
// + "single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90"
// + "&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=";
private static final String LOG_TAG = "ImaExoPlayerExample";
private View mView;
private PlayerView player_view;
private ImageView img_view;
private TextView tx_view;
/**广告插件开关*/
private boolean adsSwitch=false;
private Context mContext;
private ExoPlayer player;
private ImaAdsLoader adsLoader;
private int animDuration=50;
private View mMultiInsideLayout;
public HomeMultiView(@NonNull Context context) {
super(context);
}
public HomeMultiView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public HomeMultiView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public HomeMultiView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void initView(Context context, AttributeSet attrs){
mContext = context;
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.multi_layout,this);
mMultiInsideLayout = mView.findViewById(R.id.multi_inside);
player_view = mView.findViewById(R.id.player_view);
img_view = mView.findViewById(R.id.img_view);
tx_view = mView.findViewById(R.id.tx_view);
if(attrs!=null){
TypedArray a= context.getTheme().obtainStyledAttributes(attrs,R.styleable.MultiView,0,0);
try {
int titleResId = a.getResourceId(R.styleable.MultiView_multiViewTitle,-1);
int imageResId = a.getResourceId(R.styleable.MultiView_multiViewImage,-1);
boolean adsSwitch = a.getBoolean(R.styleable.MultiView_adsSwitch,false);
if(titleResId!=-1){
tx_view.setText(titleResId);
tx_view.setVisibility(View.VISIBLE);
} else {
tx_view.setVisibility(View.INVISIBLE);
}
if(imageResId!=-1){
img_view.setImageResource(imageResId);
}
}catch (Exception e){
e.printStackTrace();
}
}
mMultiInsideLayout.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(4, 4, view.getWidth()-4, view.getHeight()-4, 20);
}
});
mMultiInsideLayout.setClipToOutline(true);
}
@UnstableApi private void onRestart(){
if (SDK_INT <= 23 || player == null) {
initializePlayer();
if (player_view != null) {
player_view.onResume();
}
}
}
private AdEvent.AdEventListener buildAdEventListener() {
AdEvent.AdEventListener imaAdEventListener =
event -> {
AdEvent.AdEventType eventType = event.getType();
if (eventType == AdEvent.AdEventType.AD_PROGRESS) {
return;
}
String log = "IMA event: " + eventType;
LogUtils.loge(log);
};
return imaAdEventListener;
}
@Override
public void onVideoRestart(String uri){
LogUtils.loge("onVideoRestart==>"+uri);
player_view.setVisibility(VISIBLE);
img_view.setVisibility(INVISIBLE);
tx_view.setVisibility(INVISIBLE);
if(uri==null){
return;
}
SAMPLE_VIDEO_URL = uri;
if (SDK_INT <= 23 || player == null) {
initializePlayer();
if (player_view != null) {
player_view.onResume();
}
}
}
@Override
public void onImageRestart(String uri){
img_view.setVisibility(VISIBLE);
if(!TextUtils.isEmpty(tx_view.getText())) {
tx_view.setVisibility(VISIBLE);
}
player_view.setVisibility(GONE);
Glide.with(mContext).load(uri).into(img_view);
}
@Override
public void onImageRestartLocal(String path){
LogUtils.loge("onImageRestartLocal==>"+path);
if(path==null){
return;
}
img_view.setVisibility(VISIBLE);
if(!TextUtils.isEmpty(tx_view.getText())) {
tx_view.setVisibility(VISIBLE);
}
stopView();
player_view.setVisibility(INVISIBLE);
File tmpfile= new File(path);
LogUtils.loge("tmpfile===>"+tmpfile.exists());
if(tmpfile.exists()) {
Glide.with(mContext).load(tmpfile).into(img_view);
}
}
private void onStop(){
img_view.setVisibility(VISIBLE);
if(!TextUtils.isEmpty(tx_view.getText())) {
tx_view.setVisibility(VISIBLE);
}
player_view.setVisibility(INVISIBLE);
if (SDK_INT > 23) {
if (player_view != null) {
if(player_view.getPlayer()!=null&&player_view.getPlayer().isPlaying()) {
player_view.onPause();
}
}
releasePlayer();
}
}
@Override
public void loadIamgeRes(String uri,int defaultImageId){
img_view.setVisibility(VISIBLE);
if(!TextUtils.isEmpty(tx_view.getText())) {
tx_view.setVisibility(VISIBLE);
}
player_view.setVisibility(INVISIBLE);
Glide.with(mContext).load(uri).error(defaultImageId).into(img_view);
}
@Override
public void loadDefaultImage(int resId){
img_view.setImageResource(resId);
}
private void releasePlayer() {
if(player==null){
return;
}
adsLoader.setPlayer(null);
player_view.setPlayer(null);
player.release();
player = null;
}
@UnstableApi private void initializePlayer() {
LogUtils.loge("initializePlayer()");
adsLoader =
new ImaAdsLoader.Builder(/* context= */ mContext)
.setAdEventListener(buildAdEventListener())
.build();
// Set up the factory for media sources, passing the ads loader and ad view providers.
DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(mContext);
MediaSource.Factory mediaSourceFactory =
new DefaultMediaSourceFactory(dataSourceFactory)
.setLocalAdInsertionComponents(unusedAdTagUri -> adsLoader, player_view);
// Create an ExoPlayer and set it as the player for content and ads.
player = new ExoPlayer.Builder(mContext).setMediaSourceFactory(mediaSourceFactory).build();
player_view.setPlayer(player);
player_view.setControllerAutoShow(false);
player_view.setFocusable(false);
player_view.setControllerHideOnTouch(true);
// adsLoader.setPlayer(player);
// Create the MediaItem to play, specifying the content URI and ad tag URI.
Uri contentUri = Uri.parse(SAMPLE_VIDEO_URL);
// Uri adTagUri = Uri.parse(SAMPLE_VAST_TAG_URL);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(contentUri)
// .setAdsConfiguration(new MediaItem.AdsConfiguration.Builder(adTagUri).build())
.build();
// Prepare the content and ad to be played with the SimpleExoPlayer.
player.setMediaItem(mediaItem);
player.addListener(listener);
player.prepare();
// Set PlayWhenReady. If true, content and ads will autoplay.
player.setPlayWhenReady(true);
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if(gainFocus){
setBackgroundResource(R.drawable.app_item_border);
setTranslationZ(10);
setElevation(10);
ScaleAnimation anim = new ScaleAnimation(1f, 1.1f, 1f, 1.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setZAdjustment(Animation.ZORDER_TOP);
anim.setDuration(animDuration);
anim.setFillAfter(true);
this.startAnimation(anim);
this.bringToFront();
}else {
setBackgroundResource(R.color.transparent_background);
setTranslationZ(0);
setElevation(0);
ScaleAnimation anim = new ScaleAnimation(1.1f, 1f, 1.1f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setZAdjustment(Animation.ZORDER_TOP);
anim.setDuration(animDuration);
anim.setFillAfter(true);
this.startAnimation(anim);
}
// if(gainFocus){
// ViewCompat.animate(this).scaleX(1.6f).scaleY(1.6f).translationX(1).start();
// }else {
// ViewCompat.animate(this).scaleX(1.0f).scaleY(1.0f).translationX(0).start();
// }
}
Player.Listener listener = new Player.Listener() {
@Override
public void onPlaybackStateChanged(int playbackState) {
LogUtils.loge("onPlaybackStateChanged1111111===>"+playbackState);
if(playbackState==Player.STATE_ENDED||playbackState==Player.STATE_IDLE){
resetView();
}else if(playbackState ==Player.STATE_READY ){
img_view.setVisibility(INVISIBLE);
tx_view.setVisibility(INVISIBLE);
player_view.setVisibility(VISIBLE);
}
if(mMultiViewListener !=null){
mMultiViewListener.onPlaybackStateChanged(getId(),playbackState);
}
}
@Override
public void onPlayerError(PlaybackException error) {
Player.Listener.super.onPlayerError(error);
if(mMultiViewListener !=null){
mMultiViewListener.onPlaybackStateChanged(getId(),0);
}
}
};
@Override
public void resetView(){
img_view.setVisibility(VISIBLE);
if(!TextUtils.isEmpty(tx_view.getText())) {
tx_view.setVisibility(VISIBLE);
}
player_view.setVisibility(INVISIBLE);
onStop();
// if(player!=null) {
// player.stop();
// player.release();
// }
}
@Override
public void stopView(){
if(player!=null&&player.isPlaying()) {
player.stop();
releasePlayer();
}
}
@Override
public void stopAd() {
}
@Override
public void releaseView(){
if(player!=null&&player.isPlaying()) {
player.stop();
releasePlayer();
}
}
@Override
public void pauseView(){
if(player!=null) {
player.pause();
}
}
@Override
public boolean onAdViewClick() {
return false;
}
}

View File

@@ -0,0 +1,272 @@
package com.ik.mboxlauncher.view;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.util.LogUtils;
public class LoadingView extends View {
private int mWidth = 0;
private int mHeight = 0;
//文字X坐标
private float textX = 0f;
//文字Y坐标
private float textY = 0f;
private String text = "Loading";
private Rect textRect = new Rect();
//1文字距离上方的距离
private float textTopMargin = 40f;
private RectF rectF = new RectF();
private float radius = 120f;
//大园弧开始角度
private float mainstartAngle = 180f;
//大圆弧扫过角度(负值表示顺时针)
private float mainArcSweepAngle = -180f;
//小圆弧开始角度
private float unitStartAngle = 50f;
//小圆弧扫过角度 (负值表示顺时针)
private float unitSweepAngle = -10f;
//小圆弧之间间隔角度 (负值表示顺时针)
private float unitIntervalAngle = -50f;
//大圆弧路径
private Path mainArcPath = new Path();
//小圆弧路径
private Path unitArcPath = null;
/**
* 圆弧画笔
*/
private Paint mPaint;
/**
* 矩形画笔
*/
private Paint rectPaint;
/**
* 文字画笔
*/
private Paint textPaint;
//动画当前值
private float value = 0f;
//小圆点数目
private int circleNum = 0;
//小圆点的间距
private float circleEndMargin=10f;
private float circlRadius = 3f;
private ValueAnimator animator = null;
//RGB颜色数组 为渐变准备为数组,起始颜色值和终止颜色值
private int[] colors = {Color.parseColor("#744DF4"), Color.parseColor("#AA92F8"), Color.parseColor("#AA5AEC"), Color.parseColor("#744DF4")};
public LoadingView(Context context) {
super(context);
initView();
}
public LoadingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView();
}
public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView();
}
private void initView() {
intPaint();
initRect();
mPaint.setShader(new SweepGradient(rectF.centerX(), rectF.centerY(), colors, null));
initAnimator();
}
private void intPaint() {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(50f);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.RED);
rectPaint = new Paint();
rectPaint.setStyle(Paint.Style.STROKE);
rectPaint.setAntiAlias(true);
rectPaint.setDither(true);
rectPaint.setStrokeWidth(4f);
rectPaint.setColor(Color.WHITE);
textPaint = new Paint();
textPaint.setStyle(Paint.Style.FILL);
textPaint.setStrokeCap(Paint.Cap.BUTT);
textPaint.setAntiAlias(true);
textPaint.setDither(true);
textPaint.setTextSize(50f);
textPaint.setColor(Color.WHITE);
}
private void initRect() {
rectF.left = -radius;
rectF.right = radius;
rectF.top = -radius;
rectF.bottom = radius;
}
private void initAnimator() {
animator = ValueAnimator.ofFloat(0, 360);
animator.setDuration(4000);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setRepeatMode(ValueAnimator.RESTART);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(@NonNull ValueAnimator animation) {
value = (float) animation.getAnimatedValue();
mainstartAngle =value;
unitStartAngle = value;
int tmp=(int) (value%3);
if(tmp==0&&value<120){
circleNum = tmp+1;
}
if(tmp==1&&value<240&&value>120){
circleNum = tmp+1;
}
if(tmp==2&&value<360&&value>240){
circleNum = tmp+1;
}
invalidate();
}
});
animator.setInterpolator(new LinearInterpolator());
animator.start();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
textPaint.getTextBounds(text, 0, text.length(), textRect);
calculateTextPos();
}
@Override
protected void onDraw(@NonNull Canvas canvas) {
super.onDraw(canvas);
//将画布移动到屏幕中央
canvas.translate(mWidth / 2f, mHeight / 2f);
//绘制矩形
// canvas.drawRect(rectF, rectPaint);
//绘制大圆弧
drawMainArc(canvas);
//绘制两个小圆弧
drawUnitArc(canvas);
//绘制文本
drawTextAndLoading(canvas);
}
/**
* 绘制主圆弧[step 1- 固定的开始角度]
*/
private void drawMainArc(Canvas canvas) {
// mPaint.setColor(Color.RED);
// mainArcPath.addArc(rectF, mainstartAngle, mainArcSweepAngle);
canvas.drawArc(rectF, mainstartAngle, mainArcSweepAngle, false, mPaint);
}
/**
* 绘制小圆弧[step 1 - 固定的开始角度]
*/
private void drawUnitArc(Canvas canvas) {
float startAngle01 = -unitStartAngle;
float startAngle02 = startAngle01 + unitIntervalAngle + unitSweepAngle / 2;
float startAngle03 = startAngle02 + unitIntervalAngle + unitSweepAngle / 2;
float startAngle04 = startAngle03 + unitIntervalAngle + unitSweepAngle / 2;
float startAngle05 = startAngle04 + unitIntervalAngle + unitSweepAngle / 2;
float startAngle06 = startAngle05 + unitIntervalAngle + unitSweepAngle / 2;
canvas.drawArc(rectF, startAngle01, -unitSweepAngle, false, mPaint);
canvas.drawArc(rectF, startAngle02, -unitSweepAngle, false, mPaint);
canvas.drawArc(rectF, startAngle03, -unitSweepAngle, false, mPaint);
canvas.drawArc(rectF, startAngle04, -unitSweepAngle, false, mPaint);
canvas.drawArc(rectF, startAngle05, -unitSweepAngle, false, mPaint);
canvas.drawArc(rectF, startAngle06, -unitSweepAngle, false, mPaint);
// for (int i = 1; i < 3; i++) {
// unitArcPath = new Path();
// mPaint.setColor(Color.WHITE);
// //计算小圆弧路径
//// unitArcPath.addArc(rectF, -unitStartAngle * i + unitIntervalAngle + unitSweepAngle / 2, -unitSweepAngle);
//// //绘制小圆弧路径
//// canvas.drawPath(unitArcPath, mPaint);
// LogUtils.loge("unitStartAngle:"+i+"|"+(-unitStartAngle * i + unitIntervalAngle + unitSweepAngle / 2));
// canvas.drawArc(rectF,-unitStartAngle * i + unitIntervalAngle + unitSweepAngle / 2,-unitSweepAngle,false,mPaint);
// }
}
/**
* 绘制文字
*/
private void drawTextAndLoading(Canvas canvas) {
canvas.drawText(text, textX, Math.abs(textRect.top) + Math.abs(textRect.bottom) + radius + textTopMargin, textPaint);
for (int i = 0; i < circleNum; i++) {
float tx = (textX + Math.abs(textRect.right) + circleEndMargin + i * circleEndMargin);
canvas.drawCircle(tx, Math.abs(textRect.top) + Math.abs(textRect.bottom) + radius + textTopMargin, circlRadius, textPaint);
}
}
/**
* 计算文字绘制坐标
*/
private void calculateTextPos() {
textX = -Math.abs(textRect.right - textRect.left) / 2f;
textY = Math.abs(textRect.top) + Math.abs(textRect.bottom);
}
public void destory(){
if(animator!=null) {
animator.cancel();
}
}
}

View File

@@ -0,0 +1,81 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public abstract class MultiView extends FrameLayout {
protected MultiViewListener mMultiViewListener;
public MultiView(@NonNull Context context) {
super(context);
initView( context,null);
}
public MultiView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView( context,attrs);
}
public MultiView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView( context,attrs);
}
public MultiView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView( context,attrs);
}
public abstract void initView(Context context, AttributeSet attrs);
public abstract void onVideoRestart(String uri);
public abstract void onImageRestart(String uri);
public abstract void onImageRestartLocal(String path);
public abstract void loadIamgeRes(String uri,int defaultImageId);
public abstract void loadDefaultImage(int resId);
public abstract void resetView();
public abstract void stopView();
public abstract void stopAd();
public abstract void releaseView();
public abstract void pauseView();
public boolean isAdPlaying(){
return false;
}
public abstract boolean onAdViewClick();
public MultiViewListener getMultiViewListener() {
return mMultiViewListener;
}
public void setMultiViewListener(MultiViewListener mMultiViewListener) {
this.mMultiViewListener = mMultiViewListener;
}
public interface MultiViewListener{
public void onPlaybackStateChanged(int viewId,int playbackState);
}
}

View File

@@ -0,0 +1,56 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context) {
super(context);
LogUtils.loge("MyLinearLayout:");
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LogUtils.loge("MyLinearLayout:");
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LogUtils.loge("MyLinearLayout:");
}
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
LogUtils.loge("MyLinearLayout:");
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
LogUtils.loge("onFocusChanged:"+gainFocus+"|"+direction+"|"+ GsonUtil.GsonString(previouslyFocusedRect));
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
LogUtils.loge("onRequestFocusInDescendants:"+direction+"|"+ GsonUtil.GsonString(previouslyFocusedRect));
return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
}
}

View File

@@ -0,0 +1,450 @@
/*-------------------------------------------------------------------------
-------------------------------------------------------------------------*/
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.Animation.AnimationListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Matrix;
import android.util.AttributeSet;
import com.ik.mboxlauncher.R;
public class MyRelativeLayout extends RelativeLayout {
private final static String TAG = "MyRelativeLayout";
private ImageView scaleImage;
private Context mContext = null;
private static Rect imgRect;
private float scalePara = 1.1f;
private float shortcutScalePara = 1.1f;
private float framePara = 1.09f;
private int animDuration=70;
private int animDelay = 0;
public static View CurFView=null;
private final int MODE_HOME_RECT = 0;
private final int MODE_HOME_SHORTCUT = 1;
private final int MODE_CHILD_SHORTCUT = 2;
// private JsonUtils jsonUtils;
public MyRelativeLayout(Context context) {
super(context);
}
public MyRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public MyRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
// setAddShortcutHead();
// if (gainFocus == true && !Launcher.isInTouchMode && !Launcher.dontDrawFocus) {
// setNumberOfScreen();
// if (Launcher.prevFocusedView != null && (isParentSame(this, Launcher.prevFocusedView)
// || Launcher.isShowHomePage)) {
// if (!Launcher.dontRunAnim && !Launcher.IntoCustomActivity) {
// Launcher.layoutScaleShadow.setVisibility(View.INVISIBLE);
// Rect preRect = new Rect();
// Launcher.prevFocusedView.getGlobalVisibleRect(preRect);
// setShadowEffect();
// startFrameAnim(preRect);
// } else if (!(Launcher.IntoCustomActivity && Launcher.isShowHomePage && Launcher.ifChangedShortcut)) {
// Launcher.dontRunAnim = false;
// setSurface();
// }
// } else {
// if (Launcher.isShowHomePage || Launcher.dontRunAnim || Launcher.IntoCustomActivity) {
// Launcher.IntoCustomActivity = false;
// setSurface();
// }
// }
// } else if (!Launcher.isInTouchMode) {
// Launcher.prevFocusedView = this;
// if (!Launcher.dontRunAnim) {
// ScaleAnimation anim = new ScaleAnimation(1.07f, 1f, 1.07f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// anim.setZAdjustment(Animation.ZORDER_TOP);
// anim.setDuration(animDuration);
// anim.setStartTime(animDelay);
// if (!(this.getParent() instanceof MyGridLayout)) {
// this.bringToFront();
// ((View) this.getParent()).bringToFront();
// Launcher.viewHomePage.bringToFront();
// }
// this.startAnimation(anim);
// }
// }
}
// private void setAddShortcutHead() {
// View parent = (View) this.getParent();
// if (parent == (View) Launcher.videoShortcutView) {
// Launcher.current_shortcutHead = CustomAppsActivity.VIDEO_SHORTCUT_HEAD;
// } else if (parent == (View) Launcher.recommendShortcutView) {
// Launcher.current_shortcutHead = CustomAppsActivity.RECOMMEND_SHORTCUT_HEAD;
// } else if (parent == (View) Launcher.musicShortcutView) {
// Launcher.current_shortcutHead = CustomAppsActivity.MUSIC_SHORTCUT_HEAD;
// } else if (parent == (View) Launcher.localShortcutView) {
// Launcher.current_shortcutHead = CustomAppsActivity.LOCAL_SHORTCUT_HEAD;
// } else {
// Launcher.current_shortcutHead = CustomAppsActivity.HOME_SHORTCUT_HEAD;
// }
// }
// private void setNumberOfScreen() {
// if (this.getParent() instanceof MyGridLayout) {
// MyGridLayout parent = (MyGridLayout) this.getParent();
// if (parent == Launcher.videoShortcutView) {
// Launcher.tx_video_count.setText(Integer.toString(Launcher.videoShortcutView.indexOfChild(this) + 1));
// } else if (parent == Launcher.recommendShortcutView) {
// Launcher.tx_recommend_count.setText(Integer.toString(Launcher.recommendShortcutView.indexOfChild(this) + 1));
// } else if (parent == Launcher.appShortcutView) {
// Launcher.tx_app_count.setText(Integer.toString(Launcher.appShortcutView.indexOfChild(this) + 1));
// } else if (parent == Launcher.musicShortcutView) {
// Launcher.tx_music_count.setText(Integer.toString(Launcher.musicShortcutView.indexOfChild(this) + 1));
// } else if (parent == Launcher.localShortcutView) {
// Launcher.tx_local_count.setText(Integer.toString(Launcher.localShortcutView.indexOfChild(this) + 1));
// }
// }
// }
public class TransAnimationListener implements AnimationListener {
private Animation scaleAnim;
private ViewGroup mView;
public TransAnimationListener(Context context, ViewGroup view, Animation anim) {
scaleAnim = anim;
mView = view;
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// scaleAnim.reset();
// if (!Launcher.animIsRun) {
// Launcher.layoutScaleShadow.setVisibility(View.VISIBLE);
// //Launcher.frameView.setVisibility(View.VISIBLE);
// }
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
public class ScaleAnimationListener implements AnimationListener {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// if (!Launcher.animIsRun) {
// Launcher.layoutScaleShadow.setVisibility(View.VISIBLE);
// // Launcher.frameView.setVisibility(View.VISIBLE);
// }
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
private void startFrameAnim(Rect preRect) {
imgRect = new Rect();
this.getGlobalVisibleRect(imgRect);
//setTransFramePosition(preRect);
/*AnimationSet animationSet = new AnimationSet(true);
TranslateAnimation translateAnimation = new TranslateAnimation(0.0f, imgRect.left-preRect.left,0.0f, imgRect.top-preRect.top);
translateAnimation.setDuration(animDuration);
ScaleAnimation scaleAnimation = new ScaleAnimation(1f, (float)(imgRect.right-imgRect.left)/(float)(preRect.right-preRect.left),
1f, (float)(imgRect.bottom-imgRect.top)/(float)(preRect.bottom-preRect.top));
// Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f );
scaleAnimation.setDuration(animDuration);
scaleAnimation.setStartTime(animDelay);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(translateAnimation);
translateAnimation.setAnimationListener(new TransAnimationListener(mContext, this, scaleAnimation));
*/
ScaleAnimation shadowAnim = new ScaleAnimation(0.95f, 1f, 0.95f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
shadowAnim.setDuration(animDuration);
shadowAnim.setStartTime(animDelay);
shadowAnim.setAnimationListener(new ScaleAnimationListener());
// Launcher.layoutScaleShadow.startAnimation(shadowAnim);
//Launcher.trans_frameView.startAnimation(animationSet);
}
public void setSurface() {
setShadowEffect();
// if (!Launcher.animIsRun) {
// //Launcher.frameView.setVisibility(View.VISIBLE);
// Launcher.layoutScaleShadow.setVisibility(View.VISIBLE);
// }
}
public void setShadowEffect() {
float bgScalePara;
Rect layoutRect;
Bitmap scaleBitmap = null;
Bitmap shadowBitmap;
ViewGroup mView = this;
TextView scaleText;
int screen_mode;
String text = null;
//
// //Launcher.trans_frameView.bringToFront();
// Launcher.layoutScaleShadow.bringToFront();
// // Launcher.frameView.bringToFront();
//
// screen_mode = getScreenMode(mView);
//
// imgRect = new Rect();
// mView.getGlobalVisibleRect(imgRect);
// //setFramePosition(imgRect);
//
// scaleImage = (ImageView) Launcher.layoutScaleShadow.findViewById(R.id.img_focus_unit);
// scaleText = (TextView) Launcher.layoutScaleShadow.findViewById(R.id.tx_focus_unit);
//
// if (screen_mode == MODE_HOME_SHORTCUT) {
// bgScalePara = shortcutScalePara;
// } else {
// bgScalePara = scalePara;
// }
//
// if (mView.getChildAt(0) instanceof ImageView) {
// ImageView img = (ImageView) (mView.getChildAt(0));
// img.buildDrawingCache();
// Bitmap bmp = img.getDrawingCache();
// if (bmp == null) {
// Launcher.cantGetDrawingCache = true;
// return;
// } else {
// Launcher.cantGetDrawingCache = false;
// }
// scaleBitmap = zoomBitmap(bmp, (int) (imgRect.width() * bgScalePara), (int) (imgRect.height() * bgScalePara));
// img.destroyDrawingCache();
// }
// if (mView.getChildAt(1) instanceof TextView) {
// text = ((TextView) mView.getChildAt(1)).getText().toString();
// }
//
// shadowBitmap = BitmapFactory.decodeResource(mContext.getResources(), getShadow(mView.getChildAt(0), screen_mode));
// int layout_width = (shadowBitmap.getWidth() - imgRect.width()) / 2;
// int layout_height = (shadowBitmap.getHeight() - imgRect.height()) / 2;
// layoutRect = new Rect(imgRect.left - layout_width, imgRect.top - layout_height, imgRect.right + layout_width, imgRect.bottom + layout_height);
// Launcher.layoutScaleShadow.setBackgroundResource(0);
// initStatus(mView.getChildAt(0),scaleText);
// if (screen_mode == MODE_HOME_RECT) {
// Drawable drawable = getDrawable(mView,mView.getChildAt(0));
// scaleImage.setImageDrawable(drawable);
// } else {
// scaleImage.setImageBitmap(scaleBitmap);
// }
//
// if (text != null) {
// //setTextWidth(scaleText, scaleBitmap.getWidth());
// setTextMarginAndSize(scaleText, screen_mode);
// scaleText.setText(text);
// } else {
// scaleText.setText(null);
// }
//
// if (screen_mode != MODE_HOME_RECT) {
// Launcher.layoutScaleShadow.setBackgroundResource(getShadow(mView.getChildAt(0), screen_mode));
// }
// setViewPosition(Launcher.layoutScaleShadow, layoutRect);
// CurFView = mView;
}
private void setTextMarginAndSize(TextView text, int screen_mode) {
android.widget.RelativeLayout.LayoutParams para;
para = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// text.setTextColor(mContext.getResources().getColor(R.color.btn_text_color));
// if (screen_mode == MODE_HOME_RECT) {
// if (Launcher.REAL_OUTPUT_MODE.equals("4k2knative")) {
// para.setMargins(200, 170, 0, 0);
// } else if (Launcher.REAL_OUTPUT_MODE.equals("720p"))
// para.setMargins(66, 56, 0, 0);
// else
// para.setMargins(70, 60, 0, 0); // para.setMargins(100, 85, 0, 0);
// text.setLayoutParams(para);
// text.setTextSize(28);
// } else {
// para.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// para.addRule(RelativeLayout.CENTER_HORIZONTAL);
// if (Launcher.REAL_OUTPUT_MODE.equals("4k2knative")) {
// para.setMargins(130, 0, 130, 100);
// } else if (Launcher.REAL_OUTPUT_MODE.equals("720p"))
// para.setMargins(44, 0, 44, 34);
// else
// para.setMargins(65, 18, 65, 32);
// text.setLayoutParams(para);
// text.setTextSize(26);
// }
}
private void setTransFramePosition(Rect rect) {
// android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0);
// int rectWidth = rect.right - rect.left;
// int rectHeight = rect.bottom - rect.top;
//
// lp.width = (int) (rectWidth * framePara);
// lp.height = (int) (rectHeight * framePara);
// lp.x = rect.left + (int) ((rectWidth - lp.width) / 2);
// lp.y = rect.top + (int) ((rectHeight - lp.height) / 2);
// Launcher.trans_frameView.setLayoutParams(lp);
}
private void setFramePosition(Rect rect) {
android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0);
int rectWidth = rect.right - rect.left;
int rectHeight = rect.bottom - rect.top;
lp.width = (int) (rectWidth * framePara);
lp.height = (int) (rectHeight * framePara);
lp.x = rect.left + (int) ((rectWidth - lp.width) / 2);
lp.y = rect.top + (int) ((rectHeight - lp.height) / 2);
//Launcher.frameView.setLayoutParams(lp);
}
private void setViewPosition(View view, Rect rect) {
android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0);
lp.width = rect.width();
lp.height = rect.height();
lp.x = rect.left;
lp.y = rect.top;
view.setLayoutParams(lp);
}
private int getScreenMode(ViewGroup view) {
View img = view.getChildAt(0);
View tx = view.getChildAt(1);
String path = img.getResources().getResourceName(img.getId());
String vName = path.substring(path.indexOf("/") + 1);
if (vName.equals("img_recommend") || vName.equals("img_video") || vName.equals("img_setting")
|| vName.equals("img_app") || vName.equals("img_music") || vName.equals("img_local")) {
return MODE_HOME_RECT;
} else if (tx != null) {
framePara = 1.06f;
return MODE_CHILD_SHORTCUT;
} else {
return MODE_HOME_SHORTCUT;
}
}
private boolean isParentSame(View view1, View view2) {
if (((ViewGroup) view1.getParent()).indexOfChild(view2) == -1) {
return false;
} else {
return true;
}
}
// private Drawable getDrawable(View mv,View img){
// String path = img.getResources().getResourceName(img.getId());
// String vName = path.substring(path.indexOf("/")+1);
// SharedPreferences sharedPreferences = mContext.getSharedPreferences("mBox",Context.MODE_PRIVATE);
// if(vName.equals("img_video")){
// return mContext.getDrawable(R.drawable.focus_video);
// }else if (vName.equals("img_recommend")) {
// return mContext.getDrawable(R.drawable.focus_recommend);
// }else if (vName.equals("img_setting")) {
// return mContext.getDrawable(R.drawable.focus_setting);
// } else if (vName.equals("img_app")) {
// return mContext.getDrawable(R.drawable.focus_app);
// } else if (vName.equals("img_music")) {
// return mContext.getDrawable(R.drawable.focus_music);
// } else if (vName.equals("img_local")) {
//// if (JsonUtils.getInstance().getHomeType() == 0) {
//// return mContext.getDrawable(R.drawable.focus_local);
//// } else {
//// return mContext.getDrawable(R.drawable.focus_wetv);
//// }
// }
// return null;
// }
// private int getShadow(View img, int mode){
// String path = img.getResources().getResourceName(img.getId());
// String vName = path.substring(path.indexOf("/")+1);
// if (vName.equals("img_recommend")) {
// return R.drawable.focus_recommend;
// } else if(vName.equals("img_video")) {
// return R.drawable.focus_video;
// } else if(vName.equals("img_setting")) {
// return R.drawable.focus_setting;
// } else if(vName.equals("img_app")) {
// return R.drawable.focus_app;
// } else if(vName.equals("img_music")) {
// return R.drawable.focus_music;
// } else if(vName.equals("img_local")) {
// return R.drawable.focus_local;
// } else if (mode == MODE_CHILD_SHORTCUT) {
// return R.drawable.shadow_child_shortcut;
// } else if (mode == MODE_HOME_SHORTCUT) {
// return R.drawable.shadow_shortcut;
// } else {
// return -1;
// }
// }
public Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidht, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return newbmp;
}
private void initStatus(View img,TextView scaleText){
// String path = img.getResources().getResourceName(img.getId());
// String vName = path.substring(path.indexOf("/")+1);
// if (vName.equals("img_local")) {
// if (jsonUtils.getHomeType() == 0) {
// scaleText.setVisibility(View.VISIBLE);
// }else {
// scaleText.setVisibility(View.GONE);
// }
// }else {
// scaleText.setVisibility(View.VISIBLE);
// }
}
}

View File

@@ -0,0 +1,37 @@
/*-------------------------------------------------------------------------
-------------------------------------------------------------------------*/
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.widget.ScrollView;
import android.view.MotionEvent;
import android.util.AttributeSet;
public class MyScrollView extends ScrollView{
private final static String TAG="MyScrollView";
private Context mContext;
public MyScrollView (Context context){
super(context);
}
public MyScrollView (Context context, AttributeSet attrs){
super(context, attrs);
mContext = context;
}
@Override
public boolean onTouchEvent (MotionEvent event){
// Log.d(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ touch ="+ this);
return false;
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
// Launcher.layoutScaleShadow.setVisibility(View.INVISIBLE);
//Launcher.frameView.setVisibility(View.INVISIBLE);
return super.onGenericMotionEvent(event);
}
}

View File

@@ -0,0 +1,25 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.widget.TextView;
import android.util.AttributeSet;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context) {
super(context);
}
@Override
public boolean isFocused() {
return true;
}
}

View File

@@ -0,0 +1,275 @@
package com.ik.mboxlauncher.view;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.Player;
import com.android.database.lib.AdsInfoBean;
import com.android.monitor.DataBeeObserver;
import com.android.monitor.impl.EventFactory;
import com.android.nebulasdk.ADManager;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.io.File;
public class SplashView {
private View mView;
private CountdownTimeTextView txt_time;
private RelativeLayout container;
private Drawable bgDrawable=null;
private long crete_time=0;
private static String AD_FILE_PATH=null;
private HomeMultiView ad_splash_view;
private Context mContext;
private LoadingView loading_view;
private WindowManager windowManager=null;
private WindowManager.LayoutParams params;
private AdsInfoBean adsInfoBeanInfo=null;
private Handler mHandler= new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
if(adsInfoBeanInfo!=null) {
if (ADManager.ADTYPE_VIDEO.equals(adsInfoBeanInfo.getAdType())) {
// loading_view.setVisibility(View.VISIBLE);
LogUtils.loge("loading ADTYPE_VIDEO");
ad_splash_view.onVideoRestart(adsInfoBeanInfo.getLocalFilePath());
} else if (ADManager.ADTYPE_IMAGE.equals(adsInfoBeanInfo.getAdType())) {
// loading_view.setVisibility(View.GONE);
LogUtils.loge("loading ADTYPE_IMAGE");
ad_splash_view.onImageRestartLocal(adsInfoBeanInfo.getLocalFilePath());
}
}
mHandler.sendEmptyMessageDelayed(1,1000);
break;
case 1:
txt_time.starTimeUi(new CountdownTimeTextView.TextUiCallBack() {
@Override
public void onEndCallback() {
txt_time.setVisibility(View.INVISIBLE);
mHandler.sendEmptyMessageDelayed(2,1000);
}
});
break;
case 2:
dismiss();
ad_splash_view.stopView();
if(mSplashAdListener!=null){
mSplashAdListener.onEnd();
}
break;
}
}
};
public SplashView(@NonNull Context context) {
mContext = context;
// 设置布局参数
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = 0;
params.y = 100;
// 获取WindowManager并添加视图
windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
initView(context);
adsInfoBeanInfo= ADManager.getInstance().getADInfoById(100);
}
private void initView(Context context){
mView = LayoutInflater.from(context).inflate(R.layout.activity_splash_screen,null);
txt_time= mView.findViewById(R.id.txt_time);
loading_view =mView.findViewById(R.id.loading_view);
container = mView.findViewById(R.id.container);
ad_splash_view = mView.findViewById(R.id.ad_splash_view);
// ad_splash_view.setMultiViewListener(new HomeMultiView.MultiViewListener() {
// @Override
// public void onPlaybackStateChanged(int viewId, int playbackState) {
//
// if(playbackState== Player.STATE_ENDED||playbackState==Player.STATE_IDLE){
// //退出'
// DataBeeObserver.getInstance().recordEventMsg(
// EventFactory.EVENT_GOOGLE_AD,
// 100,
// System.currentTimeMillis(),
// System.currentTimeMillis(),
// "AdCompleted"
// );
// dismiss();
// }
// }
// });
}
public void show(){
if (windowManager != null && mView != null) {
try {
windowManager.addView(mView, params);
} catch (Exception e) {
e.printStackTrace();
}
}
AdsInfoBean adsInfoBeanInfo= ADManager.getInstance().getADInfoById(100);
if(adsInfoBeanInfo==null){
LogUtils.loge("adsInfoBeanInfo is null===>");
mHandler.sendEmptyMessageDelayed(2,10000);
return ;
}
if(adsInfoBeanInfo.getLocalFilePath()==null){
LogUtils.loge("getLocalFilePath is null===>");
mHandler.sendEmptyMessageDelayed(2,10000);
return ;
}
File file = new File(adsInfoBeanInfo.getLocalFilePath());
if(!file.exists()){
LogUtils.loge("file is not exits===>");
mHandler.sendEmptyMessageDelayed(2,10000);
return ;
}
if(adsInfoBeanInfo.getState()==0){
LogUtils.loge("splash task is closd ");
mHandler.sendEmptyMessageDelayed(2,5000);
return ;
}
mHandler.sendEmptyMessageDelayed(0,300);
// if(loadSplashAd()){
// // 确保windowManager和floatingView不为null
// if (windowManager != null && mView != null) {
// try {
// windowManager.addView(mView, params);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// };
}
public void dismiss(){
if (mView != null && windowManager != null) {
try {
if (mView.isAttachedToWindow()) {
windowManager.removeView(mView);
}
} catch (IllegalArgumentException e) {
// 视图可能已经被移除
e.printStackTrace();
}
}
}
// private boolean loadSplashAd(){
// AdsInfoBean adsInfoBeanInfo= ADManager.getInstance().getADInfoById(100);
//
// if(adsInfoBeanInfo==null){
// LogUtils.loge("adsInfoBeanInfo is null===>");
// return false;
// }
//
// if(adsInfoBeanInfo.getLocalFilePath()==null){
// LogUtils.loge("getLocalFilePath is null===>");
// return false;
// }
// File file = new File(adsInfoBeanInfo.getLocalFilePath());
// if(!file.exists()){
// LogUtils.loge("file is not exits===>");
// return false;
// }
//
//
// if(adsInfoBeanInfo.getState()==0){
// LogUtils.loge("splash task is closd ");
// return false;
// }
//
// if(ADManager.ADTYPE_VIDEO.equals(adsInfoBeanInfo.getAdType())) {
//// loading_view.setVisibility(View.VISIBLE);
// LogUtils.loge("loading ADTYPE_VIDEO");
// ad_splash_view.onVideoRestart(adsInfoBeanInfo.getLocalFilePath());
// }else if(ADManager.ADTYPE_IMAGE.equals(adsInfoBeanInfo.getAdType())) {
//// loading_view.setVisibility(View.GONE);
// LogUtils.loge("loading ADTYPE_IMAGE");
// ad_splash_view.onImageRestartLocal(adsInfoBeanInfo.getLocalFilePath());
// }
//
//
//
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// txt_time.starTimeUi(new CountdownTimeTextView.TextUiCallBack() {
// @Override
// public void onEndCallback() {
// txt_time.setVisibility(View.INVISIBLE);
// ad_splash_view.stopView();
// dismiss();
//
// }
// });
// }
// },1000*5);
//
// return true;
// }
private SplashAdListener mSplashAdListener;
public SplashAdListener getmSplashAdListener() {
return mSplashAdListener;
}
public void setmSplashAdListener(SplashAdListener mSplashAdListener) {
this.mSplashAdListener = mSplashAdListener;
}
public interface SplashAdListener{
public void onEnd();
}
}

View File

@@ -0,0 +1,99 @@
package com.ik.mboxlauncher.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;
import com.android.util.DateUtil;
import com.android.util.LogUtils;
import com.ik.mboxlauncher.R;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
//时间的textView
@SuppressLint("AppCompatCustomView")
public class TimeTextView extends TextView {
/*对应的时间格式为:时间 星期,月 日*/
private static final int FORMAT01=0x00;
private int DATE_FORMAT=FORMAT01;
private Handler handler = new Handler();
public TimeTextView(Context context) {
super(context);
}
public TimeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void starTimeUi(){
handler.post(timeRunnable);
}
public void cancelTimeUi(){
handler.removeCallbacks(timeRunnable);
}
Runnable timeRunnable = new Runnable() {
@Override
public void run() {
String timeStr= formatTimeDynamic(getContext());
// String weekStr = DateUtil.getNowWeek();
String dateStr = getDate();
setText(timeStr+" "+dateStr);
handler.postDelayed(this,500);
}
};
public static boolean is24HourFormat(Context context) {
// 直接使用系统提供的API判断
return android.text.format.DateFormat.is24HourFormat(context);
}
public static String formatTimeDynamic(Context context) {
String formatPattern;
// 判断设备是否使用 24 小时制
if (DateFormat.is24HourFormat(context)) {
formatPattern = "HH:mm "; // 24 小时制Log
} else {
formatPattern = "h:mm a"; // 12 小时制(如 "2:30 PM"
}
return DateFormat.format(formatPattern, new Date()).toString();
}
private String getDate(){
final Calendar c = Calendar.getInstance();
int int_Month = c.get(Calendar.MONTH);
String mDay = Integer.toString(c.get(Calendar.DAY_OF_MONTH));
int int_Week = c.get(Calendar.DAY_OF_WEEK) -1;
String str_week = this.getResources().getStringArray(R.array.week)[int_Week];
String mMonth = this.getResources().getStringArray(R.array.month)[int_Month];
String date;
if (Locale.getDefault().getLanguage().equals("zh")) {
date = str_week + " , " + mMonth + " " + mDay + this.getResources().getString(R.string.str_day);
}else {
date = str_week + " , " + mMonth + " " + mDay;
}
return date;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="300"/>
</set>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/app_info_add_bg"/>
<stroke android:width="3dp" android:color="@android:color/white"/>
<corners android:radius="25dp"/>
</shape>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/app_info_add_bg"/>
<corners android:radius="25dp"/>
</shape>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/app_info_add_bg"/>
<stroke android:width="2dp" android:color="@android:color/white"/>
<corners android:radius="9dp"/>
</shape>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/app_info_add_bg"/>
<corners android:radius="9dp"/>
</shape>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white"/>
<stroke android:width="4dp" android:color="@android:color/white"/>
<corners android:radius="20dp"/>
</shape>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white"/>
<stroke android:width="2dp" android:color="@android:color/white"/>
</shape>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 924 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 840 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 498 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -0,0 +1,9 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<gradient android:startColor="#aa000000"
android:endColor="#00000000"
android:angle="270"/>
</shape>
</item>
</layer-list>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -0,0 +1,4 @@
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_apps_select" android:state_selected="true"/>
<item android:drawable="@drawable/tab_apps_normal"/>
</selector>

View File

@@ -0,0 +1,14 @@
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<shape>
<solid android:color="@color/tab_item_select_bg"/>
<corners android:radius="400dp"/>
</shape>
</item>
<item>
<shape>
<solid android:color="@color/tab_item_bg"/>
<corners android:radius="400dp"/>
</shape>
</item>
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 977 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 B

View File

@@ -0,0 +1,4 @@
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_local_select" android:state_selected="true"/>
<item android:drawable="@drawable/tab_local_normal"/>
</selector>

Some files were not shown because too many files have changed in this diff Show More