This commit is contained in:
icewithcola 2024-05-24 12:48:34 +08:00
parent a1cccd9890
commit daeaee0d3e
24 changed files with 488 additions and 379 deletions

View file

@ -22,7 +22,20 @@
<State />
</entry>
<entry key="app">
<State />
<State>
<runningDeviceTargetSelectedWithDropDown>
<Target>
<type value="RUNNING_DEVICE_TARGET" />
<deviceKey>
<Key>
<type value="VIRTUAL_DEVICE_PATH" />
<value value="$USER_HOME$/.android/avd/Resizable_Experimental_API_34.avd" />
</Key>
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-05-24T03:51:09.939185298Z" />
</State>
</entry>
</value>
</component>

View file

@ -11,8 +11,8 @@ android {
applicationId = "uk.kagurach.android101"
minSdk = 31
targetSdk = 34
versionCode = 151
versionName = "1.5.1"
versionCode = 153
versionName = "1.5.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

View file

@ -1,9 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
@ -12,8 +13,18 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Android101"
tools:targetApi="31">
android:theme="@style/Theme.Android101">
<receiver
android:name=".vibrationBroadcastReceiver.vibrationBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.VIBRATE">
<intent-filter>
<action android:name="uk.kagurach.android101.vibrationBroadcastReceiver"/>
</intent-filter>
</receiver>
<activity
android:name=".Page4OtherActivity"
android:exported="false" />

View file

@ -3,84 +3,82 @@ package uk.kagurach.android101
import android.content.Context
import kotlin.math.pow
fun Kaculate(src: String,ctx :Context) : String{
if (src.isBlank()){
fun Kaculate(src: String, ctx: Context): String {
if (src.isBlank()) {
return src
}
val OpList = charArrayOf('+','-','x','/','^')
val OpList = charArrayOf('+', '-', 'x', '/', '^')
var numStack = floatArrayOf()
var opStack = charArrayOf()
var opStack = charArrayOf()
var _curnum = ""
for (i in src.indices){
if (src[i] in '0'..'9' || src[i] == '.'){
for (i in src.indices) {
if (src[i] in '0'..'9' || src[i] == '.') {
_curnum += src[i]
}
else if (src[i] in OpList){
} else if (src[i] in OpList) {
try {
numStack += _curnum.toFloat()
_curnum = ""
}catch (e:Exception){
ToastHelper.ShowToast(e.toString(),ctx)
} catch (e: Exception) {
ToastHelper.ShowToast(e.toString(), ctx)
return src
}
opStack += src[i]
}
else{
ToastHelper.ShowToast("Unknown input char:" + src[i].toString(),ctx)
opStack += src[i]
} else {
ToastHelper.ShowToast("Unknown input char:" + src[i].toString(), ctx)
return src
}
}
if (_curnum.isNotEmpty()){
if (_curnum.isNotEmpty()) {
try {
numStack += _curnum.toFloat()
}catch (e:Exception){
ToastHelper.ShowToast(e.toString(),ctx)
} catch (e: Exception) {
ToastHelper.ShowToast(e.toString(), ctx)
return src
}
}
if (numStack.size != opStack.size+1 ){
ToastHelper.ShowToast("Ops and nums Not Match!",ctx)
if (numStack.size != opStack.size + 1) {
ToastHelper.ShowToast("Ops and nums Not Match!", ctx)
return src
}
// ^
if ('^' in opStack){
if ('^' in opStack) {
var intStackCurr = 0
for (i in opStack.indices){
if (opStack[i]!='^'){
intStackCurr ++
for (i in opStack.indices) {
if (opStack[i] != '^') {
intStackCurr++
continue
}
val a = numStack[intStackCurr]
val b = numStack[intStackCurr+1]
val b = numStack[intStackCurr + 1]
numStack[intStackCurr] = a.pow(b)
numStack = dropAtIdx(numStack,intStackCurr+1)
numStack = dropAtIdx(numStack, intStackCurr + 1)
}
}
// x and /
var intStackCurr = 0
for (i in opStack.indices){
if (opStack[i]!='x'&&opStack[i]!='/'){
intStackCurr ++
for (i in opStack.indices) {
if (opStack[i] != 'x' && opStack[i] != '/') {
intStackCurr++
continue
}
val a = numStack[intStackCurr]
val b = numStack[intStackCurr+1]
val b = numStack[intStackCurr + 1]
if (opStack[i] == 'x'){
numStack[intStackCurr] = a*b
}else{
numStack[intStackCurr] = a/b
if (opStack[i] == 'x') {
numStack[intStackCurr] = a * b
} else {
numStack[intStackCurr] = a / b
}
numStack = dropAtIdx(numStack,intStackCurr+1)
numStack = dropAtIdx(numStack, intStackCurr + 1)
}
// + and -
@ -88,10 +86,10 @@ fun Kaculate(src: String,ctx :Context) : String{
for (i in opStack) {
if (i == '+') {
numStack[0] += numStack[1]
numStack = dropAtIdx(numStack,1)
} else if (i=='-') {
numStack = dropAtIdx(numStack, 1)
} else if (i == '-') {
numStack[0] -= numStack[1]
numStack = dropAtIdx(numStack,1)
numStack = dropAtIdx(numStack, 1)
}
}
}
@ -99,14 +97,14 @@ fun Kaculate(src: String,ctx :Context) : String{
return numStack[0].toString()
}
private fun dropAtIdx(array: FloatArray, idx:Int): FloatArray{
if (idx>array.size){
private fun dropAtIdx(array: FloatArray, idx: Int): FloatArray {
if (idx > array.size) {
throw IndexOutOfBoundsException()
}
var newArray = floatArrayOf()
for (i in array.indices){
if (i!=idx){
for (i in array.indices) {
if (i != idx) {
newArray += array[i]
}
}

View file

@ -27,6 +27,7 @@ import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
PageHelper pageHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -41,30 +42,30 @@ public class MainActivity extends AppCompatActivity {
}
@Override
protected void onResume(){
protected void onResume() {
super.onResume();
TextView tv = findViewById(R.id.tv_hello);
textViewAppendString(tv,"Starting Initialize");
textViewAppendString(tv, "Starting Initialize");
if (Build.VERSION.SDK_INT >= 33) {
textViewAppendString(tv,"Find api > 33, checking permission");
textViewAppendString(tv, "Find api > 33, checking permission");
if (ContextCompat
.checkSelfPermission
(MainActivity.this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
textViewAppendString(tv,"Acquiring POST_NOTIFICATIONS");
(MainActivity.this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
textViewAppendString(tv, "Acquiring POST_NOTIFICATIONS");
ActivityCompat.requestPermissions
(MainActivity.this,
new String[]{Manifest.permission.POST_NOTIFICATIONS},
101);
}
textViewAppendString(tv,"Check Finished");
textViewAppendString(tv,"提示:常桉有惊喜");
textViewAppendString(tv, "Check Finished");
textViewAppendString(tv, "提示:常桉有惊喜");
}
textViewAppendString(tv,"*************************\nfinished");
textViewAppendString(tv, "*************************\nfinished");
// Initialize Page Helper
pageHelper = new PageHelper(this,null,MainActivity2.class,this);
pageHelper = new PageHelper(this, null, MainActivity2.class, this);
Button button = findViewById(R.id.Page1NextPage);
button.setEnabled(true);
@ -72,28 +73,15 @@ public class MainActivity extends AppCompatActivity {
button.setOnLongClickListener(new LongClickHandler(this));
}
private void textViewAppendString(@NonNull TextView tv, String s){
private void textViewAppendString(@NonNull TextView tv, String s) {
String last = tv.getText().toString();
if (!last.endsWith("\n")){
if (!last.endsWith("\n")) {
last += "\n";
}
last += s;
tv.setText(last);
}
private final class LongClickHandler implements View.OnLongClickListener
{
LongClickHandler(Context ctx){
context = ctx;
}
Context context;
@Override
public boolean onLongClick(View v){
CreateShortcut(context);
return false;
}
}
private void CreateShortcut(Context context) {
ShortcutManager shortcutManager =
this.getSystemService(ShortcutManager.class);
@ -102,7 +90,7 @@ public class MainActivity extends AppCompatActivity {
try {
pinShortcutInfo =
new ShortcutInfo.Builder(context, "start_TODO").build();
}catch (Exception e){
} catch (Exception e) {
Log.e("ShortCutManager", Arrays.toString(e.getStackTrace()));
return;
}
@ -117,4 +105,18 @@ public class MainActivity extends AppCompatActivity {
successCallback.getIntentSender());
}
}
private final class LongClickHandler implements View.OnLongClickListener {
Context context;
LongClickHandler(Context ctx) {
context = ctx;
}
@Override
public boolean onLongClick(View v) {
CreateShortcut(context);
return false;
}
}
}

View file

@ -23,6 +23,7 @@ public class MainActivity2 extends AppCompatActivity {
PageHelper pageHelper;
int _text_size = 70;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -33,11 +34,11 @@ public class MainActivity2 extends AppCompatActivity {
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
pageHelper = new PageHelper(this,MainActivity.class,Page3.class);
pageHelper = new PageHelper(this, MainActivity.class, Page3.class);
}
@Override
protected void onResume(){
protected void onResume() {
super.onResume();
Button button = findViewById(R.id.next_page_nav_2);
button.setOnClickListener(pageHelper.pageButtonHandler);
@ -47,17 +48,17 @@ public class MainActivity2 extends AppCompatActivity {
public void set70sp(View view) {
TextView t = findViewById(R.id.test2strview);
t.setTextSize(TypedValue.COMPLEX_UNIT_SP,_text_size);
t.setTextSize(TypedValue.COMPLEX_UNIT_SP, _text_size);
}
public void set70dp(View view) {
TextView t = findViewById(R.id.test2strview);
t.setTextSize(TypedValue.COMPLEX_UNIT_DIP,_text_size);
t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, _text_size);
}
public void set70px(View view) {
TextView t = findViewById(R.id.test2strview);
t.setTextSize(TypedValue.COMPLEX_UNIT_PX,_text_size);
t.setTextSize(TypedValue.COMPLEX_UNIT_PX, _text_size);
}
public void setColor(View view) {
@ -66,11 +67,11 @@ public class MainActivity2 extends AppCompatActivity {
EditText g_edit = findViewById(R.id.G);
EditText b_edit = findViewById(R.id.B);
int _r,_g,_b;
int _r, _g, _b;
// Here we are testing toast
if( r_edit.getText().toString().isEmpty() ||
g_edit.getText().toString().isEmpty()||
b_edit.getText().toString().isEmpty() ){
if (r_edit.getText().toString().isEmpty() ||
g_edit.getText().toString().isEmpty() ||
b_edit.getText().toString().isEmpty()) {
ToastHelper.SmartToast.ShowToast("""
Please input R,G,B within 0-255
请在大小选择下方输入0-255的RGB""",
@ -81,26 +82,27 @@ public class MainActivity2 extends AppCompatActivity {
_r = Integer.parseInt(r_edit.getText().toString());
_g = Integer.parseInt(g_edit.getText().toString());
_b = Integer.parseInt(b_edit.getText().toString());
} catch (NumberFormatException e){
ToastHelper.SmartToast.ShowToast(e.toString(),this);
} catch (NumberFormatException e) {
ToastHelper.SmartToast.ShowToast(e.toString(), this);
return;
}
if (_r>=0&&_g>=0&&_b>=0&&_r<=255&&_g<=255&&_b<=255){
t.setTextColor(Color.rgb(_r,_g,_b));
}else{
if (_r >= 0 && _g >= 0 && _b >= 0 && _r <= 255 && _g <= 255 && _b <= 255) {
t.setTextColor(Color.rgb(_r, _g, _b));
} else {
ToastHelper.SmartToast.ShowToast(
"The color: R="+_r+" G="+_g+" B="+_b+" is invalid!",this);
"The color: R=" + _r + " G=" + _g + " B=" + _b + " is invalid!", this);
}
}
public void setText(View view) {
TextView textView = findViewById(R.id.test2strview);
EditText editText = findViewById(R.id.Page2SetTestText);
String s;
try {
s = editText.getText().toString();
}catch (Exception e){
ToastHelper.SmartToast.ShowToast(e.toString(),this);
} catch (Exception e) {
ToastHelper.SmartToast.ShowToast(e.toString(), this);
return;
}
textView.setText(s);
@ -116,14 +118,14 @@ public class MainActivity2 extends AppCompatActivity {
int size;
try {
size = Integer.parseInt(ed.getText().toString());
}catch (Exception e){
ToastHelper.SmartToast.ShowToast(e.toString(),this);
} catch (Exception e) {
ToastHelper.SmartToast.ShowToast(e.toString(), this);
return;
}
_text_size = size;
sp.setText(size +"SP");
dp.setText(size +"DP");
px.setText(size +"PX");
sp.setText(size + "SP");
dp.setText(size + "DP");
px.setText(size + "PX");
}

View file

@ -9,28 +9,30 @@ import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat.getSystemService
import kotlin.random.Random
class NotificationHelper(_ctx: Context) {
val CHANNEL_ID = "DBG_PUSHER"
val name = "Debug Pusher"
var ctx: Context = _ctx
companion object { // Make notify id always increase
var notifyID = 1
}
private val notificationManager =
getSystemService(ctx,NotificationManager::class.java) as NotificationManager
getSystemService(ctx, NotificationManager::class.java) as NotificationManager
fun pushNotification(title:String,content:String) {
fun pushNotification(title: String, content: String) {
val builder = NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(content)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setStyle(NotificationCompat.BigTextStyle()
.bigText(content))
.setStyle(
NotificationCompat.BigTextStyle()
.bigText(content)
)
with(NotificationManagerCompat.from(ctx)) {
if (ActivityCompat.checkSelfPermission(
@ -55,7 +57,7 @@ class NotificationHelper(_ctx: Context) {
notificationManager.createNotificationChannel(channel)
}
protected fun deleteNotificationChannel(){
protected fun deleteNotificationChannel() {
notificationManager.deleteNotificationChannel(CHANNEL_ID)
}
}

View file

@ -14,11 +14,10 @@ import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.util.List;
public class Page3 extends AppCompatActivity {
PageHelper pageHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -30,7 +29,7 @@ public class Page3 extends AppCompatActivity {
return insets;
});
pageHelper = new PageHelper(this,MainActivity2.class,Page4.class);
pageHelper = new PageHelper(this, MainActivity2.class, Page4.class);
findViewById(R.id.P3_0).setOnClickListener(new CalculateOnClickListener());
findViewById(R.id.P3_1).setOnClickListener(new CalculateOnClickListener());
@ -59,62 +58,7 @@ public class Page3 extends AppCompatActivity {
findViewById(R.id.P3Nextpage).setOnLongClickListener(pageHelper.longClickHandler);
}
class CalculateOnClickListener implements View.OnClickListener{
@Override
public void onClick(View v){
TextView tv = findViewById(R.id.P3CalcResult);
String s = tv.getText().toString();
String o = ((Button)v).getText().toString();
Button dot = findViewById(R.id.P3Dot);
switch (o){
case "退格":
if (!s.isEmpty()){
if (s.length()==1){
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
}else {
s = s.substring(0, s.length() - 1);
dot.setEnabled(!isNumberWithDot(s));
setOpButton(s.substring(s.length()-1).matches("\\d|\\."));
}
}
break;
case "CE":
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
break;
case "=":
calc();
s = tv.getText().toString();
dot.setEnabled(!s.contains("."));
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(
!s.toLowerCase().contains("n")); // For Inf & NaN
return;
case ".":
dot.setEnabled(false);
s+='.';
break;
default:
s += o;
if (o.matches("\\d")) { // If inputted a number
setOpButton(true);
}else{ // Else an operator
dot.setEnabled(true);
setOpButton(false);
}
}
tv.setText(s);
}
}
private void setOpButton(boolean state){
private void setOpButton(boolean state) {
findViewById(R.id.P3X).setEnabled(state);
findViewById(R.id.P3Plus).setEnabled(state);
findViewById(R.id.P3Minus).setEnabled(state);
@ -122,25 +66,25 @@ public class Page3 extends AppCompatActivity {
findViewById(R.id.P3ChengFang).setEnabled(state);
}
private boolean isNumberWithDot(@NonNull String s){
if (!s.contains(".")){
private boolean isNumberWithDot(@NonNull String s) {
if (!s.contains(".")) {
return false;
}
boolean hasDot = false;
for (int i = s.length()-1; i >= 0; i--) {
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c=='+'||c=='-'||c=='x'||c=='/'||c=='^'){
if (c == '+' || c == '-' || c == 'x' || c == '/' || c == '^') {
return hasDot;
}else if (c=='.'){
} else if (c == '.') {
hasDot = true;
}
}
return hasDot;
}
private void calc(){
private void calc() {
TextView textView = findViewById(R.id.P3CalcResult);
String result = Kaculate(textView.getText().toString(),this);
String result = Kaculate(textView.getText().toString(), this);
if (result.contains(".")) { // In case of Infinity or NaN as a result
int i = 0;
@ -162,4 +106,57 @@ public class Page3 extends AppCompatActivity {
textView.setText(result);
}
class CalculateOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
TextView tv = findViewById(R.id.P3CalcResult);
String s = tv.getText().toString();
String o = ((Button) v).getText().toString();
Button dot = findViewById(R.id.P3Dot);
switch (o) {
case "退格":
if (!s.isEmpty()) {
if (s.length() == 1) {
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
} else {
s = s.substring(0, s.length() - 1);
dot.setEnabled(!isNumberWithDot(s));
setOpButton(s.substring(s.length() - 1).matches("\\d|\\."));
}
}
break;
case "CE":
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
break;
case "=":
calc();
s = tv.getText().toString();
dot.setEnabled(!s.contains("."));
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(
!s.toLowerCase().contains("n")); // For Inf & NaN
return;
case ".":
dot.setEnabled(false);
s += '.';
break;
default:
s += o;
if (o.matches("\\d")) { // If inputted a number
setOpButton(true);
} else { // Else an operator
dot.setEnabled(true);
setOpButton(false);
}
}
tv.setText(s);
}
}
}

View file

@ -1,6 +1,6 @@
package uk.kagurach.android101;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
@ -14,16 +14,19 @@ import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import uk.kagurach.android101.vibrationBroadcastReceiver.vibrationBroadcastReceiver;
public class Page4 extends AppCompatActivity {
PageHelper pageHelper;
ActivityResultLauncher mLauncher;
long startTime = 0;
long endTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -35,49 +38,47 @@ public class Page4 extends AppCompatActivity {
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
pageHelper = new PageHelper(this, Page3.class,Page5.class);
pageHelper = new PageHelper(this, Page3.class, Page5.class);
Button askAI = findViewById(R.id.P4AskAI);
askAI.setOnClickListener(new ButtonHandler());
Button nextPage = findViewById(R.id.P4PageButton);
nextPage.setOnClickListener(pageHelper.pageButtonHandler);
nextPage.setOnLongClickListener(pageHelper.longClickHandler);
mLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result!=null && result.getResultCode() == RESULT_OK ){
assert result.getData() != null;
Bundle bundle = result.getData().getExtras();
if (bundle!=null) {
String response = bundle.getString("reply");
TextView tv = findViewById(R.id.P4Result);
tv.setText(response);
}
Button vibrate = findViewById(R.id.P4Vibrate);
vibrate.setOnClickListener(new VibrateButtonHandler());
mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result != null && result.getResultCode() == RESULT_OK) {
assert result.getData() != null;
Bundle bundle = result.getData().getExtras();
if (bundle != null) {
String response = bundle.getString("reply");
TextView tv = findViewById(R.id.P4Result);
tv.setText(response);
}
endTime = System.currentTimeMillis();
TextView timetv = findViewById(R.id.P4AIRuntime);
timetv.setText("使用了" + (endTime - startTime) + "毫秒");
}
);
});
}
private void callOtherActivity(){
private void callOtherActivity() {
EditText editText = findViewById(R.id.P4Ask);
String request = editText.getText().toString();
Intent intent = new Intent(this,Page4OtherActivity.class);
Intent intent = new Intent(this, Page4OtherActivity.class);
Bundle bundle = new Bundle();
bundle.putString("request_content",request);
bundle.putString("request_content", request);
intent.putExtras(bundle);
TextView tv = findViewById(R.id.P4Result);
tv.setText("正在询问AI");
startTime = System.currentTimeMillis();
mLauncher.launch(intent);
}
private final class ButtonHandler implements View.OnClickListener
{
@Override
public void onClick(View v){
callOtherActivity();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (getCurrentFocus() != null) {
@ -87,5 +88,24 @@ public class Page4 extends AppCompatActivity {
return super.dispatchTouchEvent(ev);
}
private final class ButtonHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
callOtherActivity();
}
}
private final class VibrateButtonHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
String receivierPath = "uk.kagurach.android101.vibrationBroadcastReceiver.vibrationBroadcastReceiver";
Intent intent = new Intent(vibrationBroadcastReceiver.VIBRATION_ACTION_NAME);
ComponentName componentName = new ComponentName("uk.kagurach.android101",receivierPath);
intent.setComponent(componentName);
sendBroadcast(intent);
}
}
}

View file

@ -16,30 +16,30 @@ public class Page4OtherActivity extends AppCompatActivity {
Bundle bundle = getIntent().getExtras();
if (bundle == null) throw new NullPointerException();
String content = bundle.getString("request_content");
if (content!=null){
if (content.contains("想似")||
content.contains("相似")||
content.contains("相死")||
content.contains("想死")){
if (content != null) {
if (content.contains("想似") ||
content.contains("相似") ||
content.contains("相死") ||
content.contains("想死")) {
ToastHelper.SmartToast.ShowToast("不可以!",this);
ToastHelper.SmartToast.ShowToast("不可以!", this);
Log.wtf("呜呜","要好好活着");
Log.wtf("呜呜", "要好好活着");
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(-1);
}
content = AIAnswerService(content);
}else {
} else {
content = "对不起坏掉了";
}
Intent intent = new Intent();
Bundle bundle1 = new Bundle();
bundle1.putString("reply",content);
bundle1.putString("reply", content);
intent.putExtras(bundle1);
setResult(RESULT_OK,intent);
setResult(RESULT_OK, intent);
finish();
}
}

View file

@ -8,73 +8,70 @@ import android.content.Intent;
import android.view.View;
public class PageHelper {
public final LongClickHandler longClickHandler = new LongClickHandler();
public final PageButtonHandler pageButtonHandler = new PageButtonHandler();
private final Context _curr;
private final Class<?> _prev;
private final Class<?> _next;
private Activity _activity = null;
public final LongClickHandler longClickHandler = new LongClickHandler();
public final PageButtonHandler pageButtonHandler = new PageButtonHandler();
PageHelper(Context curr, Class<?> prev, Class<?> next){
PageHelper(Context curr, Class<?> prev, Class<?> next) {
_curr = curr;
_prev = prev;
_next = next;
}
PageHelper(Context curr, Class<?> prev, Class<?> next,Activity activity){
PageHelper(Context curr, Class<?> prev, Class<?> next, Activity activity) {
_curr = curr;
_prev = prev;
_next = next;
_activity = activity;
}
void goPrev(){
if (_prev==null){
void goPrev() {
if (_prev == null) {
return;
}
Intent myIntent = new Intent(_curr, _prev);
startActivity(_curr,myIntent,null);
startActivity(_curr, myIntent, null);
}
void goNext(){
if (_next==null){
void goNext() {
if (_next == null) {
return;
}
Intent myIntent = new Intent(_curr, _next);
startActivity(_curr,myIntent,null);
startActivity(_curr, myIntent, null);
}
void goNextFinish(){
if (_activity == null){
void goNextFinish() {
if (_activity == null) {
throw new IllegalStateException("activity is null, cannot finish the activity");
}
if (_next==null){
if (_next == null) {
return;
}
Intent myIntent = new Intent(_curr, _next);
startActivity(_curr,myIntent,null);
startActivity(_curr, myIntent, null);
_activity.finish();
}
private final class LongClickHandler implements View.OnLongClickListener
{
private final class LongClickHandler implements View.OnLongClickListener {
@Override
public boolean onLongClick(View v){
public boolean onLongClick(View v) {
goPrev();
return false;
}
}
private final class PageButtonHandler implements View.OnClickListener
{
private final class PageButtonHandler implements View.OnClickListener {
@Override
public void onClick(View v){
public void onClick(View v) {
if (_activity == null) {
goNext();
}else {
} else {
goNextFinish();
}
}

View file

@ -3,24 +3,25 @@ package uk.kagurach.android101
import android.content.Context
import android.widget.Toast
class ToastHelper(text: String,ctx: Context) {
class ToastHelper(text: String, ctx: Context) {
val _text = text
val _ctx = ctx
val _ctx = ctx
companion object SmartToast {
fun ShowToast(text: String,ctx: Context){
val helper = ToastHelper(text,ctx)
fun ShowToast(text: String, ctx: Context) {
val helper = ToastHelper(text, ctx)
helper.autoShow()
}
}
fun autoShow(){
if (_text.contains('\n')){
for (line in _text.split('\n')){
Toast.makeText(_ctx,line,Toast.LENGTH_SHORT).show()
Thread.sleep(Toast.LENGTH_SHORT.toLong()+5)
fun autoShow() {
if (_text.contains('\n')) {
for (line in _text.split('\n')) {
Toast.makeText(_ctx, line, Toast.LENGTH_SHORT).show()
Thread.sleep(Toast.LENGTH_SHORT.toLong() + 5)
}
}else{
Toast.makeText(_ctx,_text,Toast.LENGTH_LONG).show()
} else {
Toast.makeText(_ctx, _text, Toast.LENGTH_LONG).show()
}
}

View file

@ -45,6 +45,7 @@ import androidx.core.content.ContextCompat
import uk.kagurach.android101.R
import uk.kagurach.android101.todoList.ui.theme.LightBlue100
import java.text.SimpleDateFormat
import java.util.Locale
class AddPage() : ComponentActivity() {
@ -73,12 +74,12 @@ class AddPage() : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddPageLayout(){
fun AddPageLayout() {
val context = LocalContext.current
var title by remember {
mutableStateOf(
when (item){
when (item) {
null -> ""
else -> item!!.title
}
@ -88,8 +89,13 @@ class AddPage() : ComponentActivity() {
val timePickerState by remember {
mutableStateOf(
when (item){
null -> TimePickerState(c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),true)
when (item) {
null -> TimePickerState(
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
)
else -> TimePickerState(
item!!.dueDate.split(" ")[1].split(":")[0].toInt(),
item!!.dueDate.split(" ")[1].split(":")[1].toInt(),
@ -103,7 +109,7 @@ class AddPage() : ComponentActivity() {
initialDisplayedMonthMillis = System.currentTimeMillis(),
yearRange = 2024..2099
)
Scaffold (
Scaffold(
topBar = {
Surface(
modifier = Modifier
@ -148,22 +154,22 @@ class AddPage() : ComponentActivity() {
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
Submit {
if (title.isBlank()||datePickerState.selectedDateMillis==null){
Toast.makeText(context,"Please Fill Every field",Toast.LENGTH_SHORT)
if (title.isBlank() || datePickerState.selectedDateMillis == null) {
Toast.makeText(context, "Please Fill Every field", Toast.LENGTH_SHORT)
.show()
return@Submit
}
val loader = TodoItemLoader(context)
val sdf = SimpleDateFormat("yyyy-MM-dd")
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
val todoItem = TodoItem(
loader.getLastId()+1,
title.replace("\t"," "),
sdf.format(datePickerState.selectedDateMillis) + " " +
loader.getLastId() + 1,
title.replace("\t", " "),
sdf.format(datePickerState.selectedDateMillis) + " " +
timePickerState.hour.toString() + ":" +
timePickerState.minute.toString()
)
)
loader.changeItem(todoItem)
val myIntent = Intent(context, MainActivity::class.java)
ContextCompat.startActivity(context, myIntent, null)

View file

@ -35,51 +35,51 @@ class MainActivity : ComponentActivity() {
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LayOut(tmpList : List<TodoItem>?) {
val context = LocalContext.current
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LayOut(tmpList: List<TodoItem>?) {
val context = LocalContext.current
Scaffold (
topBar = {
TopAppBar(
title = { Text("Simple TODO ^_^") }
)
},
content = {
padding ->
Surface(
modifier = Modifier.padding(padding)
.verticalScroll(rememberScrollState())
) {
if (tmpList != null) {
Column {
for (i in tmpList) {
TodoItemView(todoItem = i)
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("Simple TODO ^_^") }
)
},
content = { padding ->
Surface(
modifier = Modifier
.padding(padding)
.verticalScroll(rememberScrollState())
) {
if (tmpList != null) {
Column {
for (i in tmpList) {
TodoItemView(todoItem = i)
}
}
},
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
NextPage {
val myIntent = Intent(context, AddPage::class.java)
ContextCompat.startActivity(context, myIntent, null)
}
},
)
}
},
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
NextPage {
val myIntent = Intent(context, AddPage::class.java)
ContextCompat.startActivity(context, myIntent, null)
}
},
)
}
@Composable
fun NextPage(onClick: () -> Unit) {
FloatingActionButton(
onClick = { onClick() },
containerColor = LightBlue100
) {
Icon(Icons.Filled.Add, "Floating action button.")
}
@Composable
fun NextPage(onClick: () -> Unit) {
FloatingActionButton(
onClick = { onClick() },
containerColor = LightBlue100
) {
Icon(Icons.Filled.Add, "Floating action button.")
}
}
}

View file

@ -11,7 +11,7 @@ data class TodoItem(
var title: String,
var dueDate: String,
var isCompleted:Boolean = false,
var isCompleted: Boolean = false,
var MarkDeleted:Boolean = false
var MarkDeleted: Boolean = false
)

View file

@ -6,38 +6,38 @@ import java.io.File
import java.io.FileWriter
class TodoItemLoader(private val context: Context) {
private val db = File(context.filesDir,"db")
private val db = File(context.filesDir, "db")
public fun getTodoItems(): List<TodoItem>?{
if (!db.exists()){
public fun getTodoItems(): List<TodoItem>? {
if (!db.exists()) {
return null
}
val lines = db.readLines()
if (lines.isEmpty()){
if (lines.isEmpty()) {
return null
}
var list: List<TodoItem> = listOf()
for (line in lines){
for (line in lines) {
val split = line.split("\t")
val item: TodoItem
try {
item = TodoItem(split[0].toInt(),split[1],split[2], split[3].toBooleanStrict())
item = TodoItem(split[0].toInt(), split[1], split[2], split[3].toBooleanStrict())
list = list + item
} catch (e: Exception){
} catch (e: Exception) {
Log.e("DB Error", e.printStackTrace().toString())
}
}
if (list.isNotEmpty()){
if (list.isNotEmpty()) {
return list
}
return null
}
public fun saveTodoItems(list:List<TodoItem>){
public fun saveTodoItems(list: List<TodoItem>) {
var result = ""
for (i in list){
if(!i.MarkDeleted) {
for (i in list) {
if (!i.MarkDeleted) {
result += "%s\t%s\t%s\t%s\n".format(
i.id.toString(),
i.title,
@ -51,14 +51,14 @@ class TodoItemLoader(private val context: Context) {
fileWriter.close()
}
public fun getLastId():Int{
public fun getLastId(): Int {
val items = getTodoItems();
return if (items==null){
return if (items == null) {
0
}else{
} else {
var max = 0
for (i in items){
if (i.id>max){
for (i in items) {
if (i.id > max) {
max = i.id
}
}
@ -66,12 +66,12 @@ class TodoItemLoader(private val context: Context) {
}
}
public fun changeItem(todoItem: TodoItem){
public fun changeItem(todoItem: TodoItem) {
var items = getTodoItems()
var changeFlag = false
if (items != null) {
for (i in items){
if (i.id==todoItem.id){
for (i in items) {
if (i.id == todoItem.id) {
i.title = todoItem.title
i.dueDate = todoItem.dueDate
i.MarkDeleted = todoItem.MarkDeleted
@ -80,22 +80,22 @@ class TodoItemLoader(private val context: Context) {
break
}
}
if (!changeFlag){
if (!changeFlag) {
items = items + todoItem
}
}else{
} else {
items = listOf(todoItem)
}
saveTodoItems(items)
}
public fun searchItem(id:Int): TodoItem?{
public fun searchItem(id: Int): TodoItem? {
val items = getTodoItems();
return if (items==null){
return if (items == null) {
null
}else{
for (i in items){
if (i.id>id){
} else {
for (i in items) {
if (i.id > id) {
return i
}
}

View file

@ -42,7 +42,7 @@ fun TodoItemView(todoItem: TodoItem) {
}
var bgColor by remember {
mutableStateOf(
when (todoItem.isCompleted){
when (todoItem.isCompleted) {
true -> Green100
false -> Blue100
}
@ -51,7 +51,7 @@ fun TodoItemView(todoItem: TodoItem) {
var needShow by remember {
mutableStateOf(true)
}
if (!needShow){
if (!needShow) {
return
}
@ -68,14 +68,14 @@ fun TodoItemView(todoItem: TodoItem) {
start = 10.dp,
end = 10.dp
)
){
) {
Text(
text = todoItem.title,
color = Color.Black,
fontSize = 30.sp,
fontFamily = FontFamily.Monospace
)
Row{
Row {
Spacer(modifier = Modifier.weight(1f))
Text(
text = todoItem.dueDate,
@ -87,11 +87,12 @@ fun TodoItemView(todoItem: TodoItem) {
Row {
TextButton(
onClick = {
if (!todoItem.isCompleted){
Toast.makeText( context,
context.getText(R.string.yes_not_finish)
,Toast.LENGTH_SHORT).show()
}else{
if (!todoItem.isCompleted) {
Toast.makeText(
context,
context.getText(R.string.yes_not_finish), Toast.LENGTH_SHORT
).show()
} else {
todoItem.isCompleted = false
loader.changeItem(todoItem)
bgColor = Blue100
@ -105,11 +106,12 @@ fun TodoItemView(todoItem: TodoItem) {
Spacer(modifier = Modifier.width(20.dp))
TextButton(
onClick = {
if (todoItem.isCompleted){
Toast.makeText( context,
context.getText(R.string.already_finish)
,Toast.LENGTH_SHORT).show()
}else{
if (todoItem.isCompleted) {
Toast.makeText(
context,
context.getText(R.string.already_finish), Toast.LENGTH_SHORT
).show()
} else {
todoItem.isCompleted = true
loader.changeItem(todoItem)
bgColor = Green100
@ -123,9 +125,10 @@ fun TodoItemView(todoItem: TodoItem) {
Spacer(modifier = Modifier.width(20.dp))
TextButton(
onClick = {
when (deleteText){
when (deleteText) {
context.getText(R.string.first_delete).toString() ->
deleteText=context.getText(R.string.second_delete).toString()
deleteText = context.getText(R.string.second_delete).toString()
else -> {
needShow = false
todoItem.MarkDeleted = true
@ -147,12 +150,12 @@ fun TodoItemView(todoItem: TodoItem) {
@Preview(showBackground = true)
@Composable
fun TodoItemPreview(){
fun TodoItemPreview() {
val todoItem = TodoItem(
0,"Test TODO Item","2024-04-30 11:45",
0, "Test TODO Item", "2024-04-30 11:45",
)
val todoItem2 = TodoItem(
1,"测试喵","2024-11-01 22:33",true
1, "测试喵", "2024-11-01 22:33", true
)
Column {
TodoItemView(todoItem)
@ -160,8 +163,8 @@ fun TodoItemPreview(){
}
}
fun NextPage(context:Context,item: TodoItem) {
fun NextPage(context: Context, item: TodoItem) {
val myIntent = Intent(context, AddPage::class.java)
myIntent.putExtra("ITEM",item.id)
myIntent.putExtra("ITEM", item.id)
ContextCompat.startActivity(context, myIntent, null)
}

View file

@ -0,0 +1,30 @@
package uk.kagurach.android101.vibrationBroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.CombinedVibration;
import android.os.VibrationEffect;
import android.os.VibratorManager;
import android.util.Log;
import java.util.Objects;
public class vibrationBroadcastReceiver extends BroadcastReceiver {
public static final String VIBRATION_ACTION_NAME = "uk.kagurach.android101.vibrationBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), VIBRATION_ACTION_NAME)) {
VibratorManager vibrator = (VibratorManager) context.getSystemService(
Context.VIBRATOR_MANAGER_SERVICE
);
vibrator.vibrate(
CombinedVibration.createParallel(
VibrationEffect.createOneShot(1500,VibrationEffect.DEFAULT_AMPLITUDE)
));
Log.d("Debug","Vibrate!");
}
}
}

View file

@ -4,58 +4,60 @@ import java.time.Instant
import java.util.Date
import kotlin.random.Random
fun AIAnswerService(s: String):String {
fun AIAnswerService(s: String): String {
val rng = Random(Date.from(Instant.now()).time)
var result = s
result = result.replace("","?")
result = result.replace("", "?")
val isMoral = s.contains("")
val needAI = s.contains("")
val needAI = s.contains("")
result = result.replace("","^")
result = result.replace("","")
result = result.replace("","@")
result = result.replace("", "^")
result = result.replace("", "")
result = result.replace("", "@")
if (isMoral){
if (isMoral) {
result = if (rng.nextBoolean()) {
"谢谢@的提问,$result"
} else{
if (result.endsWith(".")||
result.endsWith("")||
result.endsWith("?")){
} else {
if (result.endsWith(".") ||
result.endsWith("") ||
result.endsWith("?")
) {
result = result.dropLast(1);
}
"$result,谢谢。"
}
result = result.replace("","")
result = result.replace("", "")
}
if (needAI){
result = result.replace("","")
if (needAI) {
result = result.replace("", "")
}
result = result.replace("",
if (rng.nextBoolean()){
result = result.replace(
"",
if (rng.nextBoolean()) {
"可以"
}else{
} else {
"不可以"
}
)
result = result.replace("什么","很多")
result = result.replace("","")
result = result.replace("?","")
result = result.replace("^","")
result = result.replace("@","")
result = result.replace("什么", "很多")
result = result.replace("", "")
result = result.replace("?", "")
result = result.replace("^", "")
result = result.replace("@", "")
return result
}
fun main(){
fun main() {
println(AIAnswerService("我想吃饭"))
println(AIAnswerService("咱可以吃饭吗"))
println(AIAnswerService("您可以做什么?"))

View file

@ -31,7 +31,6 @@
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/next_page"
android:onClick="jumpToNext"
android:enabled="false"
/>

View file

@ -20,15 +20,18 @@
android:layout_height="wrap_content"
android:textSize="40sp"
android:text="@string/user"/>
<EditText
android:layout_width="match_parent"
android:layout_height="200dp"
android:textSize="40sp"
android:layout_height="wrap_content"
android:textSize="35sp"
android:id="@+id/P4Ask"
android:importantForAutofill="no"
android:text="你吃了吗?"
android:text="@string/AI_ASK_DEFAULT_STRING"
android:textColor="@color/tfp"
android:hint="@string/AI_ASK_DEFAULT_STRING"
android:inputType="text" />
<View
android:layout_width="match_parent"
android:layout_height="50dp" />
@ -38,14 +41,23 @@
android:textSize="40sp"
android:text="@string/ai"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="300dp">
<TextView
android:layout_width="match_parent"
android:textSize="35sp"
android:layout_height="wrap_content"
android:id="@+id/P4Result"
android:textColor="@color/tfb"
/>
</ScrollView>
<TextView
android:layout_width="match_parent"
android:textSize="40sp"
android:layout_height="200dp"
android:id="@+id/P4Result"
android:textColor="@color/tfb"
/>
android:layout_height="wrap_content"
android:textSize="25sp"
android:id="@+id/P4AIRuntime"
android:text="@string/ai_ready"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
@ -57,6 +69,14 @@
android:id="@+id/P4AskAI"
android:text="@string/ask_ai"
/>
<Button
android:layout_width="140dp"
android:layout_height="match_parent"
android:id="@+id/P4Vibrate"
android:text="@string/vibrate"
/>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"

View file

@ -14,4 +14,7 @@
<string name="user">用户</string>
<string name="ai">AI</string>
<string name="ask_ai">询问AI</string>
<string name="ai_ready">AI 准备好了</string>
<string name="AI_ASK_DEFAULT_STRING">你吃了吗?</string>
<string name="vibrate">振动手机</string>
</resources>

View file

@ -24,4 +24,7 @@
<string name="user">User</string>
<string name="ai">AI</string>
<string name="ask_ai">ASK AI</string>
<string name="ai_ready">AI Ready</string>
<string name="AI_ASK_DEFAULT_STRING">你吃了吗?</string>
<string name="vibrate">Vibrate</string>
</resources>

View file

@ -1,24 +1,24 @@
[versions]
agp = "8.3.2"
kotlin = "1.9.0"
coreKtx = "1.13.0"
coreKtx = "1.13.1"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
appcompat = "1.6.1"
material = "1.11.0"
material = "1.12.0"
activity = "1.9.0"
constraintlayout = "2.1.4"
lifecycleRuntimeKtx = "2.7.0"
lifecycleRuntimeKtx = "2.8.0"
activityCompose = "1.9.0"
composeBom = "2024.04.01"
composeBom = "2024.05.00"
roomCommon = "2.6.1"
roomKtx = "2.6.1"
navigationFragmentKtx = "2.7.7"
navigationUiKtx = "2.7.7"
annotation = "1.7.1"
lifecycleLivedataKtx = "2.7.0"
lifecycleViewmodelKtx = "2.7.0"
annotation = "1.8.0"
lifecycleLivedataKtx = "2.8.0"
lifecycleViewmodelKtx = "2.8.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }