Compare commits

...

15 Commits

Author SHA1 Message Date
ZhanGSKen
f02dc215ca <ollama>APK 15.0.0 release Publish. 2025-03-28 05:09:21 +08:00
ZhanGSKen
1c27d0ccdc Ollama 问答模块完成。 2025-03-28 05:04:15 +08:00
ZhanGSKen
803745d12e 添加简单http访问功能 2025-03-27 20:45:57 +08:00
ZhanGSKen
a66be9cd37 添加WinBoll Ollama 访问项目。 2025-03-27 19:39:54 +08:00
ZhanGSKen
d83d460342 调试到 _GlobalApplication 实例化次数与现有实例问题... 2025-03-27 19:06:51 +08:00
ZhanGSKen
9a53d04050 窗口判断与添加测试结束,进入resumeActivity调试阶段... 2025-03-27 14:39:26 +08:00
ZhanGSKen
ada664f4ab 添加Base工具栏 2025-03-27 12:32:24 +08:00
ZhanGSKen
92a9bbb455 整理代码 2025-03-27 11:46:36 +08:00
ZhanGSKen
211eef7232 整理代码 2025-03-27 11:46:11 +08:00
ZhanGSKen
31bad8a279 调试信息调整 2025-03-27 11:45:40 +08:00
ZhanGSKen
bc0eb69edf 增加应用适配系统范围 2025-03-27 11:44:58 +08:00
ZhanGSKen
08f990de65 添加日志窗口标签查找功能 2025-03-27 10:42:58 +08:00
ZhanGSKen
e2b6fadd43 日志分屏比例切换失效时,需要手动切换出任务栏视图再回到分屏任务窗口,这时就可以切换比例。修复了应用调出二级窗口弹出时不在原应用窗口弹出问题。 2025-03-27 01:05:52 +08:00
ZhanGSKen
2074f68ef3 日志窗口函数重构 2025-03-26 19:32:21 +08:00
ZhanGSKen
56a13b4a40 <libappbase>Library Release 15.1.0 2025-03-26 15:43:27 +08:00
56 changed files with 1651 additions and 117 deletions

View File

@@ -24,7 +24,7 @@ android {
defaultConfig {
applicationId "cc.winboll.studio.appbase"
minSdkVersion 26
minSdkVersion 24
targetSdkVersion 29
versionCode 1
// versionName 更新后需要手动设置

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle
#Wed Mar 26 15:43:05 HKT 2025
#Thu Mar 27 10:59:31 GMT 2025
stageCount=1
libraryProject=libappbase
baseVersion=15.1
publishVersion=15.1.0
buildCount=0
buildCount=130
baseBetaVersion=15.1.1

View File

@@ -8,15 +8,15 @@
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/MyAPPBaseTheme"
android:resizeableActivity="true">
android:resizeableActivity="true"
android:process=":App">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:exported="true"
android:resizeableActivity="true"
android:launchMode="singleInstance"
android:taskAffinity="cc.winboll.studio.appbase.task.main"
android:exported="true">
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation">
<intent-filter>
@@ -32,7 +32,15 @@
</activity>
<activity android:name=".GlobalApplication$CrashActivity"/>
<activity android:name=".activities.NewActivity"
android:exported="true"
android:resizeableActivity="true"
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"/>
<activity android:name=".activities.New2Activity"
android:exported="true"
android:resizeableActivity="true"
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"/>
<service
android:name=".MyTileService"
@@ -111,9 +119,6 @@
android:name="android.max_aspect"
android:value="4.0"/>
<activity android:name=".activities.NewActivity"/>
<activity android:name=".activities.New2Activity"/>
</application>

View File

@@ -65,14 +65,17 @@ public class MainActivity extends AppCompatActivity implements IWinBollActivity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_main, menu);
getMenuInflater().inflate(R.menu.toolbar_appbase, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == cc.winboll.studio.appbase.R.id.item_log) {
onLogActivity();
WinBollActivityManager.getInstance(this).startLogActivity(this);
return true;
} else if(item.getItemId() == cc.winboll.studio.appbase.R.id.item_minimal) {
moveTaskToBack(true);
}
// 在switch语句中处理每个ID并在处理完后返回true未处理的情况返回false。
return super.onOptionsItemSelected(item);
@@ -176,23 +179,5 @@ public class MainActivity extends AppCompatActivity implements IWinBollActivity
WinBollActivityManager.getInstance(this).startWinBollActivity(this, NewActivity.class);
}
public void onLogActivity() {
Intent intent = new Intent(MainActivity.this, LogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
// Define the bounds.
Rect bounds = new Rect(500, 300, 100, 0);
// Set the bounds as an activity option.
ActivityOptions options = ActivityOptions.makeBasic();
options.setLaunchBounds(bounds);
//Intent intent = new Intent(this, LpgActivity.class);
startActivity(intent, options.toBundle());
//WinBollActivityManager.getInstance(this).startWinBollActivity(this, intent, LogActivity.class);
}
}

View File

@@ -7,16 +7,20 @@ package cc.winboll.studio.appbase.activities;
*/
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import cc.winboll.studio.appbase.R;
import cc.winboll.studio.libappbase.LogView;
import cc.winboll.studio.libappbase.winboll.IWinBollActivity;
import cc.winboll.studio.libappbase.winboll.WinBollActivityManager;
public class New2Activity extends Activity implements IWinBollActivity {
public class New2Activity extends AppCompatActivity implements IWinBollActivity {
public static final String TAG = "New2Activity";
Toolbar mToolbar;
//LogView mLogView;
@Override
@@ -36,6 +40,9 @@ public class New2Activity extends Activity implements IWinBollActivity {
// mLogView = findViewById(R.id.logview);
// mLogView.start();
mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
@Override
@@ -55,4 +62,24 @@ public class New2Activity extends Activity implements IWinBollActivity {
public void onNewActivity(View view) {
WinBollActivityManager.getInstance(this).startWinBollActivity(this, NewActivity.class);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_main, menu);
getMenuInflater().inflate(R.menu.toolbar_appbase, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == cc.winboll.studio.appbase.R.id.item_log) {
WinBollActivityManager.getInstance(this).startLogActivity(this);
return true;
} else if(item.getItemId() == cc.winboll.studio.appbase.R.id.item_minimal) {
moveTaskToBack(true);
}
// 在switch语句中处理每个ID并在处理完后返回true未处理的情况返回false。
return super.onOptionsItemSelected(item);
}
}

View File

@@ -6,16 +6,20 @@ package cc.winboll.studio.appbase.activities;
*/
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import cc.winboll.studio.appbase.R;
import cc.winboll.studio.libappbase.LogView;
import cc.winboll.studio.libappbase.winboll.IWinBollActivity;
import cc.winboll.studio.libappbase.winboll.WinBollActivityManager;
public class NewActivity extends Activity implements IWinBollActivity {
public class NewActivity extends AppCompatActivity implements IWinBollActivity {
public static final String TAG = "NewActivity";
Toolbar mToolbar;
//LogView mLogView;
@Override
@@ -34,6 +38,9 @@ public class NewActivity extends Activity implements IWinBollActivity {
setContentView(R.layout.activity_new);
// mLogView = findViewById(R.id.logview);
// mLogView.start();
mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
@Override
@@ -53,4 +60,24 @@ public class NewActivity extends Activity implements IWinBollActivity {
public void onNew2Activity(View view) {
WinBollActivityManager.getInstance(this).startWinBollActivity(this, New2Activity.class);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_main, menu);
getMenuInflater().inflate(R.menu.toolbar_appbase, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == cc.winboll.studio.appbase.R.id.item_log) {
WinBollActivityManager.getInstance(this).startLogActivity(this);
return true;
} else if(item.getItemId() == cc.winboll.studio.appbase.R.id.item_minimal) {
moveTaskToBack(true);
}
// 在switch语句中处理每个ID并在处理完后返回true未处理的情况返回false。
return super.onOptionsItemSelected(item);
}
}

View File

@@ -6,11 +6,11 @@
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

View File

@@ -6,9 +6,9 @@
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"/>
<TextView
@@ -30,13 +30,6 @@
android:textAllCaps="false"
android:onClick="onCloseAllActivity"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CloseAllActivity"
android:textAllCaps="false"
android:onClick="onCloseAllActivity"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"

View File

@@ -2,8 +2,5 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/item_log"
android:title="Log"/>
</menu>

View File

@@ -9,7 +9,7 @@ android {
buildToolsVersion "32.0.0"
defaultConfig {
minSdkVersion 26
minSdkVersion 24
targetSdkVersion 29
}
buildTypes {

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle
#Wed Mar 26 15:43:05 HKT 2025
#Thu Mar 27 10:59:31 GMT 2025
stageCount=1
libraryProject=libappbase
baseVersion=15.1
publishVersion=15.1.0
buildCount=0
buildCount=130
baseBetaVersion=15.1.1

View File

@@ -19,18 +19,19 @@
<activity
android:name=".GlobalCrashActivity"
android:label="GlobalCrashActivity"
android:launchMode="standard"/>
android:launchMode="singleInstance"
android:process=":GlobalCrashActivity"/>
<activity
android:theme="@android:style/Theme.Holo.Light.NoActionBar"
android:name="cc.winboll.studio.libappbase.winboll.LogActivity"
android:resizeableActivity="true"
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
android:exported="true"
android:launchMode="singleInstance"
android:taskAffinity="cc.winboll.studio.libappbase.task.log"
android:exported="true">
</activity>
android:process=":LogActivity">
</activity>
<service
android:name=".SimpleOperateSignalCenterService"
android:exported="true">

View File

@@ -27,7 +27,6 @@ public class GlobalApplication extends Application {
volatile static GlobalApplication _GlobalApplication;
// 是否处于调试状态
volatile static boolean isDebuging = false;
WinBollActivityManager mWinBollActivityManager;
MyActivityLifecycleCallbacks mMyActivityLifecycleCallbacks;
public static void setIsDebuging(boolean isDebuging) {
@@ -45,6 +44,10 @@ public class GlobalApplication extends Application {
}
}
public static GlobalApplication getInstance() {
return _GlobalApplication;
}
static String getAPPBaseModelFilePath() {
return _GlobalApplication.getDataDir().getPath() + "/APPBaseModel.json";
}
@@ -65,7 +68,17 @@ public class GlobalApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
_GlobalApplication = this;
// _GlobalApplication 取值调试部分
//
boolean is_GlobalApplicationNull = false;
if (_GlobalApplication == null) {
is_GlobalApplicationNull = true;
_GlobalApplication = this;
} else {
is_GlobalApplicationNull = false;
_GlobalApplication = this;
}
// 设置应用调试标志
APPBaseModel appBaseModel = APPBaseModel.loadBeanFromFile(getAPPBaseModelFilePath(), APPBaseModel.class);
@@ -87,17 +100,22 @@ public class GlobalApplication extends Application {
// 初始化 Toast 框架
ToastUtils.init(this);
// mWinBollActivityManager = WinBollActivityManager.getInstance(this);
// mWinBollActivityManager.setWinBollUI_TYPE(WinBollActivityManager.WinBollUI_TYPE.Service);
// // 注册回调
// mMyActivityLifecycleCallbacks = new MyActivityLifecycleCallbacks(mWinBollActivityManager);
// registerActivityLifecycleCallbacks(mMyActivityLifecycleCallbacks);
// _GlobalApplication 取值调试部分
//
LogUtils.d(TAG, String.format("is_GlobalApplicationNull is %s", is_GlobalApplicationNull));
WinBollActivityManager.getInstance(_GlobalApplication);
WinBollActivityManager.getInstance(_GlobalApplication).setWinBollUI_TYPE(WinBollActivityManager.WinBollUI_TYPE.Service);
// 注册回调
mMyActivityLifecycleCallbacks = new MyActivityLifecycleCallbacks();
registerActivityLifecycleCallbacks(mMyActivityLifecycleCallbacks);
}
@Override
public void onTerminate() {
super.onTerminate();
_GlobalApplication = null;
// 注销回调(非必须,但建议释放资源)
unregisterActivityLifecycleCallbacks(mMyActivityLifecycleCallbacks);
}

View File

@@ -10,6 +10,8 @@ import android.content.ClipboardManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
@@ -18,6 +20,8 @@ import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
@@ -42,6 +46,7 @@ public class LogView extends RelativeLayout {
Context mContext;
ScrollView mScrollView;
TextView mTextView;
EditText metTagSearch;
CheckBox mSelectableCheckBox;
CheckBox mSelectAllTAGCheckBox;
TAGListAdapter mTAGListAdapter;
@@ -107,9 +112,41 @@ public class LogView extends RelativeLayout {
//
mScrollView = findViewById(cc.winboll.studio.libappbase.R.id.viewlogScrollViewLog);
mTextView = findViewById(cc.winboll.studio.libappbase.R.id.viewlogTextViewLog);
metTagSearch = findViewById(cc.winboll.studio.libappbase.R.id.tagsearch_et);
// 获取Log Level spinner实例
mLogLevelSpinner = findViewById(cc.winboll.studio.libappbase.R.id.viewlogSpinner1);
metTagSearch.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
}
@Override
public void beforeTextChanged(CharSequence charSequence, int p, int p1, int p2) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
LogUtils.d(TAG, s.toString());
if (s.length() > 0) {
scrollToTag(s.toString());
} else {
HorizontalScrollView hsRoot = findViewById(R.id.viewlogHorizontalScrollView1);
hsRoot.smoothScrollTo(0, 0);
mListViewTags.resetScrollToStart();
}
// mListViewTags.postDelayed(new Runnable() {
// @Override
// public void run() {
// mListViewTags.scrollToItem(5);
// }
// }, 100);
}
// 其他方法留空或按需实现
});
(findViewById(cc.winboll.studio.libappbase.R.id.viewlogButtonClean)).setOnClickListener(new View.OnClickListener(){
@Override
@@ -233,6 +270,60 @@ public class LogView extends RelativeLayout {
scrollLogUp();
}
public void scrollToTag(final String prefix) {
if (mTAGListAdapter == null || prefix == null || prefix.length() == 0) {
LogUtils.d(TAG, "参数为空,无法滚动");
return;
}
final List<TAGItemModel> itemList = mTAGListAdapter.getItemList();
mListViewTags.post(new Runnable() {
@Override
public void run() {
// 查找匹配的标签位置
int targetPosition = -1;
for (int i = 0; i < itemList.size(); i++) {
String tag = itemList.get(i).getTag();
if (tag != null && tag.toLowerCase().startsWith(prefix.toLowerCase())) {
targetPosition = i;
break;
}
}
if (targetPosition != -1) {
// 优化滚动逻辑
//mListViewTags.setSelection(targetPosition);
//mListViewTags.invalidateViews(); // 强制刷新所有可见项
// 单独刷新目标视图
// View targetView = mListViewTags.getChildAt(targetPosition);
// if (targetView != null) {
// targetView.requestLayout();
// targetView.requestFocus();
// }
final int scrollPosition = targetPosition;
// 延迟滚动确保布局完成
mListViewTags.postDelayed(new Runnable() {
@Override
public void run() {
LogUtils.d(TAG, String.format("scrollPosition %d", scrollPosition));
mListViewTags.scrollToItem(scrollPosition);
}
}, 100);
} else {
LogUtils.d(TAG, "未找到匹配的标签前缀:" + prefix);
}
}
});
}
class LogViewHandler extends Handler {
final static int MSG_LOGVIEW_UPDATE = 0;
@@ -300,6 +391,30 @@ public class LogView extends RelativeLayout {
public void setChecked(boolean checked) {
isChecked = checked;
}
// getter/setter...
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TAGItemModel that = (TAGItemModel) o;
// 手动处理空值比较Java 6 不支持 Objects.equals
if (tag == null) {
return that.tag == null;
} else {
return tag.equals(that.tag);
}
}
@Override
public int hashCode() {
return tag == null ? 0 : tag.hashCode(); // 手动处理空值
}
}
@@ -314,7 +429,11 @@ public class LogView extends RelativeLayout {
mapOrigin = map;
loadMap(mapOrigin);
}
public List<TAGItemModel> getItemList() {
return itemList;
}
@Override
public int getCount() {
return itemList.size();
@@ -344,7 +463,7 @@ public class LogView extends RelativeLayout {
loadMap(mapOrigin);
super.notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;

View File

@@ -9,23 +9,34 @@ import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;
import android.widget.Scroller;
import cc.winboll.studio.libappbase.LogUtils;
public class HorizontalListView extends ListView {
public static final String TAG = "HorizontalListView";
int verticalOffset = 0;
private int verticalOffset = 0;
private Scroller scroller;
private int totalWidth;
public HorizontalListView(Context context) {
super(context);
init();
}
public HorizontalListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public HorizontalListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
scroller = new Scroller(getContext());
setHorizontalScrollBarEnabled(true);
setVerticalScrollBarEnabled(false);
}
public void setVerticalOffset(int verticalOffset) {
@@ -38,28 +49,81 @@ public class HorizontalListView extends ListView {
int childCount = getChildCount();
int left = getPaddingLeft();
int viewHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
LogUtils.d(TAG, String.format("HorizontalListView的高度 %d", viewHeight));
totalWidth = left;
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
// 计算每个子视图的宽度和高度
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
//LogUtils.d(TAG, String.format("child : width %d , height %d", width, height));
// 设置子视图的位置,实现水平布局
child.layout(left, verticalOffset, left + width, verticalOffset + height);
left += width;
}
totalWidth = left + getPaddingRight();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
//super.onMeasure(widthMeasureSpec, newHeightMeasureSpec);
int newWidthMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
//LogUtils.d(TAG, String.format("newWidthMeasureSpec %d, newHeightMeasureSpec %d", newWidthMeasureSpec, newHeightMeasureSpec));
super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec);
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
public void smoothScrollTo(int x, int y) {
int dx = x - getScrollX();
int dy = y - getScrollY();
scroller.startScroll(getScrollX(), getScrollY(), dx, dy, 300); // 300ms平滑动画
invalidate();
}
@Override
public int computeHorizontalScrollRange() {
return totalWidth;
}
@Override
public int computeHorizontalScrollOffset() {
return getScrollX();
}
@Override
public int computeHorizontalScrollExtent() {
return getWidth();
}
public void scrollToItem(int position) {
if (position < 0 || position >= getChildCount()) {
LogUtils.d(TAG, "无效的position: " + position);
return;
}
View targetView = getChildAt(position);
int targetLeft = targetView.getLeft();
int scrollX = targetLeft - getPaddingLeft();
// 修正最大滚动范围计算
int maxScrollX = totalWidth;
scrollX = Math.max(0, Math.min(scrollX, maxScrollX));
// 强制重新布局和绘制
requestLayout();
invalidateViews();
smoothScrollTo(scrollX, 0);
LogUtils.d(TAG, String.format("滚动到position: %d, scrollX: %d computeHorizontalScrollRange() %d", position, scrollX, computeHorizontalScrollRange()));
}
public void resetScrollToStart() {
// 强制重新布局和绘制
requestLayout();
invalidateViews();
smoothScrollTo(0, 0);
}
}

View File

@@ -6,22 +6,26 @@ package cc.winboll.studio.libappbase.winboll;
*/
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import cc.winboll.studio.libappbase.GlobalApplication;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.utils.ToastUtils;
import cc.winboll.studio.libappbase.utils.ToastUtils;
import cc.winboll.studio.libappbase.winboll.IWinBollActivity;
public class MyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
public static final String TAG = "MyActivityLifecycleCallbacks";
WinBollActivityManager mWinBollActivityManager;
public String mInfo = "";
public MyActivityLifecycleCallbacks(WinBollActivityManager winBollActivityManager) {
mWinBollActivityManager = winBollActivityManager;
public MyActivityLifecycleCallbacks() {
}
WinBollActivityManager getWinBollActivityManager() {
return WinBollActivityManager.getInstance(GlobalApplication.getInstance());
}
void createActivityeInfo(Activity activity) {
@@ -60,7 +64,7 @@ public class MyActivityLifecycleCallbacks implements Application.ActivityLifecyc
//System.out.println(activity.getLocalClassName() + " was created");
LogUtils.d(TAG, activity.getLocalClassName() + " was created");
createActivityeInfo(activity);
mWinBollActivityManager.add((IWinBollActivity)activity);
getWinBollActivityManager().add((IWinBollActivity)activity);
}
@Override
@@ -98,6 +102,6 @@ public class MyActivityLifecycleCallbacks implements Application.ActivityLifecyc
public void onActivityDestroyed(Activity activity) {
//System.out.println(activity.getLocalClassName() + " was destroyed");
LogUtils.d(TAG, activity.getLocalClassName() + " was destroyed");
mWinBollActivityManager.registeRemove((IWinBollActivity)activity);
getWinBollActivityManager().registeRemove((IWinBollActivity)activity);
}
}

View File

@@ -13,6 +13,7 @@ import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.utils.ToastUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -32,9 +33,9 @@ public class WinBollActivityManager {
Context mContext;
MyActivityLifecycleCallbacks mMyActivityLifecycleCallbacks;
static WinBollActivityManager _mWinBollActivityManager;
static Map<String, IWinBollActivity> _mapIWinBollList;
IWinBollActivity firstIWinBollActivity;
static volatile WinBollActivityManager _mWinBollActivityManager;
static volatile Map<String, IWinBollActivity> _mapIWinBollList;
static volatile IWinBollActivity firstIWinBollActivity;
public WinBollActivityManager(Context context) {
mContext = context;
@@ -69,7 +70,9 @@ public class WinBollActivityManager {
// 把Activity添加到管理中
//
public <T extends IWinBollActivity> void add(T iWinBoll) {
if (isActive(iWinBoll.getTag())) {
String tag = ((IWinBollActivity)iWinBoll).getTag();
LogUtils.d(TAG, String.format("add(T iWinBoll) tag is %s", tag));
if (isActive(tag)) {
LogUtils.d(TAG, String.format("add(...) %s is active.", iWinBoll.getTag()));
} else {
// 设置起始活动窗口,以便最后退出时提问
@@ -93,11 +96,13 @@ public class WinBollActivityManager {
public <T extends IWinBollActivity> void startWinBollActivity(Context context, Class<T> clazz) {
try {
// 如果窗口已存在就重启窗口
String tag = clazz.newInstance().getTag();
String tag = ((IWinBollActivity)clazz.newInstance()).getTag();
LogUtils.d(TAG, String.format("startWinBollActivity(Context context, Class<T> clazz) tag is %s", tag));
if (isActive(tag)) {
resumeActivity(context, tag);
return;
}
ToastUtils.show("startWinBollActivity(Context context, Class<T> clazz)");
// 新建一个任务窗口
Intent intent = new Intent(context, clazz);
@@ -106,7 +111,7 @@ public class WinBollActivityManager {
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_TAG, tag);
mContext.startActivity(intent);
context.startActivity(intent);
} catch (InstantiationException | IllegalAccessException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
@@ -115,7 +120,8 @@ public class WinBollActivityManager {
public <T extends IWinBollActivity> void startWinBollActivity(Context context, Intent intent, Class<T> clazz) {
try {
// 如果窗口已存在就重启窗口
String tag = clazz.newInstance().getTag();
String tag = ((IWinBollActivity)clazz.newInstance()).getTag();
LogUtils.d(TAG, String.format("startWinBollActivity(Context context, Intent intent, Class<T> clazz) tag is %s", tag));
if (isActive(tag)) {
resumeActivity(context, tag);
return;
@@ -128,12 +134,39 @@ public class WinBollActivityManager {
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_TAG, tag);
mContext.startActivity(intent);
context.startActivity(intent);
} catch (InstantiationException | IllegalAccessException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
}
public <T extends IWinBollActivity> void startLogActivity(Context context) {
// 如果窗口已存在就重启窗口
String tag = LogActivity.TAG;
if (isActive(tag)) {
resumeActivity(context, tag);
return;
}
// 新建一个任务窗口
Intent intent = new Intent(context, LogActivity.class);
//打开多任务窗口 flags
// Define the bounds.
// Rect bounds = new Rect(0, 0, 800, 200);
// // Set the bounds as an activity option.
// ActivityOptions options = ActivityOptions.makeBasic();
// options.setLaunchBounds(bounds);
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.putExtra(EXTRA_TAG, tag);
//context.startActivity(intent, options.toBundle());
context.startActivity(intent);
}
public boolean isFirstIWinBollActivity(IWinBollActivity iWinBollActivity) {
return firstIWinBollActivity != null && firstIWinBollActivity == iWinBollActivity;
}
@@ -142,10 +175,11 @@ public class WinBollActivityManager {
// 判断 tag绑定的 MyActivity是否存在
//
public boolean isActive(String tag) {
//printAvtivityListInfo();
LogUtils.d(TAG, String.format("isActive(String tag) tag is %s", tag));
//printIWinBollListInfo();
IWinBollActivity iWinBoll = getIWinBoll(tag);
if (iWinBoll != null) {
LogUtils.d(TAG, "isActive(...) activity != null tag " + tag);
//LogUtils.d(TAG, "isActive(...) activity != null tag " + tag);
//ToastUtils.show("activity != null tag " + tag);
//判断是否为 BaseActivity,如果已经销毁,则移除
if (iWinBoll.getActivity().isFinishing() || iWinBoll.getActivity().isDestroyed()) {
@@ -158,12 +192,13 @@ public class WinBollActivityManager {
return true;
}
} else {
LogUtils.d(TAG, String.format("isActive(...) activity == null\ntag : %s", tag));
LogUtils.d(TAG, String.format("isActive(...) iWinBoll is null tag by %s", tag));
return false;
}
}
static IWinBollActivity getIWinBoll(String tag) {
LogUtils.d(TAG, String.format("getIWinBoll(String tag) %s", tag));
return _mapIWinBollList.get(tag);
}
@@ -171,8 +206,9 @@ public class WinBollActivityManager {
// 找到tag 绑定的 BaseActivity ,通过 getTaskId() 移动到前台
//
public <T extends IWinBollActivity> void resumeActivity(Context context, String tag) {
LogUtils.d(TAG, "resumeActivty");
LogUtils.d(TAG, "resumeActivity(Context context, String tag)");
T iWinBoll = (T)getIWinBoll(tag);
LogUtils.d(TAG, String.format("iWinBoll.getTag() %s", iWinBoll.getTag()));
//LogUtils.d(TAG, "activity " + activity.getTag());
if (iWinBoll != null && !iWinBoll.getActivity().isFinishing() && !iWinBoll.getActivity().isDestroyed()) {
resumeActivity(context, iWinBoll);
@@ -183,16 +219,18 @@ public class WinBollActivityManager {
// 找到tag 绑定的 BaseActivity ,通过 getTaskId() 移动到前台
//
public <T extends IWinBollActivity> void resumeActivity(Context context, T iWinBoll) {
ActivityManager am = (ActivityManager) iWinBoll.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
LogUtils.d(TAG, "resumeActivity(Context context, T iWinBoll)");
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
//返回启动它的根任务home 或者 MainActivity
Intent intent = new Intent(context, iWinBoll.getClass());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
Intent intent = new Intent(mContext, iWinBoll.getClass());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
stackBuilder.addNextIntentWithParentStack(intent);
stackBuilder.startActivities();
//moveTaskToFront(YourTaskId, 0);
LogUtils.d(TAG, "am.moveTaskToFront");
//ToastUtils.show("resumeActivity am.moveTaskToFront");
LogUtils.d(TAG, String.format("iWinBoll.getActivity().getTaskId() %d", iWinBoll.getActivity().getTaskId()));
am.moveTaskToFront(iWinBoll.getActivity().getTaskId(), ActivityManager.MOVE_TASK_NO_USER_ACTION);
LogUtils.d(TAG, "am.moveTaskToFront");
}
@@ -245,7 +283,7 @@ public class WinBollActivityManager {
// ★0 1 2 [3] 4 >> 2
// ★0 1 2 3 [4] >> 3
// ★:[0] >> 直接关闭当前窗口
LogUtils.d(TAG, "finish no yet.");
//LogUtils.d(TAG, "finish no yet.");
IWinBollActivity preIWinBoll = getPreIWinBoll(iWinBoll);
iWinBoll.getActivity().finish();
if (preIWinBoll != null) {
@@ -268,7 +306,7 @@ public class WinBollActivityManager {
for (Map.Entry<String, IWinBollActivity> entity : _mapIWinBollList.entrySet()) {
if (entity.getKey().equals(iWinBoll.getTag())) {
bingo = true;
LogUtils.d(TAG, "bingo");
//LogUtils.d(TAG, "bingo");
break;
}
preIWinBoll = entity.getValue();

View File

@@ -10,8 +10,8 @@
<shape android:shape="rectangle" >
<gradient
android:angle="270"
android:endColor="@color/colorAccent"
android:startColor="@color/colorAccent" />
android:endColor="#0F000000"
android:startColor="#0F000000" />
<corners
android:bottomLeftRadius="6dip"
android:bottomRightRadius="6dip"

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#ff000000"
android:pathData="M4,1C2.89,1 2,1.89 2,3V7C2,8.11 2.89,9 4,9H1V11H13V9H10C11.11,9 12,8.11 12,7V3C12,1.89 11.11,1 10,1H4M4,3H10V7H4V3M3,12V14H5V12H3M14,13C12.89,13 12,13.89 12,15V19C12,20.11 12.89,21 14,21H11V23H23V21H20C21.11,21 22,20.11 22,19V15C22,13.89 21.11,13 20,13H14M3,15V17H5V15H3M14,15H20V19H14V15M3,18V20H5V18H3M6,18V20H8V18H6M9,18V20H11V18H9Z"/>
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#ff000000"
android:pathData="M4,1C2.89,1 2,1.89 2,3V7C2,8.11 2.89,9 4,9H1V11H13V9H10C11.11,9 12,8.11 12,7V3C12,1.89 11.11,1 10,1H4M4,3H10V7H4V3M14,13C12.89,13 12,13.89 12,15V19C12,20.11 12.89,21 14,21H11V23H23V21H20C21.11,21 22,20.11 22,19V15C22,13.89 21.11,13 20,13H14M3.88,13.46L2.46,14.88L4.59,17L2.46,19.12L3.88,20.54L6,18.41L8.12,20.54L9.54,19.12L7.41,17L9.54,14.88L8.12,13.46L6,15.59L3.88,13.46M14,15H20V19H14V15Z"/>
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#ff000000"
android:pathData="M22,6C22,4.9 21.1,4 20,4H4C2.9,4 2,4.9 2,6V18C2,19.1 2.9,20 4,20H20C21.1,20 22,19.1 22,18V6M20,6L12,11L4,6H20M20,18H4V8L12,13L20,8V18Z"/>
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#ff000000"
android:pathData="M24,7H22V13H24V7M24,15H22V17H24V15M20,6C20,4.9 19.1,4 18,4H2C0.9,4 0,4.9 0,6V18C0,19.1 0.9,20 2,20H18C19.1,20 20,19.1 20,18V6M18,6L10,11L2,6H18M18,18H2V8L10,13L18,8V18Z"/>
</vector>

View File

@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:clickable="true"
android:layout_width="24dp"
android:layout_height="24dp">
<item android:drawable="@drawable/ic_launcher_background"/>
<item
android:clickable="true">
<item
android:width="256dp"
android:height="256dp"
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
android:drawable="@drawable/ic_launcher_foreground"/>
android:drawable="@drawable/ic_winboll_logo">
</item>
</layer-list>

View File

@@ -5,7 +5,7 @@
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#FF005C12"
android:fillColor="@color/colorPrimary"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:clickable="true">
<item
android:width="256dp"
android:height="256dp"
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
android:drawable="@drawable/ic_winboll_logo">
</item>
</layer-list>

View File

@@ -0,0 +1,27 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path
android:fillColor="#FF1E9B54"
android:strokeColor="#FFF8E733"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M254.63 35.45C374.95 35.45 473.38 133.89 473.38 254.2 473.38 374.51 374.95 472.95 254.63 472.95 134.32 472.95 35.88 374.51 35.88 254.2 35.88 133.89 134.32 35.45 254.63 35.45"/>
<path
android:fillColor="#FF000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M257.28 361.25C266.56 361.25 274.14 368.84 274.14 378.11 274.14 387.39 266.56 394.98 257.28 394.98 248.01 394.98 240.42 387.39 240.42 378.11 240.42 368.84 248.01 361.25 257.28 361.25"/>
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="30.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M182.16 214.09C181.42 199.71 182.42 177.87 207.64 155.49 213.64 150.16 220.13 146.12 226.28 143.08 238.64 136.97 249.62 134.91 252.55 134.56 252.7 134.54 252.83 134.53 252.94 134.52 253.05 134.51 253.14 134.5 253.2 134.5 255.01 134.48 294.9 136.66 313.05 160.43 332.29 185.63 344.82 221.3 300.07 263.56 263.08 298.49 258.36 318 258.54 317.72"/>
</vector>

View File

@@ -0,0 +1,41 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path
android:fillColor="#FF1E9B54"
android:strokeColor="#FFF8E733"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M254.63 35.45C374.95 35.45 473.38 133.89 473.38 254.2 473.38 374.51 374.95 472.95 254.63 472.95 134.32 472.95 35.88 374.51 35.88 254.2 35.88 133.89 134.32 35.45 254.63 35.45"/>
<path
android:fillColor="#FFFFFFFF"
android:strokeColor="#FF000000"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M151.49 130.96C151.49 130.96 348.53 130.96 348.53 130.96 348.53 130.96 348.53 393.46 348.53 393.46 348.53 393.46 151.49 393.46 151.49 393.46 151.49 393.46 151.49 130.96 151.49 130.96"/>
<path
android:fillColor="#FFFFFFFF"
android:strokeColor="#FF000000"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M186.28 207.75C186.28 207.75 304.95 207.75 304.95 207.75 304.95 207.75 304.95 205.97 304.95 205.97 304.95 205.97 186.28 205.97 186.28 205.97 186.28 205.97 186.28 207.75 186.28 207.75"/>
<path
android:fillColor="#FFFFFFFF"
android:strokeColor="#FF000000"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M186.28 263.52C186.28 263.52 304.95 263.52 304.95 263.52 304.95 263.52 304.95 264.41 304.95 264.41 304.95 264.41 186.28 264.41 186.28 264.41 186.28 264.41 186.28 263.52 186.28 263.52"/>
<path
android:fillColor="#FFFFFFFF"
android:strokeColor="#FF000000"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M186.28 323.62C186.28 323.62 304.95 323.62 304.95 323.62 304.95 323.62 304.95 320.62 304.95 320.62 304.95 320.62 186.28 320.62 186.28 320.62 186.28 320.62 186.28 323.62 186.28 323.62"/>
</vector>

View File

@@ -0,0 +1,48 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path
android:fillColor="#FF1E9B54"
android:strokeColor="#FFF8E733"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M254.63 35.45C374.95 35.45 473.38 133.89 473.38 254.2 473.38 374.51 374.95 472.95 254.63 472.95 134.32 472.95 35.88 374.51 35.88 254.2 35.88 133.89 134.32 35.45 254.63 35.45"/>
<path
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="1.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M257.28 361.25C266.56 361.25 274.14 368.84 274.14 378.11 274.14 387.39 266.56 394.98 257.28 394.98 248.01 394.98 240.42 387.39 240.42 378.11 240.42 368.84 248.01 361.25 257.28 361.25"/>
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="30.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M182.16 214.09C181.42 199.71 182.42 177.87 207.64 155.49 213.64 150.16 220.13 146.12 226.28 143.08 238.64 136.97 249.62 134.91 252.55 134.56 252.7 134.54 252.83 134.53 252.94 134.52 253.05 134.51 253.14 134.5 253.2 134.5 255.01 134.48 294.9 136.66 313.05 160.43 332.29 185.63 344.82 221.3 300.07 263.56 263.08 298.49 258.36 318 258.54 317.72"/>
<path
android:fillColor="#00000000"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="30.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M103.77 307.45C103.02 293.07 104.03 271.24 129.24 248.85 135.25 243.52 141.74 239.48 147.89 236.44 160.24 230.34 171.23 228.28 174.15 227.92 174.31 227.9 174.44 227.89 174.55 227.88 174.66 227.87 174.75 227.86 174.81 227.86 176.62 227.85 216.5 230.02 234.65 253.79 253.9 278.99 266.43 314.66 221.67 356.93 184.69 391.85 179.97 411.36 180.15 411.08"/>
<path
android:fillColor="#00000000"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="30.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M248.17 309.83C247.43 295.45 248.43 273.62 273.64 251.23 279.65 245.9 286.14 241.86 292.29 238.82 304.65 232.72 315.63 230.65 318.55 230.3 318.71 230.28 318.84 230.27 318.95 230.26 319.06 230.25 319.15 230.24 319.21 230.24 321.02 230.22 360.9 232.4 379.06 256.17 398.3 281.37 410.83 317.04 366.08 359.31 329.09 394.23 324.37 413.74 324.55 413.46"/>
<path
android:fillColor="#00000000"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="30.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M182.16 214.09C181.42 199.71 182.42 177.87 207.64 155.49 213.64 150.16 220.13 146.12 226.28 143.08 238.64 136.97 249.62 134.91 252.55 134.56 252.7 134.54 252.83 134.53 252.94 134.52 253.05 134.51 253.14 134.5 253.2 134.5 255.01 134.48 294.9 136.66 313.05 160.43 332.29 185.63 344.82 221.3 300.07 263.56 263.08 298.49 258.36 318 258.54 317.72"/>
</vector>

View File

@@ -0,0 +1,20 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path
android:fillColor="#FF1E9B54"
android:strokeColor="#FFF8E733"
android:strokeWidth="20.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M254.63 35.45C374.95 35.45 473.38 133.89 473.38 254.2 473.38 374.51 374.95 472.95 254.63 472.95 134.32 472.95 35.88 374.51 35.88 254.2 35.88 133.89 134.32 35.45 254.63 35.45"/>
<path
android:fillColor="#FFFFFFFF"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="1.0"
android:strokeLineCap="round"
android:strokeMiterLimit="10"
android:pathData="M257.28 361.25C266.56 361.25 274.14 368.84 274.14 378.11 274.14 387.39 266.56 394.98 257.28 394.98 248.01 394.98 240.42 387.39 240.42 378.11 240.42 368.84 248.01 361.25 257.28 361.25"/>
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:clickable="true">
<item android:drawable="@drawable/ic_launcher_background"/>
<item
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
android:drawable="@drawable/ic_winboll_logo"/>
</layer-list>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="180"
android:endColor="#FFFFFFFF"
android:startColor="#FFFFFFFF"
android:type="linear" />
<corners android:radius="10dp" />
</shape>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:color="#000000" /> <!-- 这里可调整边框宽度和颜色 -->
<solid android:color="@android:color/transparent" />
</shape>

View File

@@ -83,13 +83,21 @@
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<EditText
android:layout_width="50dp"
android:ems="10"
android:layout_height="wrap_content"
android:singleLine="true"
android:id="@+id/tagsearch_et"/>
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="@drawable/bg_border"
android:scrollbars="none"
android:padding="5dp"
android:layout_weight="1.0">
android:layout_weight="1.0"
android:id="@+id/viewlogHorizontalScrollView1">
<cc.winboll.studio.libappbase.views.HorizontalListView
android:layout_width="wrap_content"

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/item_minimal"
android:title="MINIMAL"
android:icon="@drawable/ic_winboll_point"
app:showAsAction="always"/>
<item
android:id="@+id/item_about"
android:title="ABOUT"
android:icon="@drawable/ic_winboll_logo"
app:showAsAction="always"/>
<item
android:id="@+id/item_help"
android:title="HELP"
android:icon="@drawable/ic_winboll_help"
app:showAsAction="always"/>
<item
android:id="@+id/item_log"
android:title="LOG"
android:icon="@drawable/ic_winboll_log"
app:showAsAction="always"/>
</menu>

1
ollama/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

View File

73
ollama/build.gradle Normal file
View File

@@ -0,0 +1,73 @@
apply plugin: 'com.android.application'
apply from: '../.winboll/winboll_app_build.gradle'
apply from: '../.winboll/winboll_lint_build.gradle'
def genVersionName(def versionName){
// 检查编译标志位配置
assert (winbollBuildProps['stageCount'] != null)
assert (winbollBuildProps['baseVersion'] != null)
// 保存基础版本号
winbollBuildProps.setProperty("baseVersion", "${versionName}");
//保存编译标志配置
FileOutputStream fos = new FileOutputStream(winbollBuildPropsFile)
winbollBuildProps.store(fos, "${winbollBuildPropsDesc}");
fos.close();
// 返回编译版本号
return "${versionName}." + winbollBuildProps['stageCount']
}
android {
compileSdkVersion 32
buildToolsVersion "32.0.0"
defaultConfig {
applicationId "cc.winboll.studio.ollama"
minSdkVersion 26
targetSdkVersion 29
versionCode 1
// versionName 更新后需要手动设置
// .winboll/winbollBuildProps.properties 文件的 stageCount=0
// Gradle编译环境下合起来的 versionName 就是 "${versionName}.0"
versionName "15.0"
if(true) {
versionName = genVersionName("${versionName}")
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api 'com.squareup.okhttp3:okhttp:4.4.1'
// 吐司类库
api 'com.github.getActivity:ToastUtils:10.5'
// Android 类库
api 'com.android.support:appcompat-v7:28.0.0' // 包含 AppCompatActivity
// https://mvnrepository.com/artifact/com.android.support/support-compat
api 'com.android.support:support-compat:28.0.0' // 保留原有依赖(可选)
// https://mvnrepository.com/artifact/com.android.support/support-v4
api 'com.android.support:support-v4:28.0.0'
// https://mvnrepository.com/artifact/com.android.support/support-media-compat
api 'com.android.support:support-media-compat:28.0.0'
// https://mvnrepository.com/artifact/com.android.support/support-core-utils
api 'com.android.support:support-core-utils:28.0.0'
// https://mvnrepository.com/artifact/com.android.support/support-core-ui
api 'com.android.support:support-core-ui:28.0.0'
// https://mvnrepository.com/artifact/com.android.support/support-fragment
api 'com.android.support:support-fragment:28.0.0'
// https://mvnrepository.com/artifact/com.android.support/recyclerview-v7
api 'com.android.support:recyclerview-v7:28.0.0'
api 'cc.winboll.studio:libappbase:15.0.9'
api 'cc.winboll.studio:libapputils:15.0.11'
}

8
ollama/build.properties Normal file
View File

@@ -0,0 +1,8 @@
#Created by .winboll/winboll_app_build.gradle
#Fri Mar 28 05:09:21 HKT 2025
stageCount=1
libraryProject=
baseVersion=15.0
publishVersion=15.0.0
buildCount=0
baseBetaVersion=15.0.1

21
ollama/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application>
<!-- Put flavor specific code here -->
</application>
</manifest>

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ollama +</string>
</resources>

View File

@@ -0,0 +1,41 @@
<?xml version='1.0' encoding='utf-8'?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="cc.winboll.studio.ollama">
<!-- 拥有完全的网络访问权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/MyAppTheme"
android:resizeableActivity="true"
android:name=".App"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="android.max_aspect"
android:value="4.0"/>
<activity android:name=".GlobalApplication$CrashActivity"/>
</application>
</manifest>

View File

@@ -0,0 +1,334 @@
package cc.winboll.studio.ollama;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cc.winboll.studio.libappbase.GlobalApplication;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
public class App extends GlobalApplication {
private static Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());
@Override
public void onCreate() {
super.onCreate();
//CrashHandler.getInstance().registerGlobal(this);
//CrashHandler.getInstance().registerPart(this);
}
public static void write(InputStream input, OutputStream output) throws IOException {
byte[] buf = new byte[1024 * 8];
int len;
while ((len = input.read(buf)) != -1) {
output.write(buf, 0, len);
}
}
public static void write(File file, byte[] data) throws IOException {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) parent.mkdirs();
ByteArrayInputStream input = new ByteArrayInputStream(data);
FileOutputStream output = new FileOutputStream(file);
try {
write(input, output);
} finally {
closeIO(input, output);
}
}
public static String toString(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
write(input, output);
try {
return output.toString("UTF-8");
} finally {
closeIO(input, output);
}
}
public static void closeIO(Closeable... closeables) {
for (Closeable closeable : closeables) {
try {
if (closeable != null) closeable.close();
} catch (IOException ignored) {}
}
}
public static class CrashHandler {
public static final UncaughtExceptionHandler DEFAULT_UNCAUGHT_EXCEPTION_HANDLER = Thread.getDefaultUncaughtExceptionHandler();
private static CrashHandler sInstance;
private PartCrashHandler mPartCrashHandler;
public static CrashHandler getInstance() {
if (sInstance == null) {
sInstance = new CrashHandler();
}
return sInstance;
}
public void registerGlobal(Context context) {
registerGlobal(context, null);
}
public void registerGlobal(Context context, String crashDir) {
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandlerImpl(context.getApplicationContext(), crashDir));
}
public void unregister() {
Thread.setDefaultUncaughtExceptionHandler(DEFAULT_UNCAUGHT_EXCEPTION_HANDLER);
}
public void registerPart(Context context) {
unregisterPart(context);
mPartCrashHandler = new PartCrashHandler(context.getApplicationContext());
MAIN_HANDLER.postAtFrontOfQueue(mPartCrashHandler);
}
public void unregisterPart(Context context) {
if (mPartCrashHandler != null) {
mPartCrashHandler.isRunning.set(false);
mPartCrashHandler = null;
}
}
private static class PartCrashHandler implements Runnable {
private final Context mContext;
public AtomicBoolean isRunning = new AtomicBoolean(true);
public PartCrashHandler(Context context) {
this.mContext = context;
}
@Override
public void run() {
while (isRunning.get()) {
try {
Looper.loop();
} catch (final Throwable e) {
e.printStackTrace();
if (isRunning.get()) {
MAIN_HANDLER.post(new Runnable(){
@Override
public void run() {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
}
});
} else {
if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else {
throw new RuntimeException(e);
}
}
}
}
}
}
private static class UncaughtExceptionHandlerImpl implements UncaughtExceptionHandler {
private static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss");
private final Context mContext;
private final File mCrashDir;
public UncaughtExceptionHandlerImpl(Context context, String crashDir) {
this.mContext = context;
this.mCrashDir = TextUtils.isEmpty(crashDir) ? new File(mContext.getExternalCacheDir(), "crash") : new File(crashDir);
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
try {
String log = buildLog(throwable);
writeLog(log);
try {
Intent intent = new Intent(mContext, CrashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_TEXT, log);
mContext.startActivity(intent);
} catch (Throwable e) {
e.printStackTrace();
writeLog(e.toString());
}
throwable.printStackTrace();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
} catch (Throwable e) {
if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null) DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
}
}
private String buildLog(Throwable throwable) {
String time = DATE_FORMAT.format(new Date());
String versionName = "unknown";
long versionCode = 0;
try {
PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
versionName = packageInfo.versionName;
versionCode = Build.VERSION.SDK_INT >= 28 ? packageInfo.getLongVersionCode() : packageInfo.versionCode;
} catch (Throwable ignored) {}
LinkedHashMap<String, String> head = new LinkedHashMap<String, String>();
head.put("Time Of Crash", time);
head.put("Device", String.format("%s, %s", Build.MANUFACTURER, Build.MODEL));
head.put("Android Version", String.format("%s (%d)", Build.VERSION.RELEASE, Build.VERSION.SDK_INT));
head.put("App Version", String.format("%s (%d)", versionName, versionCode));
head.put("Kernel", getKernel());
head.put("Support Abis", Build.VERSION.SDK_INT >= 21 && Build.SUPPORTED_ABIS != null ? Arrays.toString(Build.SUPPORTED_ABIS): "unknown");
head.put("Fingerprint", Build.FINGERPRINT);
StringBuilder builder = new StringBuilder();
for (String key : head.keySet()) {
if (builder.length() != 0) builder.append("\n");
builder.append(key);
builder.append(" : ");
builder.append(head.get(key));
}
builder.append("\n\n");
builder.append(Log.getStackTraceString(throwable));
return builder.toString();
}
private void writeLog(String log) {
String time = DATE_FORMAT.format(new Date());
File file = new File(mCrashDir, "crash_" + time + ".txt");
try {
write(file, log.getBytes("UTF-8"));
} catch (Throwable e) {
e.printStackTrace();
}
}
private static String getKernel() {
try {
return App.toString(new FileInputStream("/proc/version")).trim();
} catch (Throwable e) {
return e.getMessage();
}
}
}
}
public static final class CrashActivity extends Activity {
private String mLog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_DeviceDefault);
setTitle("App Crash");
mLog = getIntent().getStringExtra(Intent.EXTRA_TEXT);
ScrollView contentView = new ScrollView(this);
contentView.setFillViewport(true);
HorizontalScrollView horizontalScrollView = new HorizontalScrollView(this);
TextView textView = new TextView(this);
int padding = dp2px(16);
textView.setPadding(padding, padding, padding, padding);
textView.setText(mLog);
textView.setTextIsSelectable(true);
textView.setTypeface(Typeface.DEFAULT);
textView.setLinksClickable(true);
horizontalScrollView.addView(textView);
contentView.addView(horizontalScrollView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
setContentView(contentView);
}
private void restart() {
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
private static int dp2px(float dpValue) {
final float scale = Resources.getSystem().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, android.R.id.copy, 0, android.R.string.copy)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.copy:
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(getPackageName(), mLog));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
restart();
}
}
}

View File

@@ -0,0 +1,88 @@
package cc.winboll.studio.ollama;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public final static int MSG_APPEND = 0;
private Handler _Handler = new Handler(Looper.getMainLooper());
private TextView mtvMessage;
private EditText metAsk;
private Button mbtSend;
private ScrollView msvMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mtvMessage = (TextView) findViewById(R.id.message_tv);
metAsk = (EditText) findViewById(R.id.ask_et);
mbtSend = (Button) findViewById(R.id.send_bt);
msvMessage = findViewById(R.id.message_sv);
mbtSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendQuestion();
}
});
}
//
// 设置输入框获得焦点的类
//
// static class MyHandler extends Handler {
// WeakReference<MainActivity> mActivity;
// MyHandler(MainActivity activity) {
// mActivity = new WeakReference<MainActivity>(activity);
// }
// public void handleMessage(Message msg) {
// MainActivity theActivity = mActivity.get();
// switch (msg.what) {
// case MSG_APPEND:
// theActivity.mtvMessage.append((String)msg.obj);
// break;
// default:
// break;
// }
// super.handleMessage(msg);
// }
// }
private void sendQuestion() {
final String question = metAsk.getText().toString().trim();
if (!question.equals("")) {
mtvMessage.append("\n\nI " + metAsk.getText().toString() + "\nOllama : ");
metAsk.setText("");
new OllamaClient.SyncAskThread(question, new OllamaClient.OnAnswerCallback() {
@Override
public void onAnswer(final String answer) {
_Handler.post(new Runnable() {
@Override
public void run() {
mtvMessage.append(answer);
msvMessage.post(new Runnable(){
@Override
public void run() {
msvMessage.fullScroll(View.FOCUS_DOWN);
}
});
}
});
}
}).start();
}
}
}

View File

@@ -0,0 +1,223 @@
package cc.winboll.studio.ollama;
/**
* @Author ZhanGSKen@AliYun.Com
* @Date 2025/03/27 19:55:28
* @Describe 简单Http协议访问客户端
*/
import cc.winboll.studio.libappbase.LogUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.Source;
import org.json.JSONException;
import org.json.JSONObject;
public class OllamaClient {
public static final String TAG = "OllamaClient";
private static final String API_BASE_URL = "https://ollama-api.winboll.cc";
//private static final String API_BASE_URL = "http://10.8.0.10:11434";
//private static final OkHttpClient client = new OkHttpClient();
private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
// 1. 生成文本示例
// static void generateText(String prompt, String model) {
// String url = API_BASE_URL + "/api/generate";
// try {
// JSONObject payload = new JSONObject()
// .put("model", model)
// .put("prompt", prompt)
// .put("temperature", 0.7)
// .put("max_tokens", 200);
//
// Request request = new Request.Builder()
// .url(url)
// .post(RequestBody.create(payload.toString(), MediaType.get("application/json")))
// .build();
//
// Response response = client.newCall(request).execute();
// if (response.isSuccessful()) {
// String result = response.body().string();
// String formattedStream = OllamaResponseFormatter.formatStreamingResponse(result);
//
// // 输出示例:
//// [2025-03-27T19:34:29.274955439Z] [llama3.1:8b] It looks like you might have miss
//// [2025-03-27T19:34:30.482553089Z] [llama3.1:8b] pelled the word "Ollama" or perhaps said something that is not a standard word in the English language. However, I'm here to provide information and assistance on various topics, so please let me know what you meant by "Ollama." Was it related to a name, place, movie, game, or something else?
//
// LogUtils.d(TAG, formattedStream);
//// JSONObject json = new JSONObject(result);
//// LogUtils.d(TAG, "生成结果: " + json.getString("response"));
// //System.out.println("生成结果: " + json.getString("response"));
// } else {
// LogUtils.d(TAG, "请求失败: " + response.code());
// //System.out.println("请求失败: " + response.code() + " " + response.message());
// }
// } catch (JSONException|IOException e) {
// LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
// }
// }
// 实时输出流式响应的函数
static void generateTextStream(String prompt, String model, final OnAnswerCallback callback) {
String url = API_BASE_URL + "/api/generate";
try {
JSONObject payload = new JSONObject()
.put("model", model)
.put("prompt", prompt)
.put("temperature", 0.7)
.put("max_tokens", 200)
.put("stream", true); // 启用流式响应
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(payload.toString(), MediaType.get("application/json")))
.build();
LogUtils.d(TAG, "Request request");
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
LogUtils.d(TAG, "请求失败: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
LogUtils.d(TAG, "请求失败: " + response.code());
return;
}
try (ResponseBody body = response.body()) {
if (body == null) return;
// 实时流式解析
LogUtils.d(TAG, "实时流式解析");
Source source = body.source();
Buffer buffer = new Buffer();
StringBuilder fullResponse = new StringBuilder();
boolean isDone = false;
while (!isDone && source.read(buffer, 1024) != -1) {
//LogUtils.d(TAG, "!isDone");
String chunk = buffer.readUtf8();
String[] lines = chunk.split("\n");
for (String line : lines) {
LogUtils.d(TAG, line);
if (line.trim().startsWith("{\"model\":")) {
LogUtils.d(TAG, line);
String jsonStr = line;
if (jsonStr.equals("[DONE]")) {
isDone = true;
LogUtils.d(TAG, "流式生成完成");
break;
}
try {
//LogUtils.d(TAG, jsonStr);
JSONObject json = new JSONObject(jsonStr);
//LogUtils.d(TAG, json.toString());
String responseText = json.getString("response");
//LogUtils.d(TAG, responseText);
fullResponse.append(responseText);
// 实时输出
callback.onAnswer(responseText);
LogUtils.d(TAG, "实时响应: " + responseText);
// 处理完成状态
if (json.getBoolean("done")) {
isDone = true;
String doneReason = json.optString("done_reason", "unknown");
LogUtils.d(TAG, "生成完成 (原因: " + doneReason + ")");
LogUtils.d(TAG, "完整回答: " + fullResponse.toString());
}
} catch (JSONException e) {
LogUtils.d(TAG, "JSON解析错误: " + e.getMessage());
}
}
}
}
}
}
});
} catch (JSONException e) {
LogUtils.d(TAG, "JSON格式错误: " + e.getMessage());
}
}
// 2. 获取模型列表示例
static void getModelList() {
String url = API_BASE_URL + "/v1/models";
LogUtils.d(TAG, "url : " + url);
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
LogUtils.d(TAG, response.body().string());
// JSONArray models = new JSONArray(response.body().string());
// //System.out.println("可用模型列表:");
// LogUtils.d(TAG, "可用模型列表:");
// for (int i = 0; i < models.length(); i++) {
// JSONObject model = models.getJSONObject(i);
// LogUtils.d(TAG, "- " + model.getString("name") + " (" + model.getString("size") + ")");
// //System.out.println("- " + model.getString("name") + " (" + model.getString("size") + ")");
// }
} else {
LogUtils.d(TAG, "获取模型列表失败: " + response.code());
//System.out.println("获取模型列表失败: " + response.code());
}
} catch (IOException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
}
static void unittest(String ask, OnAnswerCallback callback) {
// 获取模型列表
getModelList();
// 生成文本
generateTextStream(ask, "llama3.1:8b", callback);
}
public static class SyncAskThread extends Thread {
private String ask;
private OnAnswerCallback callback;
public SyncAskThread(String ask, OnAnswerCallback callback) {
this.ask = ask;
this.callback = callback;
}
@Override
public void run() {
super.run();
LogUtils.d(TAG, "run() start.");
unittest(ask, callback);
LogUtils.d(TAG, "run() end.");
}
}
public interface OnAnswerCallback {
void onAnswer(String answer);
}
}

View File

@@ -0,0 +1,72 @@
package cc.winboll.studio.ollama;
/**
* @Author ZhanGSKen@AliYun.Com
* @Date 2025/03/28 03:38:50
*/
import org.json.JSONArray;
import org.json.JSONObject;
public class OllamaResponseFormatter {
public static final String TAG = "OllamaResponseFormatter";
// 处理模型列表响应
public static String formatModelList(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
JSONArray models = json.getJSONArray("data");
StringBuilder sb = new StringBuilder();
sb.append("可用模型列表:\n");
for (int i = 0; i < models.length(); i++) {
JSONObject model = models.getJSONObject(i);
String modelId = model.getString("id");
sb.append(String.format("-%d. %s\n", i + 1, modelId));
}
return sb.toString();
} catch (Exception e) {
return "格式解析错误: " + e.getMessage();
}
}
// 处理流式生成文本响应
public static String formatStreamingResponse(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
StringBuilder sb = new StringBuilder();
String responseText = json.getString("response");
boolean isDone = json.getBoolean("done");
// 添加时间戳和模型标识
String timestamp = json.getString("created_at");
String modelName = json.getString("model");
sb.append(String.format("[%s] [%s] ", timestamp, modelName));
// 处理响应内容
if (responseText.isEmpty() && isDone) {
sb.append("生成完成\n");
} else {
sb.append(responseText);
if (isDone) {
String doneReason = json.optString("done_reason", "unknown");
sb.append(String.format(" (完成原因: %s)\n", doneReason));
}
}
return sb.toString();
} catch (Exception e) {
return "格式解析错误: " + e.getMessage();
}
}
// 使用示例
public static void main(String[] args) {
// 模型列表测试
String modelListJson = "{\"object\":\"list\",\"data\":[{...}]}";
System.out.println(formatModelList(modelListJson));
// 流式响应测试
String streamingJson = "{\"model\":\"llama3.1:8b\",\"created_at\":\"2025-03-27T19:34:29.274955439Z\",\"response\":\"It\",\"done\":false}";
System.out.println(formatStreamingResponse(streamingJson));
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:gravity="center_vertical|center_horizontal"
android:layout_weight="1.0"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.0"
android:id="@+id/message_sv">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Asking Ollama ..."
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/message_tv"/>
</ScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<EditText
android:layout_width="0dp"
android:ems="10"
android:layout_height="wrap_content"
android:id="@+id/ask_et"
android:layout_weight="1.0"
android:text="Hello, World!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="@+id/send_bt"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.0">
<cc.winboll.studio.libappbase.LogView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text"
android:id="@+id/logview"/>
</LinearLayout>
</LinearLayout>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorAccent">@color/colorAccent</item>
<item name="android:navigationBarColor">?android:colorPrimary</item>
</style>
</resources>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#009688</color>
<color name="colorPrimaryDark">#00796B</color>
<color name="colorAccent">#FF9800</color>
</resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ollama</string>
</resources>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
</resources>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">10.8.0.10</domain>
</domain-config>
</network-security-config>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application>
<!-- Put flavor specific code here -->
</application>
</manifest>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Put flavor specific strings here -->
</resources>

View File

@@ -57,3 +57,7 @@
// AndroidXDemo 项目编译设置
//include ':androidxdemo'
//rootProject.name = "androidxdemo"
// Ollama 项目编译设置
//include ':ollama'
//rootProject.name = "ollama"