編輯:關於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(); } }
本文實例講述了Android控件之Spinner用法。分享給大家供大家參考。具體如下:以下模擬下拉列表的用法布局文件:<?xml version=1.0 e
DPI:每英寸像素數簡單的屏幕分辨率計算方法:DisplayMetrics metrics = new DisplayMetrics();Display display
現在大家越來越多的使用AndroidStudio進行Android開發,那麼今天就和大家一起交流一下AndroidStudio開發NDK的配置方法。AndroidStud
Android系統中的很多安全類軟件都支持垃圾清理,但總有一些不知名文件夾能逃過類似功能的“洗禮”。那麼,我們如何根據一些蛛絲馬跡了