feat(android): warm voice interface and custom sampling up to one day v0.1.51

This commit is contained in:
Codex
2026-10-19 01:19:28 +08:00
parent e3afb2e07f
commit 0a7c4d9b96
28 changed files with 401 additions and 107 deletions
@@ -15,8 +15,10 @@ import java.util.*;
public class LocationActivity extends Activity {
static volatile boolean pairing=false;
TextView identity,status,viewStatus,permissionStatus;EditText code;Button pair,reload;
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit;EditText customAmount;LinearLayout customPeriod,settings,recipients,familyList,homeContent,shareControls;
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit,sampleUnit;EditText customAmount,sampleAmount;LinearLayout customPeriod,samplePeriod,settings,recipients,familyList,homeContent,shareControls;
TextView queueStatus;LocationQueue outbox;String queueOwner="";
final int[] sampleIntervals={10,60,300,900,1800,3600,7200,10800,14400,18000,21600,43200,86400,0};
final int[] sampleUnits={1,60,3600,86400};
final int[] uploadIntervals={10,60,300,3600,7200,10800,14400,18000,86400,172800,259200,0};
TextView historyStatus,historyNotice;Dialog historyDialog;LocationMapView historyMap;Button historyMore;JSONArray historyPoints=new JSONArray();int historyRequest=0;boolean historyAcknowledged=false;
VoicePanel voice;Button settingsButton;
@@ -52,7 +54,10 @@ public class LocationActivity extends Activity {
shareControls=new LinearLayout(this);shareControls.setOrientation(1);settings.addView(shareControls);
text("我的位置共享",22,shareControls);text("选择谁能看我的位置",16,shareControls);
recipients=new LinearLayout(this);recipients.setOrientation(1);shareControls.addView(recipients);
text("定位采集频率",16,shareControls);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟(省电)"}));sampleCadence.setSelection(1);shareControls.addView(sampleCadence);
text("定位采集频率",16,shareControls);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟","每 15 分钟","每 30 分钟","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 6 小时","每 12 小时","每 1 天","自定义采集间隔"}));sampleCadence.setSelection(1);shareControls.addView(sampleCadence);
samplePeriod=new LinearLayout(this);samplePeriod.setOrientation(LinearLayout.HORIZONTAL);sampleAmount=new EditText(this);sampleAmount.setInputType(InputType.TYPE_CLASS_NUMBER);sampleAmount.setHint("正整数");sampleAmount.setText("2");sampleAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(5)});samplePeriod.addView(sampleAmount,new LinearLayout.LayoutParams(0,-2,1));sampleUnit=new Spinner(this);sampleUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"秒","分钟","小时","天"}));sampleUnit.setSelection(2);samplePeriod.addView(sampleUnit);shareControls.addView(samplePeriod);samplePeriod.setVisibility(View.GONE);
sampleCadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){samplePeriod.setVisibility(position==sampleIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
text("每次采集留下一个定位点。可自定义 10 秒至 24 小时,最长每天一次,不设一周。采集越稀疏越省电,但无法还原期间的完整路线。",14,shareControls);
text("集中上传周期",16,shareControls);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);shareControls.addView(cadence);
customPeriod=new LinearLayout(this);customPeriod.setOrientation(0);customAmount=new EditText(this);customAmount.setInputType(InputType.TYPE_CLASS_NUMBER);customAmount.setHint("正整数");customAmount.setText("6");customAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(3)});customPeriod.addView(customAmount,new LinearLayout.LayoutParams(0,-2,1));customUnit=new Spinner(this);customUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"小时","天"}));customPeriod.addView(customUnit);shareControls.addView(customPeriod);customPeriod.setVisibility(View.GONE);
cadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){customPeriod.setVisibility(position==uploadIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
@@ -94,7 +99,7 @@ public class LocationActivity extends Activity {
rendering=true;sharing.setChecked(active);rendering=false;
sharing.setEnabled(paired&&!pairing&&(active||!busy&&settingsReady));
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
sampleCadence.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
sampleCadence.setEnabled(!active&&!busy);sampleAmount.setEnabled(!active&&!busy);sampleUnit.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
for(List<CheckBox> list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy);
reload.setEnabled(paired&&!loading&&!pairing);
}
@@ -119,7 +124,7 @@ public class LocationActivity extends Activity {
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?"按设定周期上传中,当前没有实时坐标":("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位")) : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?("sampling".equals(row.optString("scheduleReason"))?"等待下次采集,当前没有实时坐标":"等待下次上传,当前没有实时坐标"):("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位")) : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
});
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){boolean wasSharing=prefs.getBoolean("active",false);prefs.edit().putBoolean("active",false).apply();if(wasSharing||LocationService.busy)startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
}
@@ -129,7 +134,7 @@ public class LocationActivity extends Activity {
JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","settings"));
runOnUiThread(()->{if(!visible||g!=generation||request!=settingsRequest)return;settingsReceipt=result.optString("receipt");recipients.removeAllViews();choices.clear();
for(String type:new String[]{"viewers","phones","displays"}){String key=type.equals("viewers")?"viewerIds":type.equals("phones")?"phoneIds":"displayIds";text(type.equals("viewers")?"平台查看账号":type.equals("phones")?"已配对的家人手机":"公共显示终端",16,recipients);JSONArray options=result.optJSONArray(type),selected=result.optJSONArray(key);Set<String> ids=new HashSet<>();if(selected!=null)for(int i=0;i<selected.length();i++)ids.add(selected.optString(i));List<CheckBox> list=new ArrayList<>();choices.put(key,list);if(options!=null)for(int i=0;i<options.length();i++){JSONObject item=options.optJSONObject(i);CheckBox c=new CheckBox(this);c.setText(item.optString("name"));c.setTag(item.optString("id"));c.setChecked(ids.contains(item.optString("id")));recipients.addView(c);list.add(c);}if(list.isEmpty())text("暂无可选对象",14,recipients);}
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);int sample=result.optInt("sampleIntervalSeconds",60);sampleCadence.setSelection(sample==10?0:sample==300?2:1);historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);setSamplePeriod(result.optInt("sampleIntervalSeconds",60));historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
}
void start(){
@@ -138,12 +143,14 @@ public class LocationActivity extends Activity {
if(historyConsent.isChecked()&&!historyAcknowledged){new AlertDialog.Builder(this).setTitle("同意长期保存我的轨迹").setMessage("定位点将加密上传家庭百度网盘,按天、周、月、年或全部历史查看,长期保留直到你手动删除。共享时所选查看人能读取其获授权期间的历史。关闭实时共享不会删除历史。是否同意?").setNegativeButton("暂不启用",null).setPositiveButton("本人同意并开启",(d,w)->{historyAcknowledged=true;start();}).show();return;}
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
if(!LocationService.locationEnabled((android.location.LocationManager)getSystemService(LOCATION_SERVICE))){Toast.makeText(this,"请先打开手机系统定位开关",1).show();return;}
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",new int[]{10,60,300}[sampleCadence.getSelectedItemPosition()]).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"请填写 1—720 小时或 1—30 天的整数周期",1).show();return;}
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",samplePeriodSeconds()).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"采集间隔需为 10 秒至 1 天;上传周期为 1—720 小时或 1—30 天,均填正整数",1).show();return;}
final int g=generation;final String token=prefs.getString("token","");pairing=true;settingsReady=false;settingsError="";render();
new Thread(()->{try{JSONObject result=DisplayApi.call("/api/location/update",token,body);remember(result);runOnUiThread(()->{if(!visible||g!=generation)return;settingsReceipt=result.optString("receipt");settingsReady=true;LocationService.busy=true;try{startForegroundService(new Intent(this,LocationService.class).setAction("START"));}catch(Exception e){LocationService.busy=false;Toast.makeText(this,"未能启动定位,请保持页面在前台再试",1).show();}render();});}
catch(Exception e){runOnUiThread(()->{if(visible&&g==generation)Toast.makeText(this,"开启未成功,请重新读取设置并核对名单",1).show();});}
finally{pairing=false;runOnUiThread(()->{if(!isDestroyed()){if(visible&&!settingsReady)loadSettings();render();}});}},"location-configure").start();
}
int samplePeriodSeconds(){int index=sampleCadence.getSelectedItemPosition();return sampleIntervals[index]>0?sampleIntervals[index]:LocationCadence.customSample(Integer.parseInt(sampleAmount.getText().toString().trim()),sampleUnits[sampleUnit.getSelectedItemPosition()]);}
void setSamplePeriod(int seconds){seconds=LocationCadence.sample(seconds);for(int i=0;i<sampleIntervals.length-1;i++)if(sampleIntervals[i]==seconds){sampleCadence.setSelection(i);return;}sampleCadence.setSelection(sampleIntervals.length-1);int unit=seconds%86400==0?3:seconds%3600==0?2:seconds%60==0?1:0;sampleUnit.setSelection(unit);sampleAmount.setText(Integer.toString(seconds/sampleUnits[unit]));}
int uploadPeriod(){int index=cadence.getSelectedItemPosition();return uploadIntervals[index]>0?uploadIntervals[index]:LocationCadence.custom(Integer.parseInt(customAmount.getText().toString().trim()),customUnit.getSelectedItemPosition()==1);}
void setUploadPeriod(int seconds){for(int i=0;i<uploadIntervals.length-1;i++)if(uploadIntervals[i]==seconds){cadence.setSelection(i);return;}cadence.setSelection(uploadIntervals.length-1);boolean days=seconds%86400==0;customUnit.setSelection(days?1:0);customAmount.setText(Integer.toString(seconds/(days?86400:3600)));}
void refreshQueueStats(){try{queueOwner=LocationQueue.digest(prefs.getString("token",""));long[] values=outbox.stats(queueOwner);prefs.edit().putLong("pendingPoints",values[0]).putLong("pendingBytes",values[1]).putLong("uploadedPoints",values[2]).putLong("freedBytes",values[3]).apply();}catch(Exception e){prefs.edit().putString("syncStatus","本机轨迹暂不能读取,数据没有删除").apply();}}
@@ -5,7 +5,10 @@ final class LocationCadence {
static final int MAX_SECONDS=30*86400;
static boolean valid(int value){return value==10||value==60||value==300||value>=3600&&value<=MAX_SECONDS&&value%3600==0;}
static int seconds(int value){return valid(value)?value:300;}
static int sample(int value){return value==10||value==60||value==300?value:60;}
static boolean sampleValid(int value){return value>=10&&value<=86400;}
static int sample(int value){return sampleValid(value)?value:60;}
static int customSample(int value,int unit){long seconds=value*(long)unit;if(value<1||(unit!=1&&unit!=60&&unit!=3600&&unit!=86400)||seconds<10||seconds>86400)throw new IllegalArgumentException("采集间隔需在 10 秒至 1 天内");return (int)seconds;}
static boolean sampleDue(long now,long previous,int seconds){return previous==0||now-previous>=sample(seconds)*1000L;}
static int custom(int value,boolean days){long seconds=value*(days?86400L:3600L);if(value<1||seconds>MAX_SECONDS)throw new IllegalArgumentException("周期需在 1 小时至 30 天内");return (int)seconds;}
static boolean due(long now,long lastAttempt,int interval,boolean firstFix){
return lastAttempt==0||now-lastAttempt>=1000L*(firstFix?10:seconds(interval));
@@ -121,13 +121,14 @@ public class LocationService extends Service implements LocationListener {
prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0;
}
public void onLocationChanged(Location value){
if(!active||stopping)return;latest=new Location(value);if(!historyEnabled)return;
Location fix=new Location(value);String session=collection;long epoch=prefs.getLong("queueEpoch",0),started=collectionStarted;
if(!active||stopping)return;
Location fix=new Location(value);long elapsed=fix.getElapsedRealtimeNanos()/1000000;
if(!LocationCadence.sampleDue(elapsed,lastSample,sampleSeconds)||fix.getTime()<collectionStarted-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
lastSample=elapsed;latest=fix;if(!historyEnabled)return;
String session=collection;long epoch=prefs.getLong("queueEpoch",0);
recorder.execute(()->{try{
if(epoch!=prefs.getLong("queueEpoch",0))return;
long elapsed=fix.getElapsedRealtimeNanos()/1000000;
if(lastSample!=0&&elapsed-lastSample<sampleSeconds*1000L||fix.getTime()<started-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
if(queue.append(owner,session,position(fix))){lastSample=elapsed;cacheFull=false;}
if(queue.append(owner,session,position(fix))){cacheFull=false;}
else{cacheFull=true;prefs.edit().putString("syncStatus","本地缓存已达上限,暂停新增历史;未上传记录没有覆盖,请联网补传").apply();notification("轨迹缓存已满 · 请联网补传");}
updateQueueStatus();
}catch(Exception error){cacheFull=true;prefs.edit().putString("syncStatus","本地轨迹未能写入,请检查手机存储空间;已有记录保留").apply();}});
@@ -0,0 +1,7 @@
package cn.ucvl.zhaodisplay;
/** Same cancel rule for touch and the recording deadline; no audio or network dependency. */
final class VoiceGesture {
static boolean cancel(float deltaY,float x,float width,float threshold){return deltaY<=-threshold||x<0||x>width;}
static boolean sendAtLimit(boolean cancelled){return !cancelled;}
}
@@ -19,63 +19,87 @@ import java.util.function.Supplier;
final class VoicePanel extends LinearLayout {
final Activity app;final String kind;final Supplier<String> token;
final Handler ui=new Handler();final ExecutorService worker=Executors.newSingleThreadExecutor();
final TextView status;final Spinner targets;final Button speak,settings,stop;
final TextView status;final Button speak,settings,stop;final VoiceSurface dock;VoiceSurface expanded;Dialog sheet;
String selectedId="";boolean networkReady=false;long feedbackAt=0;
final AudioManager audio;final AudioAttributes attributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
AudioFocusRequest focus;MediaRecorder recorder;MediaPlayer player;File recording,playing;
JSONArray choices=new JSONArray(),allowed=new JSONArray(),destinations=new JSONArray();
boolean enabled=false,cancelled=false,sending=false,night=false,polling=false;volatile boolean visible=false,closed=false;volatile int epoch=0;
long started;String recordTarget="",recordToken="",playingId="",playingToken="",lastMessage="";
final Runnable refresh=new Runnable(){public void run(){if(!visible||closed)return;poll();ui.postDelayed(this,5000);}};
final Runnable limit=()->finish(true);
final Runnable limit=()->finish(VoiceGesture.sendAtLimit(cancelled));
final Runnable visual=new Runnable(){public void run(){if(!visible||closed)return;renderSurfaces();ui.postDelayed(this,recorder!=null?100:500);}};
VoicePanel(Activity activity,String type,Supplier<String> credentials){
super(activity);app=activity;kind=type;token=credentials;audio=(AudioManager)app.getSystemService(Context.AUDIO_SERVICE);
setOrientation(VERTICAL);int p=(int)(8*getResources().getDisplayMetrics().density);setPadding(p,p,p,p);setBackgroundColor(0xffe5ebe5);
status=new TextView(app);status.setTextSize(14);status.setTextColor(0xff254b3f);status.setText("家人喊话 · 先配对,再选择接收人");addView(status);
LinearLayout row=new LinearLayout(app);row.setGravity(Gravity.CENTER_VERTICAL);addView(row);
targets=new Spinner(app);row.addView(targets,new LayoutParams(0,-2,1));
speak=new Button(app);speak.setText("🎙 按住说话");speak.setEnabled(false);row.addView(speak);
speak.setOnTouchListener((v,event)->{
setOrientation(VERTICAL);dock=new VoiceSurface(app,false);addView(dock,new LayoutParams(-1,-2));
status=dock.status;speak=dock.speak;settings=dock.settings;stop=dock.stop;wire(dock);speak.setEnabled(false);stop.setEnabled(false);
for(File file:Optional.ofNullable(app.getCacheDir().listFiles()).orElse(new File[0]))if(file.getName().startsWith("voice-"))file.delete();
}
void showStatus(String text){VoiceSurface.text(status,text);feedbackAt=SystemClock.elapsedRealtime();if(expanded!=null)VoiceSurface.text(expanded.status,text);}
void wire(VoiceSurface view){
view.settings.setOnClickListener(v->configure());view.stop.setOnClickListener(v->stopPlayer("rejected"));
view.expand.setOnClickListener(v->{if(view.full&&sheet!=null)sheet.dismiss();else openSheet();});view.recipient.setOnClickListener(v->{if(!view.full)openSheet();});
final float[] down={0};view.speak.setOnTouchListener((v,event)->{
switch(event.getActionMasked()){
case MotionEvent.ACTION_DOWN:begin();return true;
case MotionEvent.ACTION_MOVE:cancelled=event.getX()<0||event.getY()<0||event.getX()>v.getWidth()||event.getY()>v.getHeight();if(recorder!=null)speak.setText(cancelled?"松开取消":"松开发送");return true;
case MotionEvent.ACTION_UP:finish(!cancelled);v.performClick();return true;
case MotionEvent.ACTION_DOWN:down[0]=event.getRawY();v.getParent().requestDisallowInterceptTouchEvent(true);begin();return true;
case MotionEvent.ACTION_MOVE:cancelled=VoiceGesture.cancel(event.getRawY()-down[0],event.getX(),v.getWidth(),view.dp(48));renderSurfaces();return true;
case MotionEvent.ACTION_UP:v.getParent().requestDisallowInterceptTouchEvent(false);finish(!cancelled);return true;
case MotionEvent.ACTION_POINTER_DOWN:finish(false);return true;
case MotionEvent.ACTION_CANCEL:finish(false);return true;
}return false;
});
speak.setOnKeyListener((v,key,event)->{if(key!=KeyEvent.KEYCODE_DPAD_CENTER&&key!=KeyEvent.KEYCODE_ENTER)return false;if(event.getAction()==KeyEvent.ACTION_DOWN){if(event.getRepeatCount()==0)begin();}else finish(true);return true;});
LinearLayout tools=new LinearLayout(app);addView(tools);
settings=new Button(app);settings.setText("接收设置");settings.setOnClickListener(v->configure());tools.addView(settings,new LayoutParams(0,-2,1));
stop=new Button(app);stop.setText("停止播放");stop.setEnabled(false);stop.setOnClickListener(v->stopPlayer("rejected"));tools.addView(stop,new LayoutParams(0,-2,1));
for(File file:Optional.ofNullable(app.getCacheDir().listFiles()).orElse(new File[0]))if(file.getName().startsWith("voice-"))file.delete();
view.speak.setOnKeyListener((v,key,event)->{if(key!=KeyEvent.KEYCODE_DPAD_CENTER&&key!=KeyEvent.KEYCODE_ENTER)return false;if(event.getAction()==KeyEvent.ACTION_DOWN){if(event.getRepeatCount()==0)begin();}else finish(true);return true;});
view.speak.setOnClickListener(v->{android.view.accessibility.AccessibilityManager a=(android.view.accessibility.AccessibilityManager)app.getSystemService(Context.ACCESSIBILITY_SERVICE);if(a!=null&&a.isTouchExplorationEnabled()){if(recorder==null)begin();else finish(true);}});
}
void openSheet(){
if(closed||sheet!=null&&sheet.isShowing())return;
expanded=new VoiceSurface(app,true);wire(expanded);expanded.applyTheme(night);
ScrollView scroll=new ScrollView(app);scroll.setFillViewport(true);scroll.addView(expanded);
sheet=new Dialog(app,android.R.style.Theme_Material_Light_NoActionBar);sheet.setContentView(scroll);
sheet.setOnDismissListener(d->{finish(false);expanded=null;sheet=null;});sheet.show();
sheet.getWindow().setLayout(-1,-1);sheet.getWindow().setStatusBarColor(night?0xff172820:0xfff8f5ed);sheet.getWindow().setNavigationBarColor(night?0xff172820:0xfff8f5ed);
sheet.getWindow().getDecorView().setSystemUiVisibility(night?0:View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
renderSurfaces();
}
JSONObject destination(){if(destinations!=null)for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d!=null&&d.optString("id").equals(selectedId))return d;}return null;}
void choose(String id){if(recorder!=null||sending)return;selectedId=id;lastMessage="";JSONObject d=destination();showStatus(d!=null&&d.optBoolean("online")?"按住说话,松开发送给 "+d.optString("name"):"请先让对方打开 App,再向其喊话");renderSurfaces();}
void renderSurfaces(){
JSONObject selected=destination();String name=selected==null?"":selected.optString("name");boolean available=selected!=null&&selected.optBoolean("online");
boolean can=networkReady&&available&&!sending&&microphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){}
for(VoiceSurface view:new VoiceSurface[]{dock,expanded}){if(view==null)continue;
view.targets(destinations,selectedId,this::choose);if(recorder==null||view.full)VoiceSurface.text(view.recipient,name.isEmpty()?"选择一位家人":view.full?"对"+name+"说句话":name+" · "+(available?"已打开 App":"未打开 App")+" ›");
VoiceSurface.text(view.receive,enabled?"● 接收已开启 · 仅限你允许的家人":"○ 接收已关闭 · 可在接收设置中开启");
view.settings.setEnabled(networkReady&&recorder==null&&!sending);view.stop.setVisibility(player!=null?View.VISIBLE:View.GONE);view.stop.setEnabled(player!=null);
view.recording(recorder!=null,cancelled,recorder==null?0:SystemClock.elapsedRealtime()-started,amplitude,sending,can);
if(view!=dock)VoiceSurface.text(view.status,status.getText());
if(!microphone()&&recorder==null&&!sending)view.speak.setText("待接入话筒");
}
}
JSONObject body(String action)throws Exception{return new JSONObject().put("kind",kind).put("action",action);}
boolean current(int e,String t){return visible&&!closed&&e==epoch&&t.equals(token.get());}
void active(boolean value){
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);
if(value){ui.post(refresh);}else{finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);ui.removeCallbacks(visual);
if(value){ui.post(refresh);ui.post(visual);}else{if(sheet!=null)sheet.dismiss();finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
}
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;lastMessage="";active(true);}
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;networkReady=false;selectedId="";lastMessage="";active(true);}
void close(){active(false);closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();}
void poll(){
if(polling||closed||!visible)return;
String t=token.get();if(t.isEmpty()){speak.setEnabled(false);settings.setEnabled(false);return;}final int e=epoch;polling=true;
worker.execute(()->{try{
JSONObject value=DisplayApi.call("/api/voice",t,body("status"));
ui.post(()->{if(!current(e,t))return;choices=value.optJSONArray("candidates");allowed=value.optJSONArray("allowed");enabled=value.optBoolean("enabled");settings.setEnabled(true);
ui.post(()->{if(!current(e,t))return;choices=value.optJSONArray("candidates");allowed=value.optJSONArray("allowed");enabled=value.optBoolean("enabled");networkReady=true;settings.setEnabled(true);
if(!enabled&&player!=null)stopPlayer("rejected");
if(recorder==null&&!sending){String selected=selectedTarget();destinations=value.optJSONArray("targets");List<String> names=new ArrayList<>();int index=0;
if(destinations!=null)for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);names.add(d.optString("name")+(d.optBoolean("online")?" · 在线":" · 未打开 App"));if(d.optString("id").equals(selected))index=i;}
if(names.isEmpty())names.add("暂无允许接收的对象");targets.setAdapter(new ArrayAdapter<String>(app,android.R.layout.simple_spinner_dropdown_item,names){public View getView(int position,View convert,ViewGroup parent){TextView view=(TextView)super.getView(position,convert,parent);view.setTextColor(night?0xffa6b5ac:0xff254b3f);return view;}});targets.setSelection(index);
speak.setEnabled(destinations!=null&&destinations.length()>0&&microphone());speak.setText(microphone()?"🎙 按住说话":"待接入话筒");
}
JSONArray sent=value.optJSONArray("sent");if(sent!=null&&!lastMessage.isEmpty())for(int i=0;i<sent.length();i++){JSONObject r=sent.optJSONObject(i);if(lastMessage.equals(r.optString("id"))){String s=r.optString("status");status.setText(s.equals("played")?"对方已播放":s.equals("rejected")?"对方已停止或未播放":s.equals("expired")?"喊话已过期,未播放":s.equals("received")?"对方正在接收":"已发送,等待对方播放");}}
if(lastMessage.isEmpty()&&player==null&&recorder==null)status.setText("家人喊话 · "+(enabled?"接收已开启":"接收已关闭")+" · 最长 30 秒");
if(recorder==null&&!sending){destinations=value.optJSONArray("targets");if(destination()==null){selectedId="";if(destinations!=null&&destinations.length()>0){selectedId=destinations.optJSONObject(0).optString("id");for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d.optBoolean("online")){selectedId=d.optString("id");break;}}}}}
JSONArray sent=value.optJSONArray("sent");if(sent!=null&&!lastMessage.isEmpty()&&recorder==null&&player==null&&!sending)for(int i=0;i<sent.length();i++){JSONObject r=sent.optJSONObject(i);if(lastMessage.equals(r.optString("id"))){String s=r.optString("status");showStatus(s.equals("played")?"对方已播放":s.equals("rejected")?"对方已停止或未播放":s.equals("expired")?"喊话已过期,未播放":s.equals("received")?"对方正在接收":"已发送,等待对方播放");}}
if(lastMessage.isEmpty()&&player==null&&recorder==null&&!sending&&SystemClock.elapsedRealtime()-feedbackAt>12000)showStatus(destination()==null?"暂无允许接收的家人,请对方开启接收":!destination().optBoolean("online")?"请对方打开 App 后再说话":"按住说话,松开发送 · 上滑取消");
renderSurfaces();
JSONArray inbox=value.optJSONArray("inbox");if(enabled&&player==null&&recorder==null&&!sending&&inbox!=null&&inbox.length()>0)take(inbox.optJSONObject(0).optString("id"));
});
}catch(Exception error){ui.post(()->{if(current(e,t)){speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();}status.setText("喊话连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
}catch(Exception error){ui.post(()->{if(current(e,t)){networkReady=false;speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();}showStatus("喊话连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
}
String selectedTarget(){JSONObject d=destinations==null?null:destinations.optJSONObject(targets.getSelectedItemPosition());return d==null?"":d.optString("id");}
void night(boolean value){night=value;setBackgroundColor(value?0xff17231e:0xffe5ebe5);status.setTextColor(value?0xffa6b5ac:0xff254b3f);for(Button b:new Button[]{speak,settings,stop}){b.setTextColor(value?0xffa6b5ac:0xff254b3f);b.setBackgroundTintList(android.content.res.ColorStateList.valueOf(value?0xff25362d:0xffd0dfd6));}View selected=targets.getSelectedView();if(selected instanceof TextView)((TextView)selected).setTextColor(value?0xffa6b5ac:0xff254b3f);}
String selectedTarget(){return destination()==null?"":selectedId;}
void night(boolean value){night=value;dock.applyTheme(value);if(expanded!=null)expanded.applyTheme(value);renderSurfaces();}
boolean microphone(){try{return audio.getDevices(AudioManager.GET_DEVICES_INPUTS).length>0;}catch(Exception e){return false;}}
void configure(){
if(choices==null)return;final JSONArray options=choices;String[] names=new String[options.length()];boolean[] checked=new boolean[names.length];
@@ -85,33 +109,33 @@ final class VoicePanel extends LinearLayout {
.setPositiveButton("允许所选对象",(d,w)->{JSONArray selected=new JSONArray();for(int i=0;i<checked.length;i++)if(checked[i])selected.put(options.optJSONObject(i).optString("id"));saveSettings(true,selected);}).show();
}
void saveSettings(boolean receive,JSONArray ids){
if(receive&&ids.length()==0){status.setText("请先选择允许的家人或终端");return;}
if(receive&&ids.length()==0){showStatus("请先选择允许的家人或终端");return;}
if(!receive){enabled=false;stopPlayer("rejected");}String t=token.get();int e=epoch;
worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("configure").put("enabled",receive).put("allowed",ids).put("consent",true));ui.post(()->{if(current(e,t)){lastMessage="";poll();}});}catch(Exception error){ui.post(()->{if(current(e,t))status.setText("接收设置保存失败,请检查网络后重试");});}});
worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("configure").put("enabled",receive).put("allowed",ids).put("consent",true));ui.post(()->{if(current(e,t)){lastMessage="";poll();}});}catch(Exception error){ui.post(()->{if(current(e,t))showStatus("接收设置保存失败,请检查网络后重试");});}});
}
void begin(){
if(!visible||recorder!=null||sending||selectedTarget().isEmpty())return;
JSONObject target=destinations.optJSONObject(targets.getSelectedItemPosition());if(target==null||!target.optBoolean("online")){status.setText("请先让对方打开 App");return;}
if(!microphone()){status.setText("请先连接麦克风;仍可接收家人喊话");return;}
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);status.setText("授权麦克风后,再次按住说话");return;}
JSONObject target=destination();if(target==null||!target.optBoolean("online")){showStatus("请先让对方打开 App");return;}
if(!microphone()){showStatus("请先连接麦克风;仍可接收家人喊话");return;}
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);showStatus("授权麦克风后,再次按住说话");return;}
stopPlayer("rejected");cancelled=false;recordTarget=selectedTarget();recordToken=token.get();lastMessage="";
try{
recording=File.createTempFile("voice-record-",".aac",app.getCacheDir());recorder=new MediaRecorder();recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);recorder.setAudioSamplingRate(16000);recorder.setAudioChannels(1);recorder.setAudioEncodingBitRate(32000);recorder.setOutputFile(recording.getAbsolutePath());recorder.prepare();recorder.start();started=SystemClock.elapsedRealtime();
speak.setText("松开发送");targets.setEnabled(false);settings.setEnabled(false);status.setText("正在录音 · 移出按钮后松开取消");ui.postDelayed(limit,30000);
}catch(Exception error){finish(false);status.setText("无法录音,请检查话筒和权限");}
settings.setEnabled(false);showStatus("正在对"+target.optString("name")+"说话");ui.postDelayed(limit,30000);renderSurfaces();
}catch(Exception error){finish(false);showStatus("无法录音,请检查话筒和权限");}
}
void finish(boolean send){
ui.removeCallbacks(limit);if(recorder==null)return;MediaRecorder r=recorder;recorder=null;
try{r.stop();}catch(Exception error){send=false;}finally{r.release();}
File file=recording;recording=null;speak.setText("🎙 按住说话");targets.setEnabled(true);settings.setEnabled(true);
if(!send||SystemClock.elapsedRealtime()-started<350||file==null){if(file!=null)file.delete();status.setText("录音已取消");return;}
final String t=recordToken,destination=recordTarget;final int e=epoch;sending=true;speak.setEnabled(false);status.setText("正在发送喊话…");
File file=recording;recording=null;settings.setEnabled(true);renderSurfaces();
if(!send||SystemClock.elapsedRealtime()-started<350||file==null){if(file!=null)file.delete();showStatus(send?"说话时间太短,请按住后再说一句":"已取消,这条语音没有发送");renderSurfaces();return;}
final String t=recordToken,destination=recordTarget;final int e=epoch;sending=true;speak.setEnabled(false);showStatus("正在发送喊话…");
worker.execute(()->{try{
if(!current(e,t))return;byte[] bytes=Files.readAllBytes(file.toPath());if(bytes.length>150000)throw new IOException("Too large");
JSONObject result=DisplayApi.call("/api/voice",t,body("send").put("target",destination).put("id",UUID.randomUUID().toString().replace("-","")).put("audio",Base64.encodeToString(bytes,Base64.NO_WRAP)));
ui.post(()->{if(current(e,t)){lastMessage=result.optString("id");status.setText("已发送,等待对方播放");}});
}catch(Exception error){ui.post(()->{if(current(e,t))status.setText("发送未成功,请检查对方的接收权限和在线状态");});}
ui.post(()->{if(current(e,t)){lastMessage=result.optString("id");showStatus("已发送,等待对方播放");}});
}catch(Exception error){ui.post(()->{if(current(e,t))showStatus("未发送,请检查网络或对方的接收权限后重新录制");});}
finally{file.delete();ui.post(()->{sending=false;if(current(e,t))poll();});}});
}
void take(String id){
@@ -127,16 +151,16 @@ final class VoicePanel extends LinearLayout {
playingToken=t;focus=new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(attributes).setOnAudioFocusChangeListener(change->{if(change<0)stopPlayer("rejected");}).build();
if(audio.requestAudioFocus(focus)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED)throw new IOException("Audio busy");
playing=File.createTempFile("voice-play-",".aac",app.getCacheDir());Files.write(playing.toPath(),bytes);player=new MediaPlayer();player.setAudioAttributes(attributes);player.setDataSource(playing.getAbsolutePath());
player.setOnPreparedListener(p->{if(visible&&enabled&&p==player){p.start();stop.setEnabled(true);status.setText(clip.optString("senderName")+"正在喊话 · "+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
player.setOnPreparedListener(p->{if(visible&&enabled&&p==player){p.start();stop.setEnabled(true);showStatus(clip.optString("senderName")+"正在喊话 · "+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
player.setOnCompletionListener(p->stopPlayer("played"));player.setOnErrorListener((p,what,extra)->{stopPlayer("rejected");return true;});player.prepareAsync();
}catch(Exception error){stopPlayer("rejected");status.setText("语音未能播放,请检查扬声器");}
}catch(Exception error){stopPlayer("rejected");showStatus("语音未能播放,请检查扬声器");}
}
void stopPlayer(String outcome){
if(player!=null){try{player.release();}catch(Exception ignored){}player=null;}
if(focus!=null){audio.abandonAudioFocusRequest(focus);focus=null;}
if(playing!=null){playing.delete();playing=null;}
if(!playingId.isEmpty()&&!playingToken.isEmpty())ack(playingToken,playingId,outcome);
playingId="";playingToken="";stop.setEnabled(false);
playingId="";playingToken="";stop.setEnabled(false);renderSurfaces();
}
void ack(String t,String id,String state){if(!worker.isShutdown())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("ack").put("id",id).put("status",state));}catch(Exception ignored){}});}
}
@@ -0,0 +1,92 @@
package cn.ucvl.zhaodisplay;
import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.*;
import android.graphics.drawable.*;
import android.view.*;
import android.widget.*;
import org.json.*;
import java.util.function.Consumer;
/** Native warm, large-target view shared by the compact dock and full voice sheet. */
final class VoiceSurface extends LinearLayout {
final boolean full;final TextView title,subtitle,recipient,status,hint,clock,receive;
final Button speak,settings,stop,expand;final LinearLayout people,compose;final HorizontalScrollView strip;
final VoiceArt art;boolean night=false;String targetSignature="",controlSignature="";
int ink(){return night?0xffc8d5cd:0xff29443c;}int muted(){return night?0xff96aaa0:0xff65766d;}
int accent(){return night?0xff456b5e:0xff17695e;}int paper(){return night?0xff172820:0xfff8f5ed;}
int card(){return night?0xff21372d:0xfffffefa;}
int dp(float n){return Math.round(n*getResources().getDisplayMetrics().density);}
VoiceSurface(Activity activity,boolean expanded){
super(activity);full=expanded;setOrientation(VERTICAL);setPadding(dp(full?20:12),dp(full?20:8),dp(full?20:12),dp(full?22:8));
LinearLayout header=new LinearLayout(activity);header.setGravity(Gravity.CENTER_VERTICAL);addView(header);
title=label(full?"家人喊话":"家人喊话",full?30:19);title.setTypeface(null,Typeface.BOLD);header.addView(title,new LayoutParams(0,-2,1));
settings=button("接收设置",14);header.addView(settings);expand=button(full?"收起":"展开",14);header.addView(expand);
subtitle=label("一句问候,家就在身边",17);if(full){addView(subtitle);space(16);}
strip=new HorizontalScrollView(activity);strip.setHorizontalScrollBarEnabled(false);strip.setClipToPadding(false);
people=new LinearLayout(activity);people.setOrientation(HORIZONTAL);strip.addView(people);if(full)addView(strip,new LayoutParams(-1,-2));
receive=label("",13);if(full){space(8);addView(receive);space(16);}
recipient=label("选择一位家人",full?23:15);recipient.setTypeface(null,full?Typeface.BOLD:Typeface.NORMAL);recipient.setMaxLines(full?2:1);recipient.setEllipsize(android.text.TextUtils.TruncateAt.END);addView(recipient);if(full)space(14);
compose=new LinearLayout(activity);compose.setOrientation(VERTICAL);compose.setGravity(Gravity.CENTER_HORIZONTAL);compose.setPadding(dp(full?20:0),dp(full?18:0),dp(full?20:0),dp(full?18:0));addView(compose,new LayoutParams(-1,-2));
art=new VoiceArt(activity);art.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);if(full)compose.addView(art,new LayoutParams(-1,dp(88)));
clock=label("按住说话,松开发送",16);clock.setGravity(Gravity.CENTER);if(full)compose.addView(clock,new LayoutParams(-1,dp(56)));
status=label("先配对,再选择家人",full?16:13);status.setGravity(Gravity.CENTER);status.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE);
speak=button("按住说话",full?24:21);speak.setTypeface(null,Typeface.BOLD);speak.setCompoundDrawablePadding(dp(12));speak.setContentDescription("按住说话,松开发送,上滑取消");
LayoutParams talkParams=new LayoutParams(-1,dp(full?80:64));talkParams.topMargin=dp(full?14:6);compose.addView(speak,talkParams);
hint=label("上滑取消 · 最长 30 秒",13);hint.setGravity(Gravity.CENTER);if(full){spaceIn(compose,10);compose.addView(hint);spaceIn(compose,16);}else spaceIn(compose,4);
compose.addView(status,new LayoutParams(-1,-2));
stop=button("停止播放",16);stop.setVisibility(GONE);compose.addView(stop);
applyTheme(false);
}
TextView label(String text,int size){TextView v=new TextView(getContext());v.setText(text);v.setTextSize(size);v.setPadding(0,dp(3),0,dp(3));return v;}
static void text(TextView view,CharSequence value){if(!android.text.TextUtils.equals(view.getText(),value))view.setText(value);}
Button button(String text,int size){Button b=new Button(getContext());b.setText(text);b.setTextSize(size);b.setAllCaps(false);b.setMinHeight(dp(44));b.setMinimumHeight(dp(44));b.setMinWidth(0);b.setMinimumWidth(0);b.setPadding(dp(12),dp(8),dp(12),dp(8));b.setStateListAnimator(null);return b;}
void space(int amount){spaceIn(this,amount);}void spaceIn(LinearLayout parent,int amount){parent.addView(new View(getContext()),new LayoutParams(1,dp(amount)));}
GradientDrawable shape(int color,int border,int radius){GradientDrawable d=new GradientDrawable();d.setColor(color);d.setCornerRadius(dp(radius));if(border!=0)d.setStroke(dp(1),border);return d;}
void applyTheme(boolean value){
night=value;setBackgroundColor(paper());for(TextView t:new TextView[]{title,recipient,clock})t.setTextColor(ink());for(TextView t:new TextView[]{subtitle,status,hint,receive})t.setTextColor(muted());
compose.setBackground(full?shape(card(),night?0xff345043:0xffe4e8df,26):null);
for(Button b:new Button[]{settings,stop,expand}){b.setTextColor(ink());b.setBackground(shape(night?0xff2d4439:0xffefeee6,0,18));}
art.night=value;art.invalidate();targetSignature="";controlSignature="";
}
void targets(JSONArray values,String selected,Consumer<String> choose){
String signature=String.valueOf(values)+selected+night;if(signature.equals(targetSignature))return;targetSignature=signature;people.removeAllViews();
if(values==null||values.length()==0){TextView empty=label("暂无允许接收的家人\n请对方打开 App,在接收设置中允许你",16);empty.setTextColor(muted());people.addView(empty,new LayoutParams(dp(285),-2));return;}
for(int i=0;i<values.length();i++){
JSONObject item=values.optJSONObject(i);if(item==null)continue;String id=item.optString("id"),name=item.optString("name","家人");boolean chosen=id.equals(selected),online=item.optBoolean("online");
LinearLayout tile=new LinearLayout(getContext());tile.setOrientation(VERTICAL);tile.setGravity(Gravity.CENTER);tile.setPadding(dp(8),dp(12),dp(8),dp(10));
tile.setBackground(shape(chosen?(night?0xff304f40:0xffeaf3ec):card(),chosen?accent():night?0xff345043:0xffe5e6dc,20));tile.setFocusable(true);tile.setClickable(true);tile.setSelected(chosen);tile.setContentDescription(name+","+(online?"已打开 App":"未打开 App")+(chosen?",已选中":",点按选择"));tile.setOnClickListener(v->choose.accept(id));
TextView avatar=label(name.isEmpty()?"家":name.substring(0,name.offsetByCodePoints(0,1)),28);avatar.setGravity(Gravity.CENTER);avatar.setTypeface(null,Typeface.BOLD);avatar.setTextColor(chosen?Color.WHITE:ink());avatar.setBackground(shape(chosen?accent():night?0xff375547:0xffe2e9dc,0,30));tile.addView(avatar,new LayoutParams(dp(54),dp(54)));
TextView caption=label(name+(chosen?" ✓":""),17);caption.setGravity(Gravity.CENTER);caption.setTypeface(null,Typeface.BOLD);caption.setMaxLines(2);caption.setTextColor(ink());tile.addView(caption);
TextView availability=label(online?"● 已打开 App":"○ 未打开 App",12);availability.setGravity(Gravity.CENTER);availability.setTextColor(online?(night?0xff9bbfab:accent()):muted());tile.addView(availability);
LayoutParams layout=new LayoutParams(dp(122),dp(146));layout.rightMargin=dp(10);people.addView(tile,layout);
}
}
void recording(boolean recording,boolean cancel,long duration,int amplitude,boolean uploading,boolean canSpeak){
int color=cancel?(night?0xff69433b:0xffa84b37):accent();speak.setEnabled(canSpeak||recording);speak.setAlpha(canSpeak||recording?1f:.52f);
String label=recording?(cancel?"松开取消":"松开发送"):uploading?"正在发送…":"按住说话";
MicIcon inline=new MicIcon(night?0xffc8d5cd:Color.WHITE,dp(24));inline.setBounds(0,0,dp(24),dp(24));
android.text.SpannableString text=new android.text.SpannableString(" "+label);text.setSpan(new android.text.style.ImageSpan(inline,android.text.style.ImageSpan.ALIGN_BOTTOM),0,1,android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);if(!android.text.TextUtils.equals(speak.getText(),text)||!controlSignature.equals(color+":"+night))speak.setText(text);speak.setTextColor(night?0xffd1dfd5:Color.WHITE);
String signature=color+":"+night;if(!signature.equals(controlSignature)){controlSignature=signature;
speak.setBackground(new RippleDrawable(ColorStateList.valueOf(0x337fffff),shape(color,0,32),null));}
clock.setTextSize(recording?38:16);clock.setTypeface(null,recording?Typeface.BOLD:Typeface.NORMAL);text(clock,recording?String.format(java.util.Locale.ROOT,"00:%02d",Math.min(30,duration/1000)):"按住说话,松开发送");clock.setTextColor(cancel?color:ink());
text(hint,recording?(cancel?"松开手指,取消这条语音":"上滑取消 · 松开发送 · 30 秒自动发送"):"上滑取消 · 最长 30 秒");hint.setTextColor(cancel?color:muted());
art.level(recording,cancel,amplitude);if(!full&&recording)text(recipient,String.format(java.util.Locale.CHINA,"%s · %02d 秒",cancel?"松开即取消":"正在录音,上滑可取消",Math.min(30,duration/1000)));
}
static final class MicIcon extends Drawable {
final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);final int size;
MicIcon(int color,int size){paint.setColor(color);this.size=size;}
public int getIntrinsicWidth(){return size;}public int getIntrinsicHeight(){return size;}
public void draw(Canvas canvas){Rect b=getBounds();canvas.save();canvas.translate(b.left,b.top);canvas.scale(b.width()/24f,b.height()/24f);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(1.8f);paint.setStrokeCap(Paint.Cap.ROUND);canvas.drawRoundRect(8,2,16,15,4,4,paint);canvas.drawArc(5,5,19,20,0,180,false,paint);canvas.drawLine(5,12,5,13,paint);canvas.drawLine(19,12,19,13,paint);canvas.drawLine(12,20,12,23,paint);canvas.drawLine(8,23,16,23,paint);canvas.restore();}
public void setAlpha(int alpha){paint.setAlpha(alpha);}public void setColorFilter(ColorFilter f){paint.setColorFilter(f);}public int getOpacity(){return PixelFormat.TRANSLUCENT;}
}
static final class VoiceArt extends View {
final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);final float[] bars=new float[31];boolean recording=false,cancel=false,night=false;
VoiceArt(Activity app){super(app);}
void level(boolean active,boolean cancelled,int amplitude){if(active){System.arraycopy(bars,1,bars,0,bars.length-1);bars[bars.length-1]=(float)Math.min(1,Math.sqrt(Math.max(0,amplitude)/32768d));}else java.util.Arrays.fill(bars,0);recording=active;cancel=cancelled;invalidate();}
protected void onDraw(Canvas c){super.onDraw(c);int w=getWidth(),h=getHeight();paint.setStyle(Paint.Style.FILL);int color=cancel?0xffa84b37:night?0xff91ac9d:0xff267266;
if(recording){paint.setColor(color);float step=w/35f;for(int i=0;i<bars.length;i++){float height=Math.max(4,bars[i]*(h-14));float x=step*(i+2);c.drawRoundRect(x-step*.22f,(h-height)/2,x+step*.22f,(h+height)/2,4,4,paint);}}
else{paint.setColor(night?0xff2d4439:0xfff0f1e8);c.drawCircle(w/2f,h/2f,Math.min(h*.43f,48),paint);MicIcon icon=new MicIcon(color,44);int size=(int)(h*.48f);icon.setBounds((w-size)/2,(h-size)/2,(w+size)/2,(h+size)/2);icon.draw(c);}}
}
}