android学习笔记(12) normal Services多线程初步

来源:互联网 发布:创意手机壳 知乎 编辑:程序博客网 时间:2024/05/17 04:57

直接上源码:

MainActivity.java

package com.example1.servicedemo;import org.apache.commons.logging.Log;import android.net.sip.SipAudioCall.Listener;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Button btnButton;private Button btnButton2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btnButton = (Button)findViewById(R.id.btnservicestart);        btnButton2 = (Button)findViewById(R.id.btnservicestop);        btnButton.setOnClickListener(listener);        btnButton2.setOnClickListener(listener);    }private OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnservicestart:// 本例子与上一课源码一样,仅修改了这一个地方:Intent intent = new Intent(MainActivity.this,ExamppleService.class);Log.i(TAG,"主线程ID:"+Thread.currentThread().getId());//输出当前线程IDstartService(intent);break;case R.id.btnservicestop:Intent intent2 = new Intent(MainActivity.this,ExamppleService.class);startService(intent2);break;default:break;}}};    }
ExampleService.java:

package com.example1.servicedemo;import org.apache.commons.logging.Log;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.LogPrinter;public class ExampleService extends Service {private static final String tag = "ExampleService";@Overridepublic IBinder onBind(Intent arg0) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {new MyThread().start();//创建一个新的线程,和主线程不同。这样一来点下载就会后台线程下载。return START_STICKY;}private class MyThread extends Thread{@Overridepublic void run() {try {android.util.Log.i(tag,"Exampleservice线程ID:"+Thread.currentThread().getId());android.util.Log.i(tag,"文件下载...");Thread.sleep(2000);             //如果把这3段话放在onStartCommand中,两个线程为同一个线程,这样一来如果点一个下载就要下载完了才能进行其它操作。} catch (InterruptedException e) {e.printStackTrace();}super.run();}}}
结果分别为:

主线程ID:1

文件下载...

Exampleservice线程ID:1

和:

主线程ID:1

文件下载...

Exampleservice线程ID:9

主线程ID:1

文件下载...

Exampleservice线程ID:10

主线程ID:1

文件下载...

Exampleservice线程ID:11






4 0
原创粉丝点击