三种多线程编程方法

1     class Mythread extends Thread{
@Override
public void run(){}
}
new Mythread().start()
2 class Mythread implements Runnable{
@Override
public void run(){}
}
Mythread myThread=new Mythread();
new Thread(myThread).start();
3 new Thread{new Runnable{
@Override
public void run(){}
}.start();

异步消息处理机制(使用message更新ui)

public class MainActivity extends Activity implements OnClickListener{
Button button;
TextView text;
public static final int change=1;
private Handler handler=new Handler(){
public void handleMessage(Message ms){
switch(ms.what){
case change:
text.setText("nice to meet you");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.change_Button);
text=(TextView)findViewById(R.id.text);
button.setOnClickListener(this); }
public void onClick(View v){
switch (v.getId()) {
case R.id.change_Button:
new Thread(new Runnable(){
public void run(){
Message ms=new Message();
ms.what=change;
handler.sendMessage(ms);
}
}).start();
break;
default:
break;
} }
}

使用AsynvTask更新ui

class DownloadTask extends AsyncTask<Void,Integer,Boolean>{
@Override
protected void onPreExecute(){
progressDialog.show();
}
@0verride
protected Boolean doInBackground(Void...params){
try{
while(true){
int downloadPercent=doDownload();
publishProgress(downloadPercent);
if(downloadPercent>=100){
break;
}
}
}catch(Exception e){
return false;
}
return true;
}
protected void onProgressUpdate(Integer...values){
progressDialog.setMessage("Download"+values[0]+"%");
}
@Override
protected void onPostExecute(Boolean result){
progressDialog.dismiss();
if(result){
Toast.makeText(context,"Download succeeded",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Download failed",Toast.LENGTH_SHORT).show();
}
}
}

定义一个服务

服务定义完成后要使用的话必须同android其他三大组件一样在manifest中注册才行 <service  android:name=".MyService"></service>
 在活动中启动或停止服务的话使用intent
  Intent intent=new Intent(this,Myservice.class);
  startService(intent);
  Intent intent1=new Intent(this,Myservice.class);
  stopService(intent1);或者是在服务的定义中调用stopSelf()来停止服务

public class MyService extends Service{
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
}
public int onStartCommand(Intent inten,int flags,int startId){
return super.onStartCommand(intent,flags,startId);
}
public void onDestroy(){
super.onDestroy();
}
}

活动和服务进行通信:使用onBind()

public class MyService extends Service{
private DownloadBinder mBinder=new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService","startdownload");
}
public int getProgress(){
Log.d("MyService","getProgress")
return 0
}
}
public IBinder onBind(Intent intent){
return mBinder;
}
}
主活动中调用 先建立一个ServieceConnection匿名类
private ServiceConnection connection=new ServiceConnection(){
public void onServiceDisconnected(ComponentName name){}
public void onServiceConnected(ComponentName name,IBinder service){
MyService.DownloadBinder downloadBinder=(MyService.DownloadBinder)service;获得一个DownloadBinder实例
downloadBinder.startDownload();
downloadBinder.getProgress();
}
}
Intent bindintent=new Intent(this,MyService.class);
bindService(bindintent,connection,BIND_ANTO_CREATE);绑定服务并且绑定后自动创建
。。
unbinderService(connection);解绑,connection为前面定义的ServiceConnection实例
注意服务在任何活动中都是通用的 可以和任何activity 进行绑定

使用intentService(可以自己开启线程并且可以自动停止)
定义:

public class MyIntentService  extends IntentService {

    public MyIntentService( ) {
super("MyIntentService");
// TODO Auto-generated constructor stub
}
protected void onHandleIntent(Intent intent){
Log.d("MyIntentService","thread id id"+Thread.currentThread().getId());
}
public void onDestroy(){
super.onDestroy();
Log.d("MyIntentService","ondestroy exe");
} }
在活动中启动或者的方法是一样的
Intent intentService=new Intent(this,MyIntentService.class);
startSercice(intentService);
同样要进行注册注册方法和普通服务一样的

服务的最佳实践  定时循环开启一项服务:

public class LongRunningService extends Service {
public IBinder onBind(Intent intent){
return null;
}
public int onStartCommand(Intent intent,int flags,int startId){
new Thread(new Runnable(){
public void run(){
Log.d(".","");
}
}).start();
AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
int anHour=60*60*1000;
long triggerAtTime=SystemClock.elapsedRealtime()+anHour;
Intent i=new Intent(this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this,0,i,0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
return super.onStartCommand(intent, flags, startId); }
} 定义一个广播接收器
public class AlarmReceiver extends BroadcastReceiver{
public void onReceive(Context context,Intent intent){
Intent i=new Intent(context,LongRunningService.class);
context.startService(i);
}
}
在活动中进行启动这个服务 一旦启动就会不断重复
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,LongRunningService.class);
startService(intent);
}
注意 :现在的手机当中为了省电,当存在多个Alarm定时任务的时候,他会
把时间相近的几个任务集合在一起去唤醒cpu,所以会有一些时间上的误差,为了准确无误,可以
把服务中manager.set()改为manager.setExact()

android 多线程 异步消息处理 服务 学习笔记 (六)的更多相关文章

  1. Android多线程----异步消息处理机制之Handler详解

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  2. # go微服务框架kratos学习笔记六(kratos 服务发现 discovery)

    目录 go微服务框架kratos学习笔记六(kratos 服务发现 discovery) http api register 服务注册 fetch 获取实例 fetchs 批量获取实例 polls 批 ...

  3. ArcGIS Runtime for Android 使用异步GP服务绘制等值线

    关于基于Android上ArcGIS Server GP服务的调用,已经有前辈给出了很好的例子: http://blog.csdn.net/esrichinacd/article/details/92 ...

  4. (转)ArcGIS Runtime for Android 使用异步GP服务绘制等值线

    关于基于Android上ArcGIS Server GP服务的调用,已经有前辈给出了很好的例子: http://blog.csdn.net/esrichinacd/article/details/92 ...

  5. Spring Cloud微服务学习笔记

    Spring Cloud微服务学习笔记 SOA->Dubbo 微服务架构->Spring Cloud提供了一个一站式的微服务解决方案 第一部分 微服务架构 1 互联网应用架构发展 那些迫使 ...

  6. Java IO学习笔记六:NIO到多路复用

    作者:Grey 原文地址:Java IO学习笔记六:NIO到多路复用 虽然NIO性能上比BIO要好,参考:Java IO学习笔记五:BIO到NIO 但是NIO也有问题,NIO服务端的示例代码中往往会包 ...

  7. java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)

    java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...

  8. Learning ROS for Robotics Programming Second Edition学习笔记(六) indigo xtion pro live

    中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...

  9. Typescript 学习笔记六:接口

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

随机推荐

  1. Appium Android sdk自动化工具安装

    RF环境搭建 略 Android环境搭建 jdk1.8 配环境变量 JAVA_HOME CALSSPATH:%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar; PAT ...

  2. ContextCapture水面约束(水面破洞修复)

      [问题描述] 对于水面而言,由于特征点较少,软件在计算时很难匹配正确,导致输出模型的水面通常是支离破碎的.软件针对这种情况提供了一个约束工具,用户手动的为水面添加平面约束后,输出的水面模型就会非常 ...

  3. zstu 4212 ——String Game ——————【字符串处理】

    4212: String Game Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 337  Solved: 41 Description Alice a ...

  4. 图像文字识别(OCR)用什么算法小结

    说明:主要考虑深度学习的方法,传统的方法不在考虑范围之内. 1.文字识别步骤 1.1detection:找到有文字的区域(proposal). 1.2classification:识别区域中的文字. ...

  5. 程序员心灵鸡汤桌面壁纸1080p 欢迎大家下载,HTML,PHP,node,css,前端

    上段时间在读书的时候看见了一句话:一张地图,不论比例多么精确,它永远不可能带着主人在地面上移动半步, 作为爱思考,爱学习的程序员 突然想到了:一份帮助文档,不论多么详细,它永远不会帮助主人敲一行代码. ...

  6. 1、Angular2 Component 组件

    angular2借鉴了.http://www.cnblogs.com/lewis617/p/5191007.html 导入了自己的思维方式 1.基本属性 2.*语法与template标签 3.组件的嵌 ...

  7. JUnit测试框架的使用

    1.学习Junit框架的使用 可通过以下两个示例进行学习. A.Junit使用方法示例1 1)把Junit引入当前项目库中 新建一个 Java 工程—coolJUnit,打开项目coolJUnit 的 ...

  8. IO流之File类

    IO概述: 程序数据都是在内存中,程序运行结束,这些数据将清空,数据都都不能保存下来,下次程序启动的时候,想再把这些数据读出来继续使用,把数据持久化存储,就需要把内存中的数据存储到内存以外的其他持久化 ...

  9. JS构造函数(便于理解,简易)

    * 构造函数: * 1.构造函数的函数名最好首字母大写(否则 WebStorm 编辑器会提示报错) * 2.自己的对象多次被复制 * 3.构造函数里可以创建公有属性.公有方法.私有属性和私有方法 * ...

  10. centos的nginx支持ssl

    首先看centos是否支持ssl 输入:openssl version 如无 则去 http://slproweb.com/products/Win32OpenSSL.html  寻找 生成私钥后面的 ...