Rebase to master when repo went private

This commit is contained in:
Your Name
2020-08-17 13:31:05 +01:00
commit fe20b27432
345 changed files with 28876 additions and 0 deletions
@@ -0,0 +1,330 @@
package com.sidequest.launcher.gui;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppInfo;
import com.sidequest.launcher.tools.AppStarter;
import com.sidequest.launcher.tools.AppStarterUpdater;
import com.sidequest.launcher.tools.SettingsProvider;
import com.sidequest.launcher.tools.Tools;
import static com.sidequest.launcher.gui.AppSettingsOverlayDialog.*;
/**
* Launcher main (shows the user apps)
*/
public class AppActivity extends CustomFragment
{
/**
* Default launcher package
*/
private String mDefaultLauncherPackage;
// Moving app-info (if null, no app is moving
private final AppInfo[] mMovingApp = {null};
/**
* Instance of settingsprovider
*/
SettingsProvider mSettings = SettingsProvider.getInstance(this.getActivity());
/** Latest AppStarter version found */
public static String LATEST_APP_VERSION = null;
/**
* Holds the gridview resource
*/
private GridView mGridView;
/**
* Indicated if app has been in pause but was not destroyed
*/
private Boolean mHasBeenInOnPauseButNotInDestroy = false;
/** Mandatory for fragment initation */
public AppActivity(){ }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.appactivity, container, false);
// Reset pause flag
mHasBeenInOnPauseButNotInDestroy = false;
// Get default-launcher package
mDefaultLauncherPackage = AppStarter.getLauncherPackageName(getActivity());
// Check for custom app-icon size
mGridView = (GridView) rootView.findViewById(R.id.gridview);
Integer appIconSize = mSettings.getAppIconSize();
if(appIconSize > 0)
{
// Set size of items
mGridView.setColumnWidth(Tools.getPixelFromDip(getActivity(), appIconSize));
}
mGridView.setAdapter(new InstalledAppsAdapter(getActivity()));
// Focus first item
mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
try
{
// Remove listener
mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Check if first icon have to be selected
if(mSettings.getAutoSelectFirstIcon() && mGridView.getChildCount() > 0)
{
mGridView.requestFocusFromTouch();
mGridView.setSelection(0);
}
// Check for new update
AppStarterUpdater appStarterUpdater = new AppStarterUpdater();
if(!mSettings.getHaveUpdateSeen() && appStarterUpdater.isVersionNewer(Tools.getCurrentAppVersion(getActivity()), LATEST_APP_VERSION))
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("AppStarter " + LATEST_APP_VERSION);
builder.setMessage("There is a new version of AppStarter, do you want to update?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
// Trigger update
if(getActivity() instanceof MainActivity)
{
((MainActivity) getActivity()).triggerUpdate();
}
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// Set have seen
mSettings.setHaveUpdateSeen(true);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Failed to focus first app: \n" + errorReason);
}
}
});
// Set click listener
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
if (mMovingApp[0] != null)
{
// Stop moving
mMovingApp[0] = null;
mGridView.setDrawSelectorOnTop(false);
mGridView.invalidate();
// Save current order
InstalledAppsAdapter actAdapter = (InstalledAppsAdapter) parent.getAdapter();
actAdapter.storeNewPackageOrder();
} else
{
// Get packagename of the app to be started
String packageName = ((AppInfo) parent.getAdapter().getItem(position)).packageName;
// Now start app
AppStarter.startAppByPackageName(getActivity(), packageName, false, false, false);
}
}
});
// Set long click listener
mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
// Get packagename of the app to be started
mMovingApp[0] = (AppInfo) parent.getAdapter().getItem(position);
mGridView.setDrawSelectorOnTop(true);
mGridView.invalidate();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.MoveAppAndClickToDrop), Toast.LENGTH_SHORT).show();
return true;
}
});
// Set select listener
mGridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (mMovingApp[0] != null)
{
InstalledAppsAdapter actAdapter = (InstalledAppsAdapter) parent.getAdapter();
actAdapter.moveAppToPosition(mMovingApp[0], position);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
// Do nothing here
}
});
return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public void onPause()
{
super.onPause();
mHasBeenInOnPauseButNotInDestroy = true;
}
@Override
public void onResume()
{
super.onResume();
if (mHasBeenInOnPauseButNotInDestroy)
{
// Reload app order
Log.d(MainActivity.class.getName(), "Reloading Order.");
InstalledAppsAdapter actAdapter = (InstalledAppsAdapter) mGridView.getAdapter();
actAdapter.loadInstalledApps();
actAdapter.notifyDataSetChanged();
}
}
@Override
public boolean onBackPressed()
{
boolean retVal = false;
if(mMovingApp[0] != null)
{
// Stop moving without saving the order
mMovingApp[0] = null;
mGridView.setDrawSelectorOnTop(false);
mGridView.invalidate();
// Restore old order
InstalledAppsAdapter actAdapter = (InstalledAppsAdapter)mGridView.getAdapter();
actAdapter.loadInstalledApps();
actAdapter.notifyDataSetChanged();
retVal = true;
}
return retVal;
}
@Override
public boolean onKeyDown(int keycode, KeyEvent e)
{
if(mMovingApp[0] == null && keycode == KeyEvent.KEYCODE_MENU)
{
showAppSettingsDialogForCurrentApp();
return true;
}
return false;
}
private void showAppSettingsDialogForCurrentApp()
{
try
{
// Check selected app
if(mGridView.hasFocus())
{
final AppInfo appInfo = (AppInfo) ((InstalledAppsAdapter) mGridView.getAdapter()).getItem(mGridView.getSelectedItemPosition());
final AppSettingsOverlayDialog appSettingsDialog = newInstance(appInfo);
appSettingsDialog.setOnActionClickedHandler(new OnActionClickedHandler()
{
@Override
public void onActionClicked(ActionEnum action)
{
Log.d("AppSettingsAction", "Clicked action: " + action.toString());
// Close dialog and evaluate click event:
appSettingsDialog.dismiss();
switch (action)
{
case SORT:
// Get packagename of the app to be started
mMovingApp[0] = appInfo;
mGridView.setDrawSelectorOnTop(true);
mGridView.invalidate();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.MoveAppAndClickToDropWhenStartedByMenu), Toast.LENGTH_SHORT).show();
break;
case SETTINGS:
AppStarter.startSettingsViewByPackageName(AppActivity.this.getActivity(), appInfo.packageName);
break;
default:
// Do nothing by default
}
}
});
FragmentManager fm = getActivity().getFragmentManager();
appSettingsDialog.show(fm, "");
}
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Failed to load app settings: \n" + errorReason);
}
}
}
@@ -0,0 +1,125 @@
package com.sidequest.launcher.gui;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppInfo;
/**
* App Settings Overlay for additional settings per app
*/
public class AppSettingsOverlayDialog extends DialogFragment
{
public enum ActionEnum { NOTHING, SORT, SETTINGS }
public static AppSettingsOverlayDialog newInstance(AppInfo appInfo)
{
// Create dialog and set custom style
AppSettingsOverlayDialog dialog = new AppSettingsOverlayDialog();
dialog.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.TransparentDialog);
// Add needed stuff
dialog.setAppInfo(appInfo);
return dialog;
}
/** AppInfo of the current App */
private AppInfo mAppInfo;
/** Action handler */
private OnActionClickedHandler onActionClickedHandler;
/**
* Default constructor required for DialogFragment
*/
public AppSettingsOverlayDialog()
{
}
/**
* Set the action click listener
* @param listener
*/
public void setOnActionClickedHandler(OnActionClickedHandler listener)
{
onActionClickedHandler = listener;
}
/**
* Sets the current AppInfo
* @param appInfo
*/
public void setAppInfo(AppInfo appInfo)
{
mAppInfo = appInfo;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
return dialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Create view
View view = inflater.inflate(R.layout.appsettingsoverlaydialog, container);
// Set text, icons and click-handler
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(mAppInfo.getDisplayName());
ImageView appIcon = (ImageView) view.findViewById(R.id.appIcon);
appIcon.setImageDrawable(mAppInfo.getDisplayIcon());
LinearLayout appSort = (LinearLayout) view.findViewById(R.id.appSort);
appSort.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
fireActionClicked(ActionEnum.SORT);
}
});
LinearLayout appSettings = (LinearLayout) view.findViewById(R.id.appSettings);
appSettings.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
fireActionClicked(ActionEnum.SETTINGS);
}
});
return view;
}
private void fireActionClicked(ActionEnum action)
{
if(onActionClickedHandler != null)
{
onActionClickedHandler.onActionClicked(action);
}
}
/**
* Interface for a service error
*/
public interface OnActionClickedHandler
{
public void onActionClicked(ActionEnum action);
}
}
@@ -0,0 +1,23 @@
package com.sidequest.launcher.gui;
import android.app.Fragment;
import android.view.KeyEvent;
/**
* Fragement that has additional features
*/
public class CustomFragment extends Fragment
{
/**
* Custom on backpressed method
*/
public boolean onBackPressed()
{
return false;
}
public boolean onKeyDown(int keycode, KeyEvent e)
{
return false;
}
}
@@ -0,0 +1,246 @@
package com.sidequest.launcher.gui;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by luki on 27.06.15.
*/
public class FileDialog
{
private static final String PARENT_DIR = "..";
private final String TAG = getClass().getName();
private String[] fileList;
private File currentPath;
public interface FileSelectedListener
{
void fileSelected(File file);
}
public interface DirectorySelectedListener
{
void directorySelected(File directory);
}
private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
private final Activity activity;
private boolean selectDirectoryOption;
private String[] fileEndsWith;
/**
* @param activity
* @param path
*/
public FileDialog(Activity activity, File path)
{
this.activity = activity;
if (!path.exists()) path = Environment.getExternalStorageDirectory();
loadFileList(path);
}
/**
* @return file dialog
*/
public Dialog createFileDialog()
{
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(currentPath.getPath());
if (selectDirectoryOption)
{
builder.setPositiveButton("Select directory", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Log.d(TAG, currentPath.getPath());
fireDirectorySelectedEvent(currentPath);
}
});
}
builder.setItems(fileList, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
String fileChosen = fileList[which];
File chosenFile = getChosenFile(fileChosen);
if (chosenFile.isDirectory())
{
loadFileList(chosenFile);
dialog.cancel();
dialog.dismiss();
showDialog();
} else fireFileSelectedEvent(chosenFile);
}
});
dialog = builder.show();
return dialog;
}
public void addFileListener(FileSelectedListener listener)
{
fileListenerList.add(listener);
}
public void removeFileListener(FileSelectedListener listener)
{
fileListenerList.remove(listener);
}
public void setSelectDirectoryOption(boolean selectDirectoryOption)
{
this.selectDirectoryOption = selectDirectoryOption;
}
public void addDirectoryListener(DirectorySelectedListener listener)
{
dirListenerList.add(listener);
}
public void removeDirectoryListener(DirectorySelectedListener listener)
{
dirListenerList.remove(listener);
}
/**
* Show file dialog
*/
public void showDialog()
{
createFileDialog().show();
}
private void fireFileSelectedEvent(final File file)
{
fileListenerList.fireEvent(new ListenerList.FireHandler<FileSelectedListener>()
{
public void fireEvent(FileSelectedListener listener)
{
listener.fileSelected(file);
}
});
}
private void fireDirectorySelectedEvent(final File directory)
{
dirListenerList.fireEvent(new ListenerList.FireHandler<DirectorySelectedListener>()
{
public void fireEvent(DirectorySelectedListener listener)
{
listener.directorySelected(directory);
}
});
}
private void loadFileList(File path)
{
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists())
{
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter()
{
public boolean accept(File dir, String filename)
{
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else
{
boolean endsWith = false;
if(fileEndsWith != null)
{
for (String ending : fileEndsWith)
{
if (filename.toLowerCase().endsWith(ending))
{
endsWith = true;
break;
}
}
}
return endsWith || sel.isDirectory();
}
}
};
String[] fileList1 = path.list(filter);
for (String file : fileList1)
{
r.add(file);
}
}
Collections.sort(r);
fileList = (String[]) r.toArray(new String[]{});
}
private File getChosenFile(String fileChosen)
{
if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
else return new File(currentPath, fileChosen);
}
public void setFileEndsWith(String[] fileEndsWith)
{
if(fileEndsWith != null)
{
for(Integer i = 0; i < fileEndsWith.length; i++)
{
fileEndsWith[i] = fileEndsWith[i].toLowerCase();
}
}
this.fileEndsWith = fileEndsWith;
// Again load file-list (because now file-list can change)
loadFileList(currentPath);
}
}
class ListenerList<L>
{
private List<L> listenerList = new ArrayList<L>();
public interface FireHandler<L>
{
void fireEvent(L listener);
}
public void add(L listener)
{
listenerList.add(listener);
}
public void fireEvent(FireHandler<L> fireHandler)
{
List<L> copy = new ArrayList<L>(listenerList);
for (L l : copy)
{
fireHandler.fireEvent(l);
}
}
public void remove(L listener)
{
listenerList.remove(listener);
}
public List<L> getListenerList()
{
return listenerList;
}
}
@@ -0,0 +1,79 @@
package com.sidequest.launcher.gui;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sidequest.launcher.R;
/**
* Info Overlay for additional information
*/
public class InfoOverlayDialog extends DialogFragment
{
/**
* Create a new Info-Overlay dialog
* @param title Title of the info dialog
* @param summary Text of the info dialog
* @return the dialog
*/
public static InfoOverlayDialog newInstance(String title, String summary)
{
// Create dialog and set custom style
InfoOverlayDialog dialog = new InfoOverlayDialog();
dialog.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.TransparentDialog);
// Set title and summary
dialog.setTitleAndSummary(title, summary);
return dialog;
}
/** Title of the info dialog */
private String mTitle;
/** Text of the info dialog */
private String mSummary;
/**
* Default constructor required for DialogFragment
*/
public InfoOverlayDialog()
{
}
public void setTitleAndSummary(String title, String summary)
{
// Set title and summary
mTitle = title;
mSummary = summary;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
return dialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Create view
View view = inflater.inflate(R.layout.infooverlaydialog, container);
// Set text, icons and click-handler
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(mTitle);
TextView summary = (TextView) view.findViewById(R.id.summary);
summary.setText(mSummary);
return view;
}
}
@@ -0,0 +1,109 @@
package com.sidequest.launcher.gui;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.widget.Toast;
import java.text.DateFormat;
import java.util.Date;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.Tools;
/**
* Info / System view
*/
public class InfosPrefActivity extends PreferenceFragment
{
static final long SLEEPTIME_MINIMUM = 1;
static final long SLEEPTIME_MAXIMUM = 120;
public InfosPrefActivity()
{
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.infoprefactivity);
Preference prefDeviceDetails = (Preference) findPreference("prefVirtualDeviceDetails");
prefDeviceDetails.setSummary(Tools.getDeviceDetails());
Preference prefHostname = (Preference) findPreference("prefVirtualHostname");
prefHostname.setSummary(Tools.getHostName(getActivity().getResources().getString(R.string.notfound)));
Preference prefWifiName = (Preference) findPreference("prefVirtualWifiName");
prefWifiName.setSummary(Tools.getWifiSsid(this.getActivity(), getActivity().getResources().getString(R.string.notfound)));
Preference prefIpAddress = (Preference) findPreference("prefVirtualIpAddress");
prefIpAddress.setSummary(Tools.getActiveIpAddress(getActivity(), getActivity().getResources().getString(R.string.notfound)));
Preference prefDeviceUpTime = (Preference) findPreference("prefVirtualDeviceUpTime");
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, getResources().getConfiguration().locale);
String upTime = String.format(getActivity().getResources().getString(R.string.uptimedesc), Tools.formatInterval(SystemClock.elapsedRealtime()), dateFormat.format(new Date(System.currentTimeMillis() - SystemClock.elapsedRealtime())));
prefDeviceUpTime.setSummary(upTime);
// final EditTextPreference prefSetSleepTimeout = (EditTextPreference) findPreference("prefVirtualSleepTime");
// prefSetSleepTimeout.setText(((Long)(Tools.getSleepModeTimeout(getActivity()) / 1000 / 60)).toString());
// prefSetSleepTimeout.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
// {
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue)
// {
// long newTimeInMinutes = 0;
// try
// {
// newTimeInMinutes = Long.valueOf(newValue.toString());
// }
// catch (Exception ignore)
// {
// }
//
// do
// {
// if (newTimeInMinutes < SLEEPTIME_MINIMUM || newTimeInMinutes > SLEEPTIME_MAXIMUM)
// {
// Toast.makeText(InfosPrefActivity.this.getActivity(), String.format(getActivity().getResources().getString(R.string.sleeptime_limit), SLEEPTIME_MINIMUM, SLEEPTIME_MAXIMUM), Toast.LENGTH_SHORT).show();
// break;
// }
//
// long newTimeInMs = newTimeInMinutes * 60 * 1000;
// Tools.setSleepModeTimeout(getActivity(), newTimeInMs);
// prefSetSleepTimeout.setText(((Long)(Tools.getSleepModeTimeout(getActivity()) / 1000 / 60)).toString());
// }
// while (false);
//
// return false;
// }
// });
//
// Preference prefGoToSleep = (Preference) findPreference("prefVirtualGoToSleep");
// prefGoToSleep.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
// {
// @Override
// public boolean onPreferenceClick(Preference preference)
// {
// Toast.makeText(InfosPrefActivity.this.getActivity(), getActivity().getResources().getString(R.string.gotosleep_summary), Toast.LENGTH_SHORT).show();
// return false;
// }
// });
//
// Preference prefReboot = (Preference) findPreference("prefVirtualRestart");
// prefReboot.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
// {
// @Override
// public boolean onPreferenceClick(Preference preference)
// {
// Toast.makeText(InfosPrefActivity.this.getActivity(), getActivity().getResources().getString(R.string.system_restart_summary_removed), Toast.LENGTH_SHORT).show();
// return false;
// }
// });
}
}
@@ -0,0 +1,434 @@
package com.sidequest.launcher.gui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppInfo;
import com.sidequest.launcher.tools.AppStarter;
import com.sidequest.launcher.tools.SettingsProvider;
import com.sidequest.launcher.tools.Tools;
/**
* Adapter that lists all installed apps
*/
public class InstalledAppsAdapter extends BaseAdapter
{
/** Virtual package for settings app */
public static final String VIRTUAL_SETTINGS_PACKAGE = "de.belu.appstarter.virtual.settings";
/** Context we are currently running in */
private Context mContext;
/** List of installed apps */
private List<AppInfo> mInstalledApps;
/** Default launcher package */
private String mDefaultLauncherPackage;
/** Settings */
private SettingsProvider mSettings;
/** Include this app */
private Boolean mIncludeOwnApp;
/** Show hidden apps */
private Boolean mShowHiddenApps;
/**
* Create new InstalledAppsAdapter
* @param c Current context
*/
public InstalledAppsAdapter(Context c)
{
this(c, false, false);
}
/**
* Create new InstalledAppsAdapter
* @param c Current context
* @param includeOwnApp Include this app (de.belu.appstarter)
*/
public InstalledAppsAdapter(Context c, Boolean includeOwnApp, Boolean showHiddenApps)
{
mContext = c;
mIncludeOwnApp = includeOwnApp;
mShowHiddenApps = showHiddenApps;
// Get default-launcher package
mDefaultLauncherPackage = AppStarter.getLauncherPackageName(mContext);
// Get instance of settingsprovider
mSettings = SettingsProvider.getInstance(mContext);
// Now load all installed apps
loadInstalledApps();
}
/**
* Create a launchable intent by package-name
* @param context Current context
* @param packageName Package name of app
* @return Launchable intent
*/
@SuppressLint("NewApi")
public static Intent getLaunchableIntentByPackageName(Context context, String packageName)
{
// Create intent
Intent launchIntent = null;
// Check if package is one of the virtual packages
if(packageName.equals(VIRTUAL_SETTINGS_PACKAGE))
{
launchIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
// Start settings as new activity
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
else
{
try
{
launchIntent = context.getPackageManager().getLeanbackLaunchIntentForPackage(packageName);
}
catch(Throwable ignore) { }
if(launchIntent == null)
{
launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
}
}
// Return the launchable intent
return launchIntent;
}
/**
* @return Count of installed apps
*/
public int getCount()
{
return mInstalledApps.size();
}
/**
* @param position Position of item to be returned
* @return Item on position
*/
public Object getItem(int position)
{
return mInstalledApps.get(position);
}
/**
* Currently not used..
*/
public long getItemId(int position)
{
return position;
}
/**
* @return List of found apps
*/
public List<AppInfo> getAppList()
{
return mInstalledApps;
}
/**
* Store current package-order in settings
*/
public void storeNewPackageOrder()
{
List<String> packageList = new ArrayList<String>();
for(AppInfo actApp : mInstalledApps)
{
packageList.add(actApp.packageName);
}
mSettings.setPackageOrder(packageList);
}
/**
* Move certain item to certain position
* @param app Item to move
* @param position Position to move to
*/
public void moveAppToPosition(AppInfo app, int position)
{
if(mInstalledApps.contains(app))
{
try
{
mInstalledApps.remove(app);
mInstalledApps.add(position, app);
notifyDataSetChanged();
}
catch(Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(InstalledAppsAdapter.class.getName(), "Error while moving app: \n" + errorReason);
}
}
}
/**
* @return View of the given position
*/
public View getView(int position, View convertView, ViewGroup parent)
{
// Get act app
AppInfo actApp = mInstalledApps.get(position);
// Inflate layout
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null)
{
gridView = new View(mContext);
// get layout depending on setting
if(mSettings.getShowBackgroundForAppNames())
{
gridView = inflater.inflate(R.layout.appdrawergriditemlayout_withbackground, parent, false);
}
else
{
gridView = inflater.inflate(R.layout.appdrawergriditemlayout, parent, false);
}
} else
{
gridView = (View) convertView;
}
Integer appIconSize = mSettings.getAppIconSize();
if(appIconSize > 0)
{
// Set size of items
appIconSize = Tools.getPixelFromDip(parent.getContext(), appIconSize);
LinearLayout linearLayout = (LinearLayout) gridView.findViewById(R.id.linearLayout);
ViewGroup.LayoutParams params = linearLayout.getLayoutParams();
params.width = appIconSize;
params.height = appIconSize;
linearLayout.setLayoutParams(params);
}
// set value into textview
TextView textView = (TextView) gridView.findViewById(R.id.textLabel);
textView.setText(actApp.getDisplayName());
// set image based on selected text
ImageView imageView = (ImageView) gridView.findViewById(R.id.imageLabel);
imageView.setImageDrawable(actApp.getDisplayIcon());
return gridView;
}
/**
* Load all installed apps and order them correctly
*/
public void loadInstalledApps()
{
// Get hashset of hidden apps
Set<String> hiddenApps;
if(mShowHiddenApps)
{
// Create empty hidden-list
hiddenApps = new HashSet<String>();
}
else
{
hiddenApps = mSettings.getHiddenApps();
}
// Get list of installed apps
PackageManager pm = mContext.getPackageManager();
List<ApplicationInfo> installedApplications = pm.getInstalledApplications(PackageManager.GET_META_DATA);
// Put them into a map with packagename as keyword for faster handling
Boolean includeSysApps = mSettings.getShowSystemApps();
String ownPackageName = mContext.getApplicationContext().getPackageName();
Map<String, ApplicationInfo> appMap = new LinkedHashMap<String, ApplicationInfo>();
for(ApplicationInfo installedApplication : installedApplications)
{
if(!hiddenApps.contains(installedApplication.packageName))
{
// Check for system app
Boolean isSystemApp = ((installedApplication.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1 ||
(installedApplication.flags & ApplicationInfo.FLAG_SYSTEM) == 1);
// If amazon-home, mark not as system app
if(isSystemApp && installedApplication.packageName.equals(mDefaultLauncherPackage))
{
isSystemApp = false;
}
if(includeSysApps || !isSystemApp)
{
if((mIncludeOwnApp || !installedApplication.packageName.equals(ownPackageName)))
{
appMap.put(installedApplication.packageName, installedApplication);
}
}
}
}
// Add virtual packages if not hided
if(!hiddenApps.contains(VIRTUAL_SETTINGS_PACKAGE))
{
// ApplicationInfo applicationInfo = new ApplicationInfo();
// applicationInfo.packageName = VIRTUAL_SETTINGS_PACKAGE;
// appMap.put(VIRTUAL_SETTINGS_PACKAGE, new AppInfo(mContext, applicationInfo)
// {
// @Override
// public String getDisplayName()
// {
// return mContext.getResources().getString(R.string.AmazonSettings);
// }
//
// @Override
// public Drawable getDisplayIcon()
// {
// Drawable retVal = null;
//
// try
// {
// retVal = new BitmapDrawable(mContext.getResources(), BitmapFactory.decodeStream(mContext.getAssets().open("firetv-settings-icon.png")));
// }
// catch (Exception ignore){ }
//
// return retVal;
// }
// });
}
// Get order of last run
List<String> packageOrder = mSettings.getPackageOrder();
// Create new list of apps
mInstalledApps = new ArrayList<AppInfo>();
// Default the amazon launcher to the first position
// (if user has moved it, it is not anymore in list here)
if(packageOrder.contains("com.sidequest.launcher"))
{
packageOrder.remove("com.sidequest.launcher");
}
if(packageOrder.contains("com.sidequest.wrapper"))
{
packageOrder.remove("com.sidequest.wrapper");
}
if(appMap.containsKey("com.sidequest.launcher"))
{
appMap.remove("com.sidequest.launcher");
}
if(appMap.containsKey("com.sidequest.wrapper"))
{
appMap.remove("com.sidequest.wrapper");
}
if(appMap.containsKey(mDefaultLauncherPackage))
{
//addAppToCurrentList(appMap.get(mDefaultLauncherPackage));
appMap.remove(mDefaultLauncherPackage);
}
// Default amazon settings to the second position
// (if user has moved it, it is not anymore in list here)
if(appMap.containsKey(VIRTUAL_SETTINGS_PACKAGE))
{
//addAppToCurrentList(appMap.get(VIRTUAL_SETTINGS_PACKAGE));
appMap.remove(VIRTUAL_SETTINGS_PACKAGE);
}
// First handle all apps of the last run
for(String packageName : packageOrder)
{
if(appMap.containsKey(packageName))
{
addAppToCurrentList(appMap.get(packageName));
appMap.remove(packageName);
}
}
// Now handle all other apps
for(ApplicationInfo installedApplication : appMap.values())
{
addAppToCurrentList(installedApplication);
}
}
/**
* @param app App to be added to current apps-list
*/
private void addAppToCurrentList(ApplicationInfo app)
{
if(app.packageName.equals(mDefaultLauncherPackage))
{
AppInfo amazonLauncher = new AppInfo(mContext, app)
{
@Override
public String getDisplayName()
{
return mContext.getResources().getString(R.string.AmazonHome);
}
@Override
public Drawable getDisplayIcon()
{
Drawable retVal = null;
try
{
retVal = new BitmapDrawable(mContext.getResources(), BitmapFactory.decodeStream(mContext.getAssets().open("firetv-home-icon.png")));
}
catch (Exception ignore){ }
return retVal;
}
};
mInstalledApps.add(amazonLauncher);
}
else
{
if(app instanceof AppInfo)
{
mInstalledApps.add((AppInfo)app);
}
else
{
mInstalledApps.add(new AppInfo(mContext, app));
}
}
}
}
@@ -0,0 +1,112 @@
package com.sidequest.launcher.gui;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import com.sidequest.launcher.R;
/**
* Adpater for items in the left selection bar
*/
public class LeftBarItemsListAdapter extends BaseAdapter
{
/**
* A left bar fragment item
*/
public static class FragmentListItem
{
public String description;
public String className;
public FragmentListItem(String description, String className)
{
this.description = description;
this.className = className;
}
@Override
public String toString()
{
return description;
}
}
/** Left bar item list */
private static List<FragmentListItem> mItems = null;
/** Current context */
private Context mContext;
/** Create new adapter */
public LeftBarItemsListAdapter(Context context)
{
mContext = context;
if(mItems == null)
{
mItems = new ArrayList<FragmentListItem>();
mItems.add(new FragmentListItem(mContext.getResources().getString(R.string.leftbar_allapps), AppActivity.class.getName()));
mItems.add(new FragmentListItem(mContext.getResources().getString(R.string.leftbar_infos), InfosPrefActivity.class.getName()));
// mItems.add(new FragmentListItem(mContext.getResources().getString(R.string.leftbar_updates), UpdaterActivity.class.getName()));
mItems.add(new FragmentListItem(mContext.getResources().getString(R.string.leftbar_settings), PreferenceActivity.class.getName()));
}
}
/**
* @return Count of installed apps
*/
public int getCount()
{
return mItems.size();
}
/**
* @param position Position of item to be returned
* @return Item on position
*/
public FragmentListItem getItem(int position)
{
return mItems.get(position);
}
/**
* Currently not used..
*/
public long getItemId(int position)
{
return position;
}
/**
* @return View of the given position
*/
public View getView(int position, View convertView, ViewGroup parent)
{
// Inflate layout
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView;
if (convertView == null)
{
// get layout from mobile.xml
itemView = inflater.inflate(R.layout.leftbarlistitemlayout, parent, false);
} else
{
itemView = (View) convertView;
}
// set value into textview
TextView textView = (TextView) itemView.findViewById(R.id.textLabel);
textView.setText(mItems.get(position).description);
return itemView;
}
}
@@ -0,0 +1,458 @@
package com.sidequest.launcher.gui;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.SettingsProvider;
public class MainActivity extends Activity
{
private LinearLayout mMainLayout;
private LinearLayout mSemiTransparentLayout;
private ListView mListView;
private Fragment mLastSetFragment;
private SettingsProvider mSettings;
private LinearLayout mLeftBar;
private TextView mTextViewClock;
private TextView mTextViewDate;
private Timer mTimer = null;
private boolean mOnResumeDirectlyAfterOnCreate = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// Get settings provider
mSettings = SettingsProvider.getInstance(this);
// Check language
Log.d(MainActivity.class.getName(), "Set locale in onCreate");
setLocale();
// Set flag indicating we are in oncreate
mOnResumeDirectlyAfterOnCreate = true;
// Now go on
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
// Get base linear layout
mMainLayout = (LinearLayout)findViewById(R.id.linearLayoutMain);
// Check if background image have to be set
WallpaperSelectDialog selectDialog = new WallpaperSelectDialog(this);
selectDialog.setWallpaper(false);
// Get linear layout for semi-transparent background
mSemiTransparentLayout = (LinearLayout) findViewById(R.id.linearLayoutSemiTransparentBackground);
// Get clock and date
mTextViewClock = (TextView)findViewById(R.id.textViewClock);
mTextViewDate = (TextView)findViewById(R.id.textViewDate);
// Get ListView
mListView = (ListView)findViewById(R.id.listView);
// Handle item click listener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d(MainActivity.class.getName(), "OnItemClickListener: clicked position " + position);
handleLeftBarItemSelection(parent, view, position, id);
}
});
// Handle item selected changes
mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.d(MainActivity.class.getName(), "OnItemSelectedListener: selected position " + position);
handleLeftBarItemSelection(parent, view, position, id);
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
// Set adapter
LeftBarItemsListAdapter actAdapter = new LeftBarItemsListAdapter(this);
mListView.setAdapter(actAdapter);
mListView.setSelection(0);
// Focus first item
mListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
try
{
// Remove listener
mListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Check if first icon have to be selected
mListView.requestFocusFromTouch();
mListView.setSelection(0);
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Failed to focus first left bar list item: \n" + errorReason);
}
}
});
// Check if left bar shall be hided
mLeftBar = (LinearLayout) findViewById(R.id.leftbar);
}
@Override
public void onResume()
{
// If not onResume directly after onCreate reset locale
if(!mOnResumeDirectlyAfterOnCreate)
{
Log.d(MainActivity.class.getName(), "Set locale again in onResume");
setLocale();
}
// Set date and time and start timer
setDateAndTime();
startTimer();
super.onResume();
}
@Override
public void onPause()
{
super.onPause();
// Stop update timer
stopTimer();
// Set back onResume directly after onCreate
mOnResumeDirectlyAfterOnCreate = false;
}
private void setActiveFragment(Fragment fragment)
{
try
{
// Check fragment type
if(fragment instanceof AppActivity)
{
// In app overview disable semi-transparent background
mSemiTransparentLayout.setBackgroundResource(android.R.color.transparent);
// Check if animation have to be changed
if(mSettings.getHideLeftBarInAppOverview())
{
mListView.setOnFocusChangeListener(new View.OnFocusChangeListener()
//mLeftBar.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
Log.d(MainActivity.class.getName(), "LeftBar focus changed to: hasFocus = " + hasFocus);
if (mLastSetFragment instanceof AppActivity)
{
Integer newWidth = 0;
if (hasFocus)
{
newWidth = Math.round(getResources().getDimension(R.dimen.leftbarwidth));
}
Log.d(MainActivity.class.getName(), "LeftBar new width = " + newWidth);
ResizeWidthAnimation anim = new ResizeWidthAnimation(mLeftBar, newWidth);
anim.setDuration(300);
mLeftBar.startAnimation(anim);
}
}
});
}
else
{
mListView.setOnFocusChangeListener(null);
}
}
else
{
// In all other fragments enable semi-transparent background if setting is set
if(mSettings.getShowBackgroundForAppNames())
{
mSemiTransparentLayout.setBackgroundResource(R.color.semitransparentbackground_medium);
}
}
// Set fragment as lastSetFragment
mLastSetFragment = fragment;
// Initiate fragment change
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.item_detail_container, fragment);
fragmentTransaction.commit();
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Set Active Fragment: Exception: \n" + errorReason);
}
}
/**
* Handles selection or click of the left-bar items..
* @param parent
* @param view
* @param position
* @param id
*/
private void handleLeftBarItemSelection(AdapterView<?> parent, View view, int position, long id)
{
// Get instance of selected item and set as current fragment
try
{
Log.d(MainActivity.class.getName(), "HandleLeftBarItemSelection: selected position " + position);
// Create fragment
Fragment fragment = (Fragment)Class.forName(((LeftBarItemsListAdapter)parent.getAdapter()).getItem(position).className).getConstructor().newInstance();
// Set fragment
setActiveFragment(fragment);
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "HandleLeftBarItemSelection: Exception: \n" + errorReason);
}
}
private void setLocale()
{
// Check language
String lang = mSettings.getLanguage();
if(lang != null && !lang.equals("") && SettingsProvider.LANG.containsKey(lang))
{
try
{
Locale newLocale;
// If lang is <= 3 chars, it is a language code
if(lang.length() <= 3)
{
newLocale = new Locale(lang);
}
else
{
newLocale = (Locale) Locale.class.getField(lang).get(Locale.getDefault());
}
Locale.setDefault(newLocale);
Configuration config = new Configuration(getResources().getConfiguration());
config.locale = newLocale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Failed to load custom language setting: \n" + errorReason);
}
}
}
/**
* Start the timer to update clock
*/
private void startTimer()
{
mTimer = new Timer ();
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
setDateAndTime();
}
};
// Schedule task every full minute
Integer everyXminute = 1;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Integer toBeAdded = everyXminute - (calendar.get(Calendar.MINUTE) % everyXminute);
if(toBeAdded == 0)
{
toBeAdded = everyXminute;
}
calendar.add(Calendar.MINUTE, toBeAdded);
mTimer.schedule(timerTask, calendar.getTime(), 1000*60*everyXminute);
Log.d(MainActivity.class.getName(), "Update Time started");
}
/**
* Stops the timer to update clock
*/
private void stopTimer()
{
if(mTimer != null)
{
mTimer.cancel();
mTimer = null;
}
Log.d(MainActivity.class.getName(), "Update Time stopped");
}
/**
* Sets the current time and date
*/
private void setDateAndTime()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Get current date time
Date actDateTime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS");
Log.d(MainActivity.class.getName(), "Update Time to " + sdf.format(actDateTime));
// Set clock
// DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, getResources().getConfiguration().locale.getDefault());
// if(android.text.format.DateFormat.is24HourFormat(MainActivity.this))
// {
// }
// mTextViewClock.setText(timeFormat.format(actDateTime));
mTextViewClock.setText(DateUtils.formatDateTime(MainActivity.this, actDateTime.getTime(), DateUtils.FORMAT_SHOW_TIME));
// Set date
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, getResources().getConfiguration().locale);
mTextViewDate.setText(dateFormat.format(actDateTime));
}
});
}
/**
* @param drawable Set this drawable as background image
*/
public void setBackgroundImage(Drawable drawable)
{
mMainLayout.setBackground(drawable);
}
public Integer getBackgroundWidth()
{
return mMainLayout.getWidth();
}
public Integer getBackgroundHeight()
{
return mMainLayout.getHeight();
}
/** Trigger update */
public void triggerUpdate()
{
try
{
UpdaterActivity fragment = (UpdaterActivity)Class.forName(UpdaterActivity.class.getName()).getConstructor().newInstance();
fragment.triggerUpdateOnStartup();
setActiveFragment(fragment);
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public boolean onKeyDown(int keycode, KeyEvent e)
{
// Check if there is a receiver fragment
if(mLastSetFragment != null && mLastSetFragment instanceof CustomFragment)
{
CustomFragment actFragment = (CustomFragment)mLastSetFragment;
Boolean retVal = ((CustomFragment) mLastSetFragment).onKeyDown(keycode, e);
if(retVal)
{
return true;
}
}
return super.onKeyDown(keycode, e);
}
@Override
public void onBackPressed()
{
boolean isHandled = false;
// Check if there is a receiver fragment
if(mLastSetFragment != null && mLastSetFragment instanceof CustomFragment)
{
CustomFragment actFragment = (CustomFragment)mLastSetFragment;
isHandled = ((CustomFragment) mLastSetFragment).onBackPressed();
}
// Check if back-pressed is already handled
if(!isHandled)
{
// If the fragment does not handle the back-button and AppStarter is not
// on the main-app-view, open main-app-view
if(!(mLastSetFragment instanceof AppActivity))
{
mListView.setSelection(0);
}
}
// Prevent default by not calling super class..
}
}
@@ -0,0 +1,235 @@
package com.sidequest.launcher.gui;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.widget.Toast;
import java.util.List;
import java.util.Map;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppInfo;
import com.sidequest.launcher.tools.KodiUpdater;
import com.sidequest.launcher.tools.SettingsProvider;
import com.sidequest.launcher.tools.Tools;
/**
* Preferences activity
*/
public class PreferenceActivity extends PreferenceFragment
{
SettingsProvider mSettings = SettingsProvider.getInstance(this.getActivity());
SharedPreferences.OnSharedPreferenceChangeListener mSharedPreferenceListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Thread readValuesThread = new Thread(new Runnable()
{
@Override
public void run()
{
mSettings.readValues(true);
}
});
readValuesThread.start();
}
};
public PreferenceActivity()
{
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
// {
// View rootView = super.onCreateView(inflater, container, savedInstanceState);
//
// // Set padding to settings view:
// Integer pad = Math.round(getActivity().getResources().getDimension(R.dimen.settingspadding));
// Integer padBottom = Math.round(getActivity().getResources().getDimension(R.dimen.settingspadding_bottom));
// if (rootView != null)
// {
// rootView.setPadding(pad,pad,pad,padBottom);
// }
//
// return rootView;
// }
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencesactivity);
InstalledAppsAdapter actAppsAdapter = new InstalledAppsAdapter(getActivity(), true, false);
List<AppInfo> actApps = actAppsAdapter.getAppList();
CharSequence[] entries = new CharSequence[actApps.size() + 1];
CharSequence[] entryValues = new CharSequence[actApps.size() + 1];
entries[0] = " - No Action - ";
entryValues[0] = "";
for (Integer i = 1; i < actApps.size() + 1; i++)
{
AppInfo actApp = actApps.get(i - 1);
entries[i] = actApp.getDisplayName();
entryValues[i] = actApp.packageName;
}
CharSequence[] langEntries = new CharSequence[SettingsProvider.LANG.size()];
CharSequence[] langValues = new CharSequence[SettingsProvider.LANG.size()];
Integer counter = 0;
for (Map.Entry<String, String> entry : SettingsProvider.LANG.entrySet())
{
langEntries[counter] = entry.getValue();
langValues[counter] = entry.getKey();
counter++;
}
ListPreference languagePreference = (ListPreference) findPreference("prefLanguage");
languagePreference.setEntries(langEntries);
languagePreference.setEntryValues(langValues);
languagePreference.setDefaultValue(mSettings.getLanguage());
languagePreference.setValue(mSettings.getLanguage());
languagePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
// Check if value has really changed:
if (!mSettings.getLanguage().equals(newValue.toString()))
{
// Force reload settings
mSettings.setLanguage(newValue.toString());
// Restart whole app
Tools.doRestart(PreferenceActivity.this.getActivity());
}
return true;
}
});
// ListPreference prefKodiUpdatePolicy = (ListPreference) findPreference("prefKodiUpdatePolicy");
// prefKodiUpdatePolicy.setEntries(KodiUpdater.UPDATE_POLICY.toArray(new CharSequence[KodiUpdater.UPDATE_POLICY.size()]));
// prefKodiUpdatePolicy.setEntryValues(KodiUpdater.UPDATE_POLICY.toArray(new CharSequence[KodiUpdater.UPDATE_POLICY.size()]));
// prefKodiUpdatePolicy.setDefaultValue(mSettings.getKodiUpdatePolicy());
// prefKodiUpdatePolicy.setValue(mSettings.getKodiUpdatePolicy());
InstalledAppsAdapter actHiddenAppsAdapter = new InstalledAppsAdapter(getActivity(), true, true);
List<AppInfo> actHiddenApps = actHiddenAppsAdapter.getAppList();
CharSequence[] hiddenEntries = new CharSequence[actHiddenApps.size()];
CharSequence[] hiddenEntryValues = new CharSequence[actHiddenApps.size()];
for (Integer i = 0; i < actHiddenApps.size(); i++)
{
AppInfo actApp = actHiddenApps.get(i);
hiddenEntries[i] = actApp.getDisplayName();
hiddenEntryValues[i] = actApp.packageName;
}
MultiSelectListPreference hiddenAppsList = (MultiSelectListPreference) findPreference("prefHiddenApps");
hiddenAppsList.setEntries(hiddenEntries);
hiddenAppsList.setEntryValues(hiddenEntryValues);
hiddenAppsList.setDefaultValue(mSettings.getHiddenApps());
EditTextPreference appIconSize = (EditTextPreference) findPreference("prefAppIconSize");
appIconSize.setDefaultValue(mSettings.getAppIconSize().toString());
appIconSize.setText(mSettings.getAppIconSize().toString());
appIconSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
return mSettings.setAppIconSize(newValue, true);
}
});
Preference prefWallpaper = (Preference) findPreference("prefWallpaper");
prefWallpaper.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
WallpaperSelectDialog wallpaperSelector = new WallpaperSelectDialog((MainActivity) PreferenceActivity.this.getActivity());
wallpaperSelector.show();
return false;
}
});
Preference prefExportCurrentSettings = (Preference) findPreference("prefExportCurrentSettings");
prefExportCurrentSettings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
Toast.makeText(getActivity(), Tools.settingsExport(getActivity()), Toast.LENGTH_SHORT).show();
return false;
}
});
Preference prefImportCurrentSettings = (Preference) findPreference("prefImportCurrentSettings");
prefImportCurrentSettings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
String retVal = Tools.settingsImport(getActivity());
if (retVal == null)
{
Toast.makeText(getActivity(), "Settings imported successful, restart..", Toast.LENGTH_SHORT).show();
Thread restarter = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(2000);
}
catch (Exception ignore)
{
}
Tools.doRestart(getActivity());
}
});
restarter.start();
} else
{
Toast.makeText(getActivity(), retVal, Toast.LENGTH_SHORT).show();
}
return false;
}
});
}
@Override
public void onPause()
{
super.onPause();
PreferenceManager.getDefaultSharedPreferences(getActivity()).unregisterOnSharedPreferenceChangeListener(mSharedPreferenceListener);
// Force read-settings
mSettings.readValues(true);
}
@Override
public void onResume()
{
super.onResume();
PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(mSharedPreferenceListener);
}
}
@@ -0,0 +1,44 @@
package com.sidequest.launcher.gui;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
/**
* Animate change of width
* https://stackoverflow.com/questions/16641539/animate-change-width-of-android-relativelayout
*/
public class ResizeWidthAnimation extends Animation
{
private int mWidth;
private int mStartWidth;
private View mView;
public ResizeWidthAnimation(View view, int width)
{
mView = view;
mWidth = width;
mStartWidth = view.getWidth();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
int newWidth = mStartWidth + (int) ((mWidth - mStartWidth) * interpolatedTime);
mView.getLayoutParams().width = newWidth;
mView.requestLayout();
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight)
{
super.initialize(width, height, parentWidth, parentHeight);
}
@Override
public boolean willChangeBounds()
{
return true;
}
}
@@ -0,0 +1,117 @@
package com.sidequest.launcher.gui;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ListView;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppStarterUpdater;
import com.sidequest.launcher.tools.SettingsProvider;
import com.sidequest.launcher.tools.Updater;
/**
* Shows the updates for all available installable apps including AppStarter itself
*/
public class UpdaterActivity extends Fragment
{
/** Instance of settings provider */
private SettingsProvider mSettings = SettingsProvider.getInstance(getActivity());
/** ListView to show all updateable apps */
private ListView mListView;
/** Indicates if update shall be triggered directly */
private Boolean mTriggerUpdate = false;
/** Updater apps adapter */
UpdaterAppsAdapter mUpdaterAppsAdapter;
/** Mandatory for fragment initation */
public UpdaterActivity(){ }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.updateractivity, container, false);
// Get ListView
mListView = (ListView) rootView.findViewById(R.id.listView);
// Set updateable apps adapter
mUpdaterAppsAdapter = new UpdaterAppsAdapter(this.getActivity());
mListView.setAdapter(mUpdaterAppsAdapter);
// Make buttons useable
mListView.setItemsCanFocus(true);
mListView.setFocusable(false);
mListView.setFocusableInTouchMode(false);
mListView.setClickable(false);
// Trigger update mechanism when first view is ready..
mListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
try
{
// Remove listener
mListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(mTriggerUpdate)
{
mTriggerUpdate = false;
Updater actAppStarterUpdater = (Updater) mUpdaterAppsAdapter.getItem(0);
if(actAppStarterUpdater != null && actAppStarterUpdater instanceof AppStarterUpdater)
{
actAppStarterUpdater.DialogHandler.performUpdate();
}
}
}
catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Failed to trigger update directly: \n" + errorReason);
}
}
});
return rootView;
}
/** Trigger update programmtically */
public void triggerUpdateOnStartup()
{
mTriggerUpdate = true;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public void onPause()
{
super.onPause();
}
@Override
public void onResume()
{
super.onResume();
mUpdaterAppsAdapter.notifyDataSetChanged();
}
}
@@ -0,0 +1,174 @@
package com.sidequest.launcher.gui;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppStarterUpdater;
import com.sidequest.launcher.tools.KodiUpdater;
import com.sidequest.launcher.tools.SPMCUpdater;
import com.sidequest.launcher.tools.SettingsProvider;
import com.sidequest.launcher.tools.Updater;
/**
* Adapter that lists all installed apps
*/
public class UpdaterAppsAdapter extends BaseAdapter
{
Activity mActivity;
private List<Updater> mUpdaterList;
/**
* Create new UpdaterAppsadapter
*/
public UpdaterAppsAdapter(Activity activity)
{
// Set context
mActivity = activity;
// Set list of updaters
mUpdaterList = new ArrayList<>();
mUpdaterList.add(new AppStarterUpdater());
mUpdaterList.add(new KodiUpdater(activity));
mUpdaterList.add(new SPMCUpdater());
}
/**
* @return Count of installed apps
*/
public int getCount()
{
return mUpdaterList.size();
}
/**
* @param position Position of item to be returned
* @return Item on position
*/
public Object getItem(int position)
{
return mUpdaterList.get(position);
}
/**
* Currently not used..
*/
public long getItemId(int position)
{
return position;
}
/**
* @return View of the given position
*/
public View getView(int position, View convertView, ViewGroup parent)
{
// Get act updater
final Updater actUpdater = mUpdaterList.get(position);
// Inflate layout
View rootView;
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rootView = new View(mActivity);
rootView = inflater.inflate(R.layout.appupdateritemlayout, parent, false);
}
else
{
rootView = (View) convertView;
}
// Set title
TextView textViewTitle = (TextView) rootView.findViewById(R.id.title);
textViewTitle.setText(actUpdater.getAppName());
// Set current version
TextView textViewCurrentVersion = (TextView) rootView.findViewById(R.id.currentVersion);
textViewCurrentVersion.setText(actUpdater.getCurrentVersion(mActivity));
// Set latest version
final TextView textViewLatestVersion = (TextView) rootView.findViewById(R.id.latestVersion);
String latestVersion = actUpdater.getLatestVersion();
if(latestVersion == null)
{
latestVersion = mActivity.getResources().getString(R.string.update_hitcheckfor);
}
textViewLatestVersion.setText(latestVersion);
// Create an UpdaterDialogHandler
final UpdaterDialogHandler updaterDialogHandler = new UpdaterDialogHandler(mActivity, actUpdater);
actUpdater.DialogHandler = updaterDialogHandler;
updaterDialogHandler.setCheckForUpdateFinishedListener(new Updater.OnCheckForUpdateFinishedListener()
{
@Override
public void onCheckForUpdateFinished(String message)
{
if (actUpdater.getLatestVersion() != null)
{
if (actUpdater.isVersionNewer(actUpdater.getCurrentVersion(mActivity), actUpdater.getLatestVersion()))
{
textViewLatestVersion.setText(actUpdater.getLatestVersion() + " - " + mActivity.getResources().getString(R.string.update_foundnew));
if (actUpdater instanceof AppStarterUpdater)
{
AppActivity.LATEST_APP_VERSION = actUpdater.getLatestVersion();
}
} else
{
textViewLatestVersion.setText(actUpdater.getLatestVersion() + " - " + mActivity.getResources().getString(R.string.update_foundnotnew));
}
} else
{
textViewLatestVersion.setText(message);
}
}
});
// Set the button onclicks
Button checkUpdateButton = (Button) rootView.findViewById(R.id.buttonCheckForUpdate);
checkUpdateButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
updaterDialogHandler.checkForUpdate();
}
});
Button updateButton = (Button) rootView.findViewById(R.id.buttonUpdate);
updateButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
updaterDialogHandler.performUpdate();
if(actUpdater instanceof AppStarterUpdater)
{
SettingsProvider settings = SettingsProvider.getInstance(mActivity);
settings.setHaveUpdateSeen(false);
}
}
});
if(rootView.getResources().getString(R.string.not_installed).equals(textViewCurrentVersion.getText()))
{
// App is not installed, change update to install text
updateButton.setText(rootView.getResources().getString(R.string.install));
}
return rootView;
}
}
@@ -0,0 +1,116 @@
package com.sidequest.launcher.gui;
import android.app.Activity;
import android.app.ProgressDialog;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.AppStarterUpdater;
import com.sidequest.launcher.tools.Updater;
/**
* Handles the update-dialogs in case of an update
*/
public class UpdaterDialogHandler
{
/** Updater of the dialog handler */
private Updater mUpdater;
/** Context of the current dialog handler */
private Activity mActivity;
/** Check for update progress */
ProgressDialog mCheckForUpdateProgress = null;
/** Update progress */
ProgressDialog mUpdateProgress = null;
/** Listener for checkforupdate finished event */
Updater.OnCheckForUpdateFinishedListener mCheckForUpdateFinishedListener = null;
public UpdaterDialogHandler(Activity activity, Updater updater)
{
mActivity = activity;
mUpdater = updater;
mUpdater.setOnCheckForUpdateFinishedListener(mOnCheckForUpdateFinishedListener);
mUpdater.setOnUpdateProgressListener(mOnUpdateProgressListener);
}
public void setCheckForUpdateFinishedListener(Updater.OnCheckForUpdateFinishedListener listener)
{
mCheckForUpdateFinishedListener = listener;
}
public void checkForUpdate()
{
mCheckForUpdateProgress = ProgressDialog.show(mActivity, mActivity.getResources().getString(R.string.update_checkfortitle), mActivity.getResources().getString(R.string.update_checkfordesc), true);
mUpdater.checkForUpdate();
}
public void performUpdate()
{
mUpdateProgress = new ProgressDialog(mActivity);
mUpdateProgress.setMessage(mActivity.getResources().getString(R.string.update_checkformessage));
mUpdateProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mUpdateProgress.setCancelable(false);
mUpdateProgress.setProgress(0);
mUpdateProgress.show();
mUpdater.update(mActivity);
}
/** Handle check for update */
Updater.OnCheckForUpdateFinishedListener mOnCheckForUpdateFinishedListener = new AppStarterUpdater.OnCheckForUpdateFinishedListener()
{
@Override
public void onCheckForUpdateFinished(final String message)
{
mActivity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (mCheckForUpdateProgress != null)
{
mCheckForUpdateProgress.dismiss();
mCheckForUpdateProgress = null;
}
mCheckForUpdateFinishedListener.onCheckForUpdateFinished(message);
}
});
}
};
/** Handle update progress */
Updater.OnUpdateProgressListener mOnUpdateProgressListener = new AppStarterUpdater.OnUpdateProgressListener()
{
@Override
public void onUpdateProgress(final Boolean isError,final Integer percent, final String message)
{
mActivity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (isError)
{
mUpdateProgress.setProgress(100);
mUpdateProgress.setMessage(message);
mUpdateProgress.setCancelable(true);
} else
{
mUpdateProgress.setProgress(percent);
mUpdateProgress.setMessage(message);
if (percent >= 100)
{
mUpdateProgress.setCancelable(true);
mUpdateProgress.dismiss();
}
}
}
});
}
};
}
@@ -0,0 +1,173 @@
package com.sidequest.launcher.gui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import com.sidequest.launcher.R;
import com.sidequest.launcher.tools.Tools;
/**
* Created by luki on 28.06.15.
*/
public class WallpaperSelectDialog
{
/** Current MainActivity */
MainActivity mMainActivity;
/** Current Wallpaper Path */
File mWallpaperPath;
public WallpaperSelectDialog(MainActivity mainActivity)
{
mMainActivity = mainActivity;
mWallpaperPath = new File(mMainActivity.getApplicationInfo().dataDir, "wallpaper.png");
}
public void setWallpaper(Boolean forceError)
{
try
{
if(!forceError)
{
if(!mWallpaperPath.exists())
{
return;
}
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mWallpaperPath.getAbsolutePath(), bmOptions);
BitmapDrawable drawable = new BitmapDrawable(mMainActivity.getResources(), bitmap);
mMainActivity.setBackgroundImage(drawable);
}
catch(Exception e)
{
Toast.makeText(mMainActivity, "Could not set wallpaper", Toast.LENGTH_SHORT).show();
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(WallpaperSelectDialog.class.getName(), "Failed to set background: \n" + errorReason);
}
}
public void show()
{
AlertDialog.Builder builder = new AlertDialog.Builder(mMainActivity);
builder.setTitle("JPG/PNG - 1920x1080px");
List<String> items = new ArrayList<String>();
if(mWallpaperPath.exists())
{
items.add(mMainActivity.getResources().getString(R.string.remove_wallpaper));
}
items.add(mMainActivity.getResources().getString(R.string.select_wallpaper));
final String[] itemList = items.toArray(new String[items.size()]);
builder.setItems(itemList, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
dialog.dismiss();
String itemChosen = itemList[which];
if (itemChosen == mMainActivity.getResources().getString(R.string.remove_wallpaper))
{
deleteWallpaper();
}
else if(itemChosen == mMainActivity.getResources().getString(R.string.select_wallpaper))
{
showFileSelectorDialog();
}
}
});
Dialog dialog = builder.show();
dialog.show();
}
private void deleteWallpaper()
{
if(mWallpaperPath.exists())
{
mWallpaperPath.delete();
Tools.doRestart(mMainActivity);
}
}
private void showFileSelectorDialog()
{
File mPath = Environment.getExternalStorageDirectory();
FileDialog fileDialog = new FileDialog(mMainActivity, mPath);
fileDialog.setFileEndsWith(new String[]{".jpg", ".jpeg", ".png"});
fileDialog.addFileListener(new FileDialog.FileSelectedListener()
{
public void fileSelected(File file)
{
WallpaperSelectDialog.this.handleFileSelected(file);
}
});
//fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
// public void directorySelected(File directory) {
// Log.d(getClass().getName(), "selected dir " + directory.toString());
// }
//});
//fileDialog.setSelectDirectoryOption(false);
fileDialog.showDialog();
}
private void handleFileSelected(File file)
{
// Now we try to resize and set this file
try
{
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions);
// Resize image
bitmap = Tools.resizeBitmapToFit(bitmap, mMainActivity.getBackgroundWidth(), mMainActivity.getBackgroundHeight());
File dir = mWallpaperPath.getParentFile();
if(!dir.exists())
{
dir.mkdirs();
}
if(mWallpaperPath.exists())
{
mWallpaperPath.delete();
}
FileOutputStream fOut = new FileOutputStream(mWallpaperPath);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
// Now try to load this one
setWallpaper(true);
}
catch(Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(MainActivity.class.getName(), "Failed to set background: \n" + errorReason);
}
}
}
@@ -0,0 +1,16 @@
package com.sidequest.launcher.tests;
import android.test.InstrumentationTestCase;
import com.sidequest.launcher.tools.KodiUpdater;
/**
* Created by attila.szasz on 23-Oct-15.
*/
public class KodiTests extends InstrumentationTestCase {
public void testCheckForUpdate() throws Exception {
KodiUpdater mKodiUpdater = new KodiUpdater(this.getInstrumentation().getContext());
mKodiUpdater.checkForUpdate(true);
assertNotNull("Latest version should not be null", mKodiUpdater.getLatestVersion());
}
}
@@ -0,0 +1,44 @@
package com.sidequest.launcher.tools;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.drawable.Drawable;
/**
* Container to hold app informations
*/
public class AppInfo extends ApplicationInfo
{
/** The current context */
Context mContext;
/**
* @param app App to be hold
*/
public AppInfo(Context context, ApplicationInfo app)
{
super(app);
mContext = context;
}
/**
* @return Name to be displayed
*/
public String getDisplayName()
{
String retVal = this.loadLabel(mContext.getPackageManager()).toString();
if(retVal == null || retVal.equals(""))
{
retVal = packageName;
}
return retVal;
}
/**
* @return Icon to be displayed
*/
public Drawable getDisplayIcon()
{
return this.loadIcon(mContext.getPackageManager());
}
}
@@ -0,0 +1,144 @@
package com.sidequest.launcher.tools;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.sidequest.launcher.gui.InstalledAppsAdapter;
/**
* Provides methods to start apps
*/
public class AppStarter
{
/** Name of the launcher package */
private static String mLauncherPackageName = null;
/** Thread to start and watch if correct action is happening */
private static Thread mStartAndWatchThread = null;
private static Object mSyncObj = new Object();
public static void stopWatchThread()
{
synchronized (mSyncObj)
{
Log.d(AppStarter.class.getName(), "Stop watch thread");
try
{
if(mStartAndWatchThread != null && mStartAndWatchThread.isAlive())
{
mStartAndWatchThread.interrupt();
mStartAndWatchThread.join();
mStartAndWatchThread = null;
Log.d(AppStarter.class.getName(), "Watchthread stopped");
}
else
{
Log.d(AppStarter.class.getName(), "Watchthread was not alive, nothing to be done.");
}
}
catch(Exception e)
{
Log.d(AppStarter.class.getName(), "Exception while stopping watchthread: \n" + e.getMessage());
}
}
}
/**
* Starting an app by its package-name
* @param context Context in that the app shall be started.
* @param packageName Name of the apps package
* @param isClickAction Indicates if this method is initiated by a click-action
*/
public static void startAppByPackageName(final Context context, String packageName, Boolean isClickAction, Boolean isStartupAction, Boolean isClearPreviousInstancesForced)
{
try
{
// If currently a watchdog thread is running, stop it first
stopWatchThread();
synchronized (mSyncObj)
{
if (packageName != null && !packageName.equals(""))
{
// Prepare the intent
final Intent launchIntent = InstalledAppsAdapter.getLaunchableIntentByPackageName(context, packageName);
if (isStartupAction || isClearPreviousInstancesForced)
{
// Start in new Task if startup -> perhaps prevents weird colors of kodi
// that some users reported..
Log.d(AppStarter.class.getName(), "Using FLAG_ACTIVITY_CLEAR_TASK: isStartupAction=" + isStartupAction.toString() + ", isClearPreviousInstancesForced=" + isClearPreviousInstancesForced.toString());
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
// Launch the intent
Log.d(AppStarter.class.getName(), "Starting launcher activity of package: " + packageName);
context.startActivity(launchIntent);
}
}
}
catch(Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(AppStarter.class.getName(), "Failed to launch activity: \n" + errorReason);
}
}
/**
* Start settings view by packagename
* @param context
* @param packageName
*/
public static void startSettingsViewByPackageName(Context context, String packageName)
{
try
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package", packageName, null));
context.startActivity(intent);
}
catch(Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(AppStarter.class.getName(), "Failed to launch settings-activity: \n" + errorReason);
}
}
/**
* Uses package manager to find the package name of the device launcher. Usually this package
* is "com.android.launcher" but can be different at times. This is a generic solution which
* works on all platforms.`
*/
public static synchronized String getLauncherPackageName(Context context)
{
// We only need to find the launcher package once as it should not change
if(mLauncherPackageName == null)
{
// Create launcher Intent
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
// Use PackageManager to get the launcher package name
PackageManager pm = context.getPackageManager();
ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
mLauncherPackageName = resolveInfo.activityInfo.packageName;
}
return mLauncherPackageName;
}
}
@@ -0,0 +1,86 @@
package com.sidequest.launcher.tools;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.Scanner;
/**
* Update class for AppStarter
*/
public class AppStarterUpdater extends Updater
{
/** Update URL where updated versions are found */
private String mUpdateUrl = "https://api.github.com/repos/sphinx02/AppStarter/releases";
@Override
public String getAppName()
{
return "AppStarter";
}
@Override
public String getPackageName(Context context)
{
return context.getApplicationInfo().packageName;
}
@Override
public Boolean isVersionNewer(String oldVersion, String newVersion)
{
// Use standard check
return isVersionNewerStandardCheck(oldVersion, newVersion);
}
@Override
protected void updateLatestVersionAndApkDownloadUrl() throws Exception
{
// Build the url
URL url = new URL(mUpdateUrl);
// Read from the URL
Scanner scan = new Scanner(url.openStream());
StringBuilder str = new StringBuilder();
while (scan.hasNext())
{
str.append(scan.nextLine());
}
scan.close();
// build a JSON object
JSONArray obj = new JSONArray(str.toString());
if(obj.length() <= 0)
{
throw new JSONException("No content found");
}
JSONObject latestRelease = obj.getJSONObject(0);
String tagName = latestRelease.getString("tag_name");
if(tagName == null || tagName.equals(""))
{
throw new JSONException("Latest release tag name is empty");
}
mLatestVersion = tagName;
// Search for apk-download url
JSONArray assets = latestRelease.getJSONArray("assets");
for(Integer i = 0; i < assets.length(); i++)
{
JSONObject currentAsset = assets.getJSONObject(i);
String downloadUrl = currentAsset.getString("browser_download_url");
if(downloadUrl.startsWith("https://github.com/sphinx02/") && downloadUrl.endsWith(".apk"))
{
mApkDownloadUrl = downloadUrl;
break;
}
}
if(mApkDownloadUrl == null)
{
throw new JSONException("No .apk download URL found");
}
}
}
@@ -0,0 +1,237 @@
package com.sidequest.launcher.tools;
import android.content.Context;
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class KodiUpdater extends Updater
{
public static List<String> UPDATE_POLICY = new ArrayList<String>()
{
{
add("Stable");
add("Beta and RC");
add("Nightly Builds");
}
};
/** Update URL where updated versions are found */
private String mUpdateUrl = "http://mirrors.kodi.tv/releases/android/arm/";
/** Update URL for nightly versions */
private String mUpdateUrlNightly = "http://mirrors.kodi.tv/nightlies/android/arm/";
/** Current context */
private Context mContext;
/** Instance of settings */
private SettingsProvider mSettings;
/** Constructor to get Context */
public KodiUpdater(Context context)
{
mContext = context;
mSettings = SettingsProvider.getInstance(context);
}
@Override
public String getAppName()
{
return "Kodi";
}
@Override
public String getPackageName(Context context)
{
return "org.xbmc.kodi";
}
@Override
public Boolean isVersionNewer(String oldVersion, String newVersion)
{
// // Kodi versiong String can have additional RC-Version which is lower
// // than equal version String without RC-Version
// Boolean retVal = false;
//
// // Start do-while-false to be able to break out any time
// do
// {
// // First prepare Strings
// String workOldVersion = oldVersion.replace("_", "-").toUpperCase();
// String workNewVersion = newVersion.replace("_", "-").toUpperCase();
//
// // If Strings are now equal, version is not newer
// if(workOldVersion.equals(workNewVersion))
// {
// retVal = false;
// break;
// }
//
// // Split version Strings
// String[] splitOldVersion = workOldVersion.split("-");
// String[] splitNewVersion = workNewVersion.split("-");
//
// // We should have at least one version string
// if(splitOldVersion.length < 1 || splitNewVersion.length < 1)
// {
// retVal = false;
// break;
// }
//
// // If the first part (the normal version string) is identical
// // we have to perform further tests
// if(splitOldVersion[0].equals(splitNewVersion[0]))
// {
// // If only the oldversion string has the rc-part,
// // the version is newer as no rc-part is newer than any rc-part
// if(splitOldVersion.length == 2 && splitNewVersion.length == 1)
// {
// retVal = true;
// break;
// }
//
// // If both have the rc-part, we have to compare the rc part
// if(splitOldVersion.length == 2 && splitNewVersion.length == 2)
// {
// try
// {
// String oldRc = splitOldVersion[1];
// String newRc = splitNewVersion[1];
//
// if(oldRc.startsWith("RC") && newRc.startsWith("RC"))
// {
// oldRc = oldRc.substring(2, oldRc.length());
// newRc = newRc.substring(2, newRc.length());
// Integer oldInt = Integer.valueOf(oldRc);
// Integer newInt = Integer.valueOf(newRc);
// if(newInt > oldInt)
// {
// retVal = true;
// break;
// }
// }
// else if(oldRc.startsWith("BETA") && newRc.startsWith("RC"))
// {
// retVal = true;
// }
// }
// catch(Exception ignore){}
// break;
// }
// }
//
// // Else we use the standard check for the main-version part
// retVal = isVersionNewerStandardCheck(splitOldVersion[0], splitNewVersion[0]);
//
// }
// while(false);
// Too complex, we simply check if the versions are equal or not
Boolean retVal = false;
String workOldVersion = oldVersion.replace("_", "-").toUpperCase();
String workNewVersion = newVersion.replace("_", "-").toUpperCase();
if(!workOldVersion.equals(workNewVersion))
{
retVal = true;
}
return retVal;
}
@Override
protected void updateLatestVersionAndApkDownloadUrl() throws Exception
{
String updatePolicy = mSettings.getKodiUpdatePolicy();
String updateUrl = mUpdateUrl;
Log.d("KODI-UPDATER", "Policy: " + updatePolicy);
if(updatePolicy.equals(UPDATE_POLICY.get(2)))
{
// Change link to nightlies
updateUrl = mUpdateUrlNightly;
}
Document doc = Jsoup.connect(updateUrl).get();
Elements files = doc.select("#list tbody tr");
String latestApk = "";
for(int i = 0; i < files.size(); i++)
{
String foundApk = files.get(i).select("td").first().text();
Log.d("KODI-UPDATER", "Found: " + foundApk);
if(foundApk.toLowerCase().endsWith(".apk"))
{
if(updatePolicy.equals(UPDATE_POLICY.get(1)) || updatePolicy.equals(UPDATE_POLICY.get(2)))
{
// We use the first file with .apk ending
latestApk = foundApk;
break;
}
else
{
// We have to check if this is no RC, ALPHA, OR BETA
String replacedApkName = foundApk.replace("_", "-").toUpperCase();
String[] splitApkName = replacedApkName.split("-");
if(splitApkName.length < 4 || (!splitApkName[3].startsWith("RC") && !splitApkName[3].startsWith("BETA") && !splitApkName[3].startsWith("ALPHA")))
{
latestApk = foundApk;
break;
}
}
}
}
if(latestApk.equals(""))
{
throw new Exception("No apk found on: " + mUpdateUrl);
}
mApkDownloadUrl = updateUrl + latestApk;
mLatestVersion = getVersion(latestApk);
}
/**
* Get version from file name
* @param apkName file name to be parsedf
* @return Version string
*/
private static String getVersion(String apkName)
{
String retVal = null;
try
{
if(apkName != null && !apkName.equals(""))
{
// apkName = apkName
// .replace("kodi-", "")
// .replace("-Isengard", "")
// .replace("-Jarvis", "")
// .replace("_rc", "-RC")
// .replace("_alpha", "-ALPHA")
// .replace("-armeabi-v7a.apk", "");
// retVal = "v" + apkName;
// We try to split up the kodi apk name into parts
// and check the correct parts
String replacedApkName = apkName.replace("_", "-").toUpperCase();
String[] splitApkName = replacedApkName.split("-");
if(splitApkName.length >= 2)
{
retVal = "v" + splitApkName[1];
}
if(splitApkName.length >= 4 && splitApkName[3].startsWith("RC") || splitApkName[3].startsWith("BETA") || splitApkName[3].startsWith("ALPHA"))
{
retVal += "-" + splitApkName[3];
}
}
}
catch(Exception ignore) { }
return retVal;
}
}
@@ -0,0 +1,96 @@
package com.sidequest.launcher.tools;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.Scanner;
/**
* Handles updates for SPMC
*/
public class SPMCUpdater extends Updater
{
/** Update URL where updated versions are found */
private String mUpdateUrl = "https://api.github.com/repos/koying/SPMC/releases";
@Override
public String getAppName()
{
return "SPMC";
}
@Override
public String getPackageName(Context context)
{
return "com.semperpax.spmc16";
}
@Override
public Boolean isVersionNewer(String oldVersion, String newVersion)
{
// Use standard check
return isVersionNewerStandardCheck(oldVersion, newVersion);
}
@Override
public String getCurrentVersion(Context context)
{
return Tools.getCurrentAppVersion(context, getPackageName(context)).replace("-", ".");
}
@Override
protected void updateLatestVersionAndApkDownloadUrl() throws Exception
{
// Build the url
URL url = new URL(mUpdateUrl);
// Read from the URL
Scanner scan = new Scanner(url.openStream());
StringBuilder str = new StringBuilder();
while (scan.hasNext())
{
str.append(scan.nextLine());
}
scan.close();
// build a JSON object
JSONArray obj = new JSONArray(str.toString());
if(obj.length() <= 0)
{
throw new JSONException("No content found");
}
JSONObject latestRelease = obj.getJSONObject(0);
String tagName = latestRelease.getString("tag_name");
if(tagName == null || tagName.equals(""))
{
throw new JSONException("Latest release tag name is empty");
}
mLatestVersion = "v" + tagName.replaceAll("[^\\d.]", "");
// Search for apk-download url
JSONArray assets = latestRelease.getJSONArray("assets");
for(Integer i = 0; i < assets.length(); i++)
{
JSONObject currentAsset = assets.getJSONObject(i);
String downloadUrl = currentAsset.getString("browser_download_url");
if(downloadUrl.startsWith("https://github.com/koying/SPMC/releases")
&& downloadUrl.endsWith(".apk")
&& downloadUrl.toLowerCase().contains("arm")
&& !(downloadUrl.toLowerCase().contains("launcher")))
{
mApkDownloadUrl = downloadUrl;
break;
}
}
if(mApkDownloadUrl == null)
{
throw new JSONException("No .apk download URL found");
}
}
}
@@ -0,0 +1,402 @@
package com.sidequest.launcher.tools;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Semaphore;
import com.sidequest.launcher.R;
/**
* Settings Provider to store all Settins of the app
*/
public class SettingsProvider
{
/** Map of possible languages */
public static final Map<String, String> LANG = new LinkedHashMap<String, String>()
{{
// Key is the static field name of Locale (e.g. Locale.GERMAN or Locale.ENGLISH)
// Value is the displayed value for the settings
put("", "Auto");
put("GERMAN", "Deutsch");
put("ENGLISH", "English");
//put("hu", "Magyar");
put("ru", "Русский");
put("uk", "Українська");
}};
/** Private static singleton object */
private static SettingsProvider _instance;
/** Semaphore to limit readValues and writeValues access */
private static Semaphore mSemaphore = new Semaphore(1);
/** Synchronized singleton getter (Thread Safe) */
public static synchronized SettingsProvider getInstance (Context context)
{
if(SettingsProvider._instance == null)
{
SettingsProvider._instance = new SettingsProvider(context);
}
return SettingsProvider._instance;
}
/** Stored context */
Context mContext;
/** Instance of app-shared preferences */
SharedPreferences mPreferences;
/** Indicator for package-order */
final static String PACKAGEORDER = "packageorder_";
/** Indicates if settings are already loaded */
Boolean mIsLoaded = false;
/** Package-Order List */
List<String> mPackageOrder = new ArrayList<String>();
/** Language string */
String mLanguage = "";
/** Update policy of Kodi */
String mKodiUpdatePolicy = KodiUpdater.UPDATE_POLICY.get(0);
/** List of hidden apps */
Set<String> mHiddenAppsList = new HashSet<String>();
/** Show system apps */
Boolean mShowSystemApps = false;
/** Size of the app icons */
Integer mAppIconSize = 0;
/** Indicates if user have seen update but do not want to update */
Boolean mHaveUpdateSeen = false;
/** Automatically select first icon when switching to app-drawer */
Boolean mAutoSelectFirstIcon = true;
/** Indicates if the LeftBar is hided when on the app overview */
Boolean mHideLeftBarInAppOverview = false;
/** Indicates if app names in the app drawer are having a background */
Boolean mShowBackgroundForAppNames = false;
/** Create a the instace of SettingsProvider */
private SettingsProvider(Context context)
{
mContext = context;
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
/**
* Set order of packages for app-drawer
* @param packageOrder List of packagenames in correct order
*/
public void setPackageOrder(List<String> packageOrder)
{
mPackageOrder = packageOrder;
storeValues();
}
/**
* @return List of packagenames in last saved order
*/
public List<String> getPackageOrder()
{
readValues();
return mPackageOrder;
}
public void setHideLeftBarInAppOverview(Boolean value)
{
mHideLeftBarInAppOverview = value;
storeValues();
}
public Boolean getHideLeftBarInAppOverview()
{
readValues();
return mHideLeftBarInAppOverview;
}
public void setShowBackgroundForAppNames(Boolean value)
{
mShowBackgroundForAppNames = value;
storeValues();
}
public Boolean getShowBackgroundForAppNames()
{
readValues();
return mShowBackgroundForAppNames;
}
public void setHaveUpdateSeen(Boolean value)
{
mHaveUpdateSeen = value;
storeValues();
}
public Boolean getHaveUpdateSeen()
{
readValues();
return mHaveUpdateSeen;
}
public void setAutoSelectFirstIcon(Boolean value)
{
mAutoSelectFirstIcon = value;
storeValues();
}
public Boolean getAutoSelectFirstIcon()
{
readValues();
return mAutoSelectFirstIcon;
}
public void setKodiUpdatePolicy(String policy)
{
mKodiUpdatePolicy = policy;
storeValues();
}
public String getKodiUpdatePolicy()
{
readValues();
return mKodiUpdatePolicy;
}
public void setLanguage(String language)
{
mLanguage = language;
storeValues();
}
public String getLanguage()
{
readValues();
return mLanguage;
}
public void setHiddenApps(Set<String> hiddenApps)
{
mHiddenAppsList = hiddenApps;
storeValues();
}
public Set<String> getHiddenApps()
{
readValues();
return mHiddenAppsList;
}
public void setShowSystemApps(Boolean value)
{
mShowSystemApps = value;
storeValues();
}
public Boolean getShowSystemApps()
{
readValues();
return mShowSystemApps;
}
public Boolean setAppIconSize(Object appIconSize, Boolean simulate)
{
Boolean retVal = numberCheck(appIconSize, 0, 200);
if(!simulate && retVal)
{
setAppIconSize(Integer.valueOf(appIconSize.toString()));
}
return retVal;
}
public void setAppIconSize(Integer appIconSize)
{
mAppIconSize = appIconSize;
storeValues();
}
public Integer getAppIconSize()
{
readValues();
return mAppIconSize;
}
private boolean numberCheck(Object newValue, Integer min, Integer max)
{
Boolean retVal = false;
try
{
if(!newValue.toString().equals("") && newValue.toString().matches("\\d*") )
{
Integer value = Integer.valueOf(newValue.toString());
if(value >= min && value <= max)
{
retVal = true;
}
}
}
catch(Exception ignore){}
if(!retVal)
{
Toast.makeText(mContext, newValue + " " + mContext.getResources().getString(R.string.is_invalid_number), Toast.LENGTH_SHORT).show();
}
return retVal;
}
/**
* Read values from settings
*/
public void readValues()
{
readValues(false);
}
/**
* @param forceRead Force reading values from preferences
*/
public void readValues(Boolean forceRead)
{
try
{
// ATTENTION: NEVER CALL ONE OF THE GETTERS OR SETTERS IN HERE!
// Aquire semaphore
mSemaphore.acquire();
// Load only once (hold in singleton)
if (mIsLoaded && !forceRead)
{
mSemaphore.release();
return;
}
// PackageList
List<String> packageList = new ArrayList<String>();
Integer size = mPreferences.getInt(PACKAGEORDER + "size", 0);
for (Integer i = 0; i < size; i++)
{
String actKey = PACKAGEORDER + i.toString();
packageList.add(mPreferences.getString(actKey, null));
}
mPackageOrder = packageList;
// HideLeftBarInAppOverview
mHideLeftBarInAppOverview = mPreferences.getBoolean("prefHideLeftBarInAppOverview", mHideLeftBarInAppOverview);
// ShowBackgroundForAppNames
mShowBackgroundForAppNames = mPreferences.getBoolean("prefShowBackgroundForAppNames", mShowBackgroundForAppNames);
// Have update seen
mHaveUpdateSeen = mPreferences.getBoolean("prefHaveUpdateSeen", mHaveUpdateSeen);
// Auto select first icon
mAutoSelectFirstIcon = mPreferences.getBoolean("prefAutoSelectFirstIcon", mAutoSelectFirstIcon);
// HiddenApps-List
mHiddenAppsList = mPreferences.getStringSet("prefHiddenApps", mHiddenAppsList);
// Show sys apps
mShowSystemApps = mPreferences.getBoolean("prefShowSysApps", mShowSystemApps);
// lang
mLanguage = mPreferences.getString("prefLanguage", mLanguage);
// Kodi update policy
mKodiUpdatePolicy = mPreferences.getString("prefKodiUpdatePolicy", mKodiUpdatePolicy);
// App icon size
String pref = mPreferences.getString("prefAppIconSize", mAppIconSize.toString());
if(setAppIconSize(pref, true))
{
mAppIconSize = Integer.valueOf(pref);
}
// Set is loaded flag
mIsLoaded = true;
}
catch(Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(SettingsProvider.class.getName(), "Exception while reading settings: \n" + errorReason);
}
mSemaphore.release();
}
/**
* Store values to settings
*/
public void storeValues()
{
try
{
// ATTENTION: NEVER CALL ONE OF THE GETTERS OR SETTERS IN HERE!
// Aquire semaphore
mSemaphore.acquire();
// Get editor, clear editor and save new values
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
// PackageList
editor.putInt(PACKAGEORDER + "size", mPackageOrder.size());
for (Integer i = 0; i < mPackageOrder.size(); i++)
{
String actKey = PACKAGEORDER + i.toString();
editor.remove(actKey);
editor.putString(actKey, mPackageOrder.get(i));
}
// BackgroundObserverEnabled
editor.putBoolean("prefHideLeftBarInAppOverview", mHideLeftBarInAppOverview);
// ShowBackgroundForAppNames
editor.putBoolean("prefShowBackgroundForAppNames", mShowBackgroundForAppNames);
// Update seen
editor.putBoolean("prefHaveUpdateSeen", mHaveUpdateSeen);
// Auto select first icon
editor.putBoolean("prefAutoSelectFirstIcon", mAutoSelectFirstIcon);
// Hidden apps list
editor.putStringSet("prefHiddenApps", mHiddenAppsList);
// Show sys apps
editor.putBoolean("prefShowSysApps", mShowSystemApps);
// Kodi update policy
editor.putString("prefKodiUpdatePolicy", mKodiUpdatePolicy);
// Lang
editor.putString("prefLanguage", mLanguage);
// App icon size
editor.putString("prefAppIconSize", mAppIconSize.toString());
editor.commit();
}
catch(Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String errorReason = errors.toString();
Log.d(SettingsProvider.class.getName(), "Exception while reading settings: \n" + errorReason);
}
mSemaphore.release();
}
}
@@ -0,0 +1,388 @@
package com.sidequest.launcher.tools;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.util.TypedValue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import com.sidequest.launcher.R;
/**
* Tools class to provide some additional infos
*/
public class Tools
{
// Fallback-value if timeout-value is not found
private static final int FALLBACK_SCREEN_TIMEOUT_VALUE = 30000;
// Path of the backup-file
private static final String EXPORT_FILE_PATH_NAME = new File(Environment.getExternalStorageDirectory(), "AppStarterBackup.zip").getAbsolutePath();
/**
* Restarts the current application
*
* @param c
*/
public static void doRestart(Context c)
{
try
{
//check if the context is given
if (c != null)
{
//fetch the packagemanager so we can get the default launch activity
// (you can replace this intent with any other activity if you want
PackageManager pm = c.getPackageManager();
//check if we got the PackageManager
if (pm != null)
{
//create the intent with the default start activity for your application
Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
if (mStartActivity != null)
{
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//create a pending intent so the application is restarted after System.exit(0) was called.
// We use an AlarmManager to call this intent in 100ms
int mPendingIntentId = 223344;
PendingIntent mPendingIntent = PendingIntent.getActivity(c, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//kill the application
System.exit(0);
} else
{
Log.e("AppRestarter", "Was not able to restart application, mStartActivity null");
}
} else
{
Log.e("AppRestarter", "Was not able to restart application, PM null");
}
} else
{
Log.e("AppRestarter", "Was not able to restart application, Context null");
}
}
catch (Exception ex)
{
Log.e("AppRestarter", "Was not able to restart application");
}
}
public static long getSleepModeTimeout(Context c)
{
long currentTimeout = Settings.System.getLong(c.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE);
Log.d("SLEEPMODE", "CurrentSleepModeTime: " + currentTimeout);
return currentTimeout;
}
public static void setSleepModeTimeout(Context c, long valueInMs)
{
Settings.System.putInt(c.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int) valueInMs);
}
public static String formatInterval(final long ms)
{
long millis = ms % 1000;
long x = ms / 1000;
long seconds = x % 60;
x /= 60;
long minutes = x % 60;
x /= 60;
long hours = x % 24;
x /= 24;
long days = x;
return String.format("%dd %02dh %02dm %02ds", days, hours, minutes, seconds, millis);
}
/**
* @param c context
* @return active ip address
*/
public static String getActiveIpAddress(Context c, String defValue)
{
try
{
String retVal = "";
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); )
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); )
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
if (!retVal.equals(""))
{
retVal += ", ";
}
// retVal += Formatter.formatIpAddress(inetAddress.hashCode());
retVal += inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException ex)
{
}
if (retVal == null || retVal.equals(""))
{
retVal = defValue;
}
ConnectivityManager connectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
String subType = activeNetworkInfo.getSubtypeName();
if (subType != null && !subType.equals(""))
{
subType = "-" + subType;
}
retVal = activeNetworkInfo.getTypeName() + subType + ": " + retVal;
return retVal;
}
catch (Exception e)
{
return defValue;
}
}
/**
* Retrieves the wifi name
*
* @param defValue the value to be returned if info could
* not be resolved
*/
public static String getWifiSsid(Context context, String defValue)
{
try
{
WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
return wifiInfo.getSSID();
}
catch (Exception ex)
{
return defValue;
}
}
/**
* @return Details about the device
*/
public static String getDeviceDetails()
{
String versionName = getProp("ro.build.version.name");
if(!versionName.equals(""))
{
versionName = "- " + versionName;
}
String retVal = String.format("%s - Android %s %s\n\t-> %s", Build.MODEL, Build.VERSION.RELEASE, versionName, Build.DISPLAY);
return retVal;
}
/**
* Makes a system call to "getprop" and returns the property
* @param propertyName name of the property like ro.build.version.name
* @return property content or empty string if not found
*/
public static String getProp(String propertyName)
{
String result = "";
if(propertyName != null && !propertyName.equals(""))
{
Process getProcess = null;
try
{
getProcess = Runtime.getRuntime().exec("getprop " + propertyName);
BufferedReader reader = new BufferedReader(new InputStreamReader(getProcess.getInputStream()));
result = reader.readLine().trim();
getProcess.destroy();
}
catch (java.io.IOException e)
{
}
}
return result;
}
/**
* Retrieves the net.hostname system property
*
* @param defValue the value to be returned if the hostname could
* not be resolved
*/
public static String getHostName(String defValue)
{
try
{
Method getString = Build.class.getDeclaredMethod("getString", String.class);
getString.setAccessible(true);
return getString.invoke(null, "net.hostname").toString();
}
catch (Exception ex)
{
return defValue;
}
}
/**
* @param c
* @param dip Value in DIP
* @return Value in Pixel
*/
public static int getPixelFromDip(Context c, int dip)
{
int retVal = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, c.getResources().getDisplayMetrics());
return retVal;
}
/**
* @param context
* @return Current version of AppStarter
*/
public static String getCurrentAppVersion(Context context)
{
return getCurrentAppVersion(context, context.getApplicationInfo().packageName);
}
/**
* @param context
* @return Current version of an app
*/
public static String getCurrentAppVersion(Context context, String app)
{
String retVal = context.getResources().getString(R.string.not_installed);
try
{
retVal = "v" + context.getPackageManager().getPackageInfo(app, 0).versionName;
}
catch (PackageManager.NameNotFoundException e)
{
}
return retVal;
}
/**
* Delete a directory recursively
*
* @param f Directory
* @throws IOException
*/
public static void deleteDirectoryRecursively(Context context, File f, Boolean onlyContent) throws IOException
{
if (f.isDirectory())
{
for (File c : f.listFiles())
{
deleteDirectoryRecursively(context, c, false);
}
}
if (!onlyContent)
{
if (!f.delete())
{
throw new IOException("Failed to delete file: " + f);
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + f.getAbsolutePath())));
}
}
public static String settingsExport(Context c)
{
String retVal = "Settings export failed..";
try
{
ZipDirectory.zipDirectory(c.getApplicationInfo().dataDir, EXPORT_FILE_PATH_NAME);
retVal = "Settings exported to: " + EXPORT_FILE_PATH_NAME;
}
catch(Exception e)
{
retVal += " " + e.getMessage();
}
return retVal;
}
public static String settingsImport(Context c)
{
String retVal = null;
try
{
File dataDir = new File(c.getApplicationInfo().dataDir);
ZipDirectory.unZipDirectory(new File(EXPORT_FILE_PATH_NAME), dataDir);
}
catch(Exception e)
{
retVal = "Settings import failed: " + e.getMessage();
}
return retVal;
}
/**
* Resize a bitmap to fit the new dimensions (Fit-Center)
*
* @param source
* @param fitWidth
* @param fitHeight
* @return
*/
public static Bitmap resizeBitmapToFit(Bitmap source, Integer fitWidth, Integer fitHeight)
{
return ThumbnailUtils.extractThumbnail(source, fitWidth, fitHeight);
// // Set new width and height to fit center
// int targetW = fitWidth;
// int targetH = fitHeight;
// Log.d("PHOTO", "Target-Size : " + targetW + "x" + targetH);
//
// // Get size of current bitmap
// int photoW = source.getWidth();
// int photoH = source.getHeight();
// Log.d("PHOTO", "Source-Size : " + photoW + "x" + photoH);
//
// // Create and return correct bitmap
// Matrix m = new Matrix();
// m.setRectToRect(new RectF(0, 0, photoW, photoH), new RectF(0, 0, targetW, targetH), Matrix.ScaleToFit.CENTER);
//
// Bitmap retVal = Bitmap.createBitmap(source, 0, 0, photoW, photoH, m, true);
// Log.d("PHOTO", "Cropped-Size: " + retVal.getWidth() + "x" + retVal.getHeight());
// return retVal;
}
}
@@ -0,0 +1,517 @@
package com.sidequest.launcher.tools;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import com.sidequest.launcher.gui.UpdaterDialogHandler;
/**
* Base Updater functionality
*/
public abstract class Updater
{
/** Holds the current updater dialog handler */
public UpdaterDialogHandler DialogHandler = null;
/** Latest version of AppStarter */
protected String mLatestVersion = null;
/** Download URL of the latest APK */
protected String mApkDownloadUrl = null;
/** Indicates if process is busy */
private Boolean mIsBusy = false;
/** Update dir on external storage */
private String mDownloadFolder = "AppStarterUpdates";
/** Indicates if the download was succesful */
private Boolean mDownloadSuccessful = false;
/** Error reason */
private String mDownloadErrorReason = null;
/** Queue value of running download */
private Long mQueueValue;
/** Download manager */
private DownloadManager mDownloadManager;
/** Update semaphore */
private Semaphore mUpdateSemaphore = null;
/** Check for update listener */
private OnCheckForUpdateFinishedListener mOnCheckForUpdateFinishedListener;
/** Update progress listener */
private OnUpdateProgressListener mOnUpdateProgressListener;
/** Returns the name of the App */
public abstract String getAppName();
/** Returns the name of the App */
public abstract String getPackageName(Context context);
public abstract Boolean isVersionNewer(String oldVersion, String newVersion);
/** Update the values of the latest version and of the APK download URL for the latest version */
protected abstract void updateLatestVersionAndApkDownloadUrl() throws Exception;
/** Return the current version */
public String getCurrentVersion(Context context)
{
return Tools.getCurrentAppVersion(context, getPackageName(context));
}
/** Return the latest version */
public String getLatestVersion()
{
return mLatestVersion;
}
/** Set the check for update listener */
public void setOnCheckForUpdateFinishedListener(OnCheckForUpdateFinishedListener listener)
{
mOnCheckForUpdateFinishedListener = listener;
}
/** Set progress update listener */
public void setOnUpdateProgressListener(OnUpdateProgressListener listener)
{
mOnUpdateProgressListener = listener;
}
/**
* Compares standard version strings like "2.1", "v2.3.1.0" or "version 1.3.2"
* @param oldVersion Old version String
* @param newVersion New version String
* @return true if newVersion String is newer than oldVersion String
*/
public Boolean isVersionNewerStandardCheck(String oldVersion, String newVersion)
{
Boolean retVal = false;
try
{
List<Integer> oldVerList = getVersionList(oldVersion);
List<Integer> newVerList = getVersionList(newVersion);
if(oldVerList.size() > 0 && newVerList.size() > 0)
{
for(Integer i = 0; i < newVerList.size(); i++)
{
// If oldversion has no additional step and all
// steps before have been equal, newVersion is newer
if(i >= oldVerList.size())
{
retVal = true;
break;
}
// If newVersions current step is higher than oldversions stage,
// newVersion is newer
if(newVerList.get(i) > oldVerList.get(i))
{
retVal = true;
break;
}
// If oldVersions current step is higher than newVersions stage,
// oldVersion is newer
if(oldVerList.get(i) > newVerList.get(i))
{
break;
}
// Else versions have been equal --> no newer
// --> check next stage or finish
}
}
else if(oldVerList.size() == 0 && newVerList.size() > 0)
{
// This happens if old version is not installed / not found
// which should mean that the latest version is anyway newer
retVal = true;
}
}
catch(Exception ignore){}
return retVal;
}
/**
* Separate version string in major, minor, ..
* Most significant value first
* @param versionString Version string to be parsed
* @return List of Integers
*/
private List<Integer> getVersionList(String versionString)
{
List<Integer> retVal = new ArrayList<Integer>();
try
{
if(versionString != null && !versionString.equals(""))
{
// Delete everything that is no digit and no dot (like e.g. "v" or "version")
versionString = versionString.replaceAll("[^\\d.]", "");
// Split the remaining part by the dots
String[] parts = versionString.split("\\.");
// Now create the version list
if(parts != null && parts.length > 0)
{
for(String part : parts)
{
retVal.add(Integer.valueOf(part));
}
}
}
}
catch(Exception ignore) { }
return retVal;
}
/** Check github for update */
public void checkForUpdate(Boolean synchron)
{
Thread checkForUpdateThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (mIsBusy)
{
throw new Exception("Updater is already working..");
}
mIsBusy = true;
// Reset variables
mApkDownloadUrl = null;
mLatestVersion = null;
// Call the update mechanism of the actual updater
updateLatestVersionAndApkDownloadUrl();
// Check if latest version is not null
if(mLatestVersion == null)
{
throw new Exception("Latest version not found.");
}
// Check if download url is not null
if(mApkDownloadUrl == null)
{
throw new Exception("No .apk download URL found.");
}
// If everything was fine show success-message:
fireOnCheckForUpdateFinished("Check for update finished successful, found version: " + getLatestVersion());
Log.d(AppStarterUpdater.class.getName(), "Check for update finished successful, found version: " + getLatestVersion());
}
catch (Exception e)
{
Log.d(AppStarterUpdater.class.getName(), "Update-Check-Error: " + e.getMessage());
fireOnCheckForUpdateFinished("Update-Check-Error: " + e.getMessage());
}
finally
{
mIsBusy = false;
}
}
});
checkForUpdateThread.start();
if(synchron)
{
try
{
checkForUpdateThread.join();
}
catch (InterruptedException ignore) {}
}
}
public void update(final Context context)
{
Thread updateThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (mIsBusy)
{
throw new Exception("AppStarterUpdater is already working..");
}
// Check for update synchron
checkForUpdate(true);
mIsBusy = true;
// Check if update-check was successful and version is newer
String oldVersion = getCurrentVersion(context);
String latestVersion = getLatestVersion();
if (latestVersion == null || !isVersionNewer(oldVersion, latestVersion))
{
throw new Exception("No newer version found..");
}
String apkUrl = mApkDownloadUrl;
if(apkUrl == null)
{
throw new Exception("Download URL of new version not found..");
}
Log.d(AppStarterUpdater.class.getName(), "Download from URL: " + apkUrl);
fireOnUpdateProgressListener(false, 10, "Newer version found, start download..");
// Create download-dir and start download
File downloadDir = new File(Environment.getExternalStorageDirectory(), mDownloadFolder);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + downloadDir.getAbsolutePath())));
if(downloadDir.exists() && !downloadDir.isDirectory())
{
if(!downloadDir.delete())
{
throw new Exception("Can not delete file: " + downloadDir.getAbsolutePath());
}
}
if(!downloadDir.exists() && !downloadDir.mkdir())
{
throw new Exception("Can not create download folder: " + downloadDir.getAbsolutePath());
}
else
{
Tools.deleteDirectoryRecursively(context, downloadDir, true);
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + downloadDir.getAbsolutePath())));
File downloadFile = new File(downloadDir, getAppName() + "-" + latestVersion + ".apk");
mDownloadSuccessful = false;
mDownloadErrorReason = null;
DownloadManager.Request localRequest = new DownloadManager.Request(Uri.parse(apkUrl));
localRequest.setDescription("Downloading " + getAppName() + " " + latestVersion);
localRequest.setTitle(getAppName() + " Update");
localRequest.allowScanningByMediaScanner();
localRequest.setNotificationVisibility(1);
Log.d(AppStarterUpdater.class.getName(), "Download to file://" + downloadFile.getAbsolutePath());
localRequest.setDestinationUri(Uri.parse("file://" + downloadFile.getAbsolutePath()));
context.registerReceiver(new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(AppStarterUpdater.class.getName(), "Received intent: " + action);
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
{
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(mQueueValue);
Cursor c = mDownloadManager.query(query);
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex))
{
mDownloadSuccessful = true;
}
else
{
// Try to get error reason
switch(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)))
{
case DownloadManager.ERROR_CANNOT_RESUME:
mDownloadErrorReason = "ERROR_CANNOT_RESUME";
break;
case DownloadManager.ERROR_DEVICE_NOT_FOUND:
mDownloadErrorReason = "ERROR_DEVICE_NOT_FOUND";
break;
case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
mDownloadErrorReason = "ERROR_FILE_ALREADY_EXISTS";
break;
case DownloadManager.ERROR_FILE_ERROR:
mDownloadErrorReason = "ERROR_FILE_ERROR";
break;
case DownloadManager.ERROR_HTTP_DATA_ERROR:
mDownloadErrorReason = "ERROR_HTTP_DATA_ERROR";
break;
case DownloadManager.ERROR_INSUFFICIENT_SPACE:
mDownloadErrorReason = "ERROR_INSUFFICIENT_SPACE";
break;
case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
mDownloadErrorReason = "ERROR_TOO_MANY_REDIRECTS";
break;
case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
mDownloadErrorReason = "ERROR_UNHANDLED_HTTP_CODE";
break;
default:
mDownloadErrorReason = "ERROR_UNKNOWN";
break;
}
}
}
c.close();
}
// Unregister receiver
context.unregisterReceiver(this);
// Release semaphore in any case..
Log.d(AppStarterUpdater.class.getName(), "Release semaphore..");
mUpdateSemaphore.release();
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Log.d(AppStarterUpdater.class.getName(), "Aquire semaphore");
mUpdateSemaphore = new Semaphore(1);
mUpdateSemaphore.acquire();
// Here the download is performed
Log.d(AppStarterUpdater.class.getName(), "Start download");
mDownloadManager = (DownloadManager)context.getSystemService(context.DOWNLOAD_SERVICE);
mQueueValue = mDownloadManager.enqueue(localRequest);
Log.d(AppStarterUpdater.class.getName(), "Aquire semaphore again");
int lastPercentage = 0;
while(!mUpdateSemaphore.tryAcquire())
{
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(mQueueValue);
Cursor cursor = mDownloadManager.query(q);
int percentage = 0;
if(cursor.moveToFirst())
{
int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
percentage = (int)Math.round((((double)bytes_downloaded / (double)bytes_total) * 100.0) * 8.0/10.0);
if(percentage < 0) percentage = 0;
if(percentage > 100) percentage = 100;
}
cursor.close();
if(percentage > lastPercentage)
{
lastPercentage = percentage;
fireOnUpdateProgressListener(false, 10 + percentage, "Download in progress..");
}
Thread.sleep(500);
}
mUpdateSemaphore.release();
mUpdateSemaphore = null;
Log.d(AppStarterUpdater.class.getName(), "Download finished");
if(!mDownloadSuccessful)
{
String reason = "";
if(mDownloadErrorReason != null)
{
reason = " Reason: " + mDownloadErrorReason;
}
throw new Exception("Download failed.." + reason);
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + downloadFile.getAbsolutePath())));
fireOnUpdateProgressListener(false, 80, "Download finished, start installation..");
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setDataAndType(Uri.parse("file://" + downloadFile.getAbsolutePath()), "application/vnd.android.package-archive");
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(installIntent);
fireOnUpdateProgressListener(false, 100, "Successfully initiated update..");
}
catch(Exception e)
{
Log.d(AppStarterUpdater.class.getName(), "UpdateError: " + e.getMessage());
fireOnUpdateProgressListener(true, 100, e.getMessage());
}
finally
{
mIsBusy = false;
}
}
});
updateThread.start();
}
/** Check for update */
public void checkForUpdate()
{
checkForUpdate(false);
}
/**
* Fire update progress
* @param percent Percentage
* @param message Message
*/
protected void fireOnUpdateProgressListener(final Boolean isError, final Integer percent, final String message)
{
Thread fireThread = new Thread(new Runnable()
{
@Override
public void run()
{
if(mOnUpdateProgressListener != null)
{
mOnUpdateProgressListener.onUpdateProgress(isError, percent, message);
}
}
});
fireThread.start();
}
/**
* Fire check for update finished message
* @param message Message to fire
*/
protected void fireOnCheckForUpdateFinished(final String message)
{
Thread fireThread = new Thread(new Runnable()
{
@Override
public void run()
{
if(mOnCheckForUpdateFinishedListener != null)
{
mOnCheckForUpdateFinishedListener.onCheckForUpdateFinished(message);
}
}
});
fireThread.start();
}
/**
* Interface for progress messages of update check
*/
public interface OnCheckForUpdateFinishedListener
{
public void onCheckForUpdateFinished(String message);
}
/**
* Interface for progress messages of performing an update
*/
public interface OnUpdateProgressListener
{
public void onUpdateProgress(Boolean isError, Integer percent, String message);
}
}
@@ -0,0 +1,170 @@
package com.sidequest.launcher.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipDirectory
{
public static void zipDirectory(String directoryPath, String zipFileNamePath) throws IOException
{
File directoryToZip = new File(directoryPath);
File zipFile = new File(zipFileNamePath);
File zipFilePath = zipFile.getParentFile();
if (!zipFilePath.exists())
{
zipFilePath.mkdirs();
}
if (zipFile.exists())
{
zipFile.delete();
}
List<File> fileList = new ArrayList<File>();
getAllFiles(directoryToZip, fileList);
writeZipFile(directoryToZip, fileList, zipFile);
}
/**
* Extract a zip file to the given destination folder.
* @param file zip file to extract
* @param destination destinatin folder
*/
public static void unZipDirectory(File file, File destination) throws IOException
{
ZipInputStream in = null;
OutputStream out = null;
try
{
// Open the ZIP file
in = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null)
{
String outFilename = entry.getName();
// Open the output file
if (entry.isDirectory())
{
new File(destination, outFilename).mkdirs();
}
else
{
File outputFile = new File(destination, outFilename);
File outputFileFolder = outputFile.getParentFile();
if(!outputFileFolder.exists())
{
outputFileFolder.mkdirs();
}
if(outputFile.exists())
{
outputFile.delete();
}
out = new FileOutputStream(outputFile);
// Transfer bytes from the ZIP file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
// Close the stream
out.close();
}
}
}
finally
{
// Close the stream
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
private static void getAllFiles(File dir, List<File> fileList)
{
File[] files = dir.listFiles();
for (File file : files)
{
fileList.add(file);
if (file.isDirectory())
{
getAllFiles(file, fileList);
}
}
}
private static void writeZipFile(File directoryToZip, List<File> fileList, File zipFile)
{
try
{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : fileList)
{
if (file.exists() && !file.isDirectory())
{ // we only zip files, not directories
addToZip(directoryToZip, file, zos);
}
}
zos.close();
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException, IOException
{
FileInputStream fis = new FileInputStream(file);
// we want the zipEntry's path to be a relative path that is relative
// to the directory being zipped, so chop off the rest of the path
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0)
{
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
}