【android 服务与多线程】幽沉谢世事,俯默窥唐虞。这篇文章主要讲述android 服务与多线程相关的知识,希望能为你提供帮助。
android服务是执行在UI主线程的。一下是代码demo:
package com.example.testservice; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class MainActivity extends Activity {@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(MainActivity.this,ServiceTest.class)); }@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }}
package com.example.testservice; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.Toast; public class ServiceTest extends Service { private Handler mHandler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: new Thread(){ @Override public void run() { Log.i("服务", "第2个线程"); Looper.prepare(); for(int i=10; i< 20; i++){ Toast.makeText(getApplicationContext(), i+"",0).show(); try { //Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception }} mHandler.sendEmptyMessage(2); Looper.loop(); }; }.start(); break; case 2: new Thread(){ @Override public void run() { Log.i("服务", "第3个线程"); Looper.prepare(); for(int i=20; i< 30; i++){ Toast.makeText(getApplicationContext(), i+"",0).show(); try { //Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception }} mHandler.sendEmptyMessage(3); Looper.loop(); }; }.start(); break; case 3: onDestroy(); break; default: break; } super.handleMessage(msg); } }; public ServiceTest() { // TODO Auto-generated constructor stub } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { Log.i("服务", "onCreate()"); super.onCreate(); new Thread(){ @Override public void run() { Log.i("服务", "第一个线程"); Looper.prepare(); for(int i=0; i< 10; i++){ Toast.makeText(getApplicationContext(), i+"",0).show(); try { //Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception }} mHandler.sendEmptyMessage(1); Looper.loop(); }; }.start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("服务", "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("服务", "onDestroy()"); super.onDestroy(); stopSelf(); } }
demo下载地址:http://download.csdn.net/detail/u014600432/8104521
推荐阅读
- Android MarginLeft与MarginStart的差别
- 安卓手机软件測试耗电量
- Android之自己定义checkbox样式
- Android蓝牙开发
- Charles 查看https请求数据 Mac/ android
- 怎样通过Html网页调用本地安卓app
- An internal error occurred during: &quot;J2EE Component Mapping Update&quot;.
- AndroidActivity间动画跳转
- Android 开发 Tip 6 -- Spinner