thread

我们知道安卓不能在子线程中进行UI操作,那么我们如何在发送一个子进程的过程中然后进行UI操作呢

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

public static final int UP_DATE=1;

private TextView text;

private Handler handler=new Handler(){

public void handleMessage(Message msg){

switch(msg.what){

case UPDATE_TEXT:

text.setText("Nice to meet you");

break;

default:break;}}};

...

public void onClick(View v){

switch(v.getId)){

case R.id.change_text:

new Thread(new Runnable(){

public void run(){  Message message=new Message();   message.what=UPDATE_TEXT;handler.sendMessage(message);}

还可以使用一种更简单的工具AsyncTask从子线程切换到主线程:这是一个抽象类:有三个参数需要一个子类去继承。

AsyncTask(Params:后台任务传入的参数,Progress:进度单位,Result:对结果进行返回><void,Integer,Boolean>

需要重写的几个方法

1、onPreExecute()后台任务开始之前调用,用于显示一些界面上的初始化操作

2、doInBackground(params...)这个方法中代码都会在子线程中进行,反馈当前任务进度可以调用publishProgress(Progress)

3、onProgressUpdate(Progress)后台任务传递过来的,可以进行UI操作

4、onPostExecute(Result)利用返回结果进行UI操作

添加服务:在example包中添加new service命名为MyService 继承Service

public class MyService extends Service{

public MyService(){}

@Override

public void onCreate(){  super.onCreate()};

@Override public int onStartCommand(Intent intent,int flags,int startId){}

@Override public void Destroy(){super.onDestroy();}

@Override   public IBinder onbind(Intent intent){throw new UnsupportedOperationException("fff");}

启动服务的按键响应方式:Intent startIntent=new Intent(this,MyService.class) ;   startService(startIntent);

停止方式 Intent stopIntent;   stopService(stopIntent);

在服务运行的任何位置调用stopSelf()都能拿使服务自动停止;

活动与服务的联系更紧密就要用到上面的onBind()方法了;

public class MyService extends Service{

private DownloadBinder mBinder=new DownloadBinder();

class DownloadBinder extends Binder{

public void start Download();   public  int getProgress();    public int getProgress();}

@Override   public IBinder onBind(Intent intent){   return mBinder;}}

然后在活动中处理这个:

public class.....{

private MyService.DownloadBinder downloadBinder;

private ServiceConnection connection=new ServiceConnection(){

@Override   public void onServiceDisconnected(ComponentName name){}

@Override    public void onServiceConnected(ComponentName name,IBinder service){

downloadBinder=(MyService.DownloadBinder)service;

downloadBinder.startDownload();

downloadBinder.getProgress();}};

同理bindService 与unbindService 与上面的startService和stopService用法一样;

bindService(bindIntent,connection,BIND_AUTO_CREATE);   unbindService(connection);

在服务中startForeground(1,notification)可以在前台显示通知。

在onStartCommand函数中可以

new Thread(new Runnable(){

public void run(){

stopSelf();

}

}IntentService可以创建异步的,自动停止的服务。

Thread.currentThread().getId();打印当前线程的ID;同时还要记住去androidmanifest里面注册服务<service android:name=".MyIntentService"/>

完整的下载示例:

写文件流FileOutputStream out=openFileOutput(fileName,Activity.MPDE_PRIVATE)重复写入文件会覆盖

out.write(content.getBytes());

out.close()

读文件

FileInputStream in=this.openFileInput(fileName);

byte[] bytes=new byte[1024];

ByteArrayOutputStream arrayout=new....;

String content=new String(arrayout.toByteArray());

showTextView.setText(content);

定义一个回调接口,用于对下载过程中各种状态进行监听和回调

public interface DownloadListener{

void onProgress(int progress);

void onSuccess();

void onFailed();

void onPaused();

void onCanceled();}

public class DownloadTask extends AsyncTask<String,integer,Integer>{

public static final int TYPE_SUCCESS=0;

public static final int TYPE_FAILED=1;

public static final int TYPE_PAUSED=2;

public static final int TYPE_CANCELED=3;

private DownloadListener listener;

private boolean isCanceled=false;

private boolean isPaused=false;

private int lastProgress;

public DownloadTask(DownloadListener listener){

this.listener=listener;}在服务的过程中回调参数。

@Override

protected Integer doInBackground(String ...params){

InputStream is=null;

RandomAccessFile savedFile=null;

File file=null;

try{

long downloadLength=0;

String downloadUrl=params[0];

String fileName=downloadUrl.substring(downloadUrl.lastIndexOf("/"));

String directory=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();

file=new File(directory+fileName);

if (file.exists()){downloadedLength=file.length();}

long contentLength=getContentLength(downloadUrl);

if (contentLength==0){

return TYPE_FAILED;}

else if (contentLength=downloadedLength){

return TYPE_SUCCESS;}

OkHttpClient client=new OkHttpClient();

Request request=new Request.Builder().addHeader("RANGE","bytes="+downloadedLength+"-")

.url(downloadUrl).build();Response response=client.newCall(request).execute();

if (response!=null){

is=response.body().byteStream();

savedFile=new RandomAccessFile(file,"rw");

savedFile.seek(downloadedLength);

byte[] b=new byte[1024];

int total=0;

int len;

while ((len=is.read(b))!=-1){

if (isCancled)   return TYPE_CANCELED;  else if (isPaused)  return TYPE_PAUSED;

else {total+=len;   savedFile.write(b,0,len);   

int progress=(int)((total+downloadedLength)*100/contentLength);

publishProgress(progress);}}

response.body().close;

return TYPE_SUCCESS;}catch(Exception e){  e.printStackTrace();}

finally{try{if (is!=null){  is.close();}   if (savedFile!=null){savedFile.close();}if (isCanceled&&file!=null){file.delete()'}}

catch(Exception e){ e.printStackTrace();}}

return TYPE_FAILED}

@Override

protected  void onProgressUpdate(Integer...values){

int progress=values[0];

if (progress>lastProgress){listener.onProgress(progress);   lastProgress=progress;}}

@Override

protected void onPostExecute(Integer status){

switch(status)   case TYPE_SUCCESS;

listener.onSuccess();

....

}}

public void pauseDownload(){

isPaused =true;}

public void cancelDownload(){   isCanceled=true;}

private long getContentLength(String downloadUrl)throws IOException{

OkHttpClient client=new OkHttpClient();

Request request=new Request.Builder().url(downloadUrl).build();

Response response=client.newCall(request).execute();

if (response!=null&&response.isSuccessful()){

long contentLength=response.body().contentLength();

response.close();

return contentLength();}

return 0;}}


【轴承故障诊断】加权多尺度字典学习模型(WMSDL)及其在轴承故障诊断上的应用(Matlab代码实现)内容概要:本文介绍了加权多尺度字典学习模型(WMSDL)在轴承故障诊断中的应用,并提供了基于Matlab的代码实现。该模型结合多尺度分析与字典学习技术,能够有效提取轴承振动信号中的故障特征,提升故障识别精度。文档重点阐述了WMSDL模型的理论基础、算法流程及其在实际故障诊断中的实施步骤,展示了其相较于传统方法在特征表达能力和诊断准确性方面的优势。同时,文中还提及该资源属于一个涵盖多个科研方向的技术合集,包括智能优化算法、机器学习、信号处理、电力系统等多个领域的Matlab仿真案例。; 适合人群:具备一定信号处理和机器学习基础,从事机械故障诊断、工业自动化、智能制造等相关领域的研究生、科研人员及工程技术人员。; 使用场景及目标:①学习并掌握加权多尺度字典学习模型的基本原理与实现方法;②将其应用于旋转机械的轴承故障特征提取与智能诊断;③结合实际工程数据复现算法,提升故障诊断系统的准确性和鲁棒性。; 阅读建议:建议读者结合提供的Matlab代码进行实践操作,重点关注字典学习的训练过程与多尺度分解的实现细节,同时可参考文中提到的其他相关技术(如VMD、CNN、BILSTM等)进行对比实验与算法优化。
【硕士论文复现】可再生能源发电与电动汽车的协同调度策略研究(Matlab代码实现)内容概要:本文档围绕“可再生能源发电与电动汽车的协同调度策略研究”展开,旨在通过Matlab代码复现硕士论文中的核心模型与算法,探讨可再生能源(如风电、光伏)与大规模电动汽车接入电网后的协同优化调度方法。研究重点包括考虑需求侧响应的多时间尺度调度、电动汽车集群有序充电优化、源荷不确定性建模及鲁棒优化方法的应用。文中提供了完整的Matlab实现代码与仿真模型,涵盖从场景生成、数学建模到求解算法(如NSGA-III、粒子群优化、ADMM等)的全过程,帮助读者深入理解微电网与智能电网中的能量管理机制。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的研究生、科研人员及从事新能源、智能电网、电动汽车等领域技术研发的工程人员。; 使用场景及目标:①用于复现和验证硕士论文中的协同调度模型;②支撑科研工作中关于可再生能源消纳、电动汽车V2G调度、需求响应机制等课题的算法开发与仿真验证;③作为教学案例辅助讲授能源互联网中的优化调度理论与实践。; 阅读建议:建议结合文档提供的网盘资源下载完整代码,按照目录顺序逐步学习各模块实现,重点关注模型构建逻辑与优化算法的Matlab实现细节,并通过修改参数进行仿真实验以加深理解。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值