Android Service
2018-10-06 本文已影响23人
安卓小白之小楼又东风
Android Service(服务)
- 服务的定义
服务是Android中实现后台运行的解决方案。 - android多线程
定义线程:(两种方式)
class MyThread extends Thread{
@Override
public void run(){
//处理的逻辑
}
}
class MyThread implements Runnable{
@Override
public void run(){
//处理的逻辑
}
}
启动线程
MyThread myThread = new MyThread();
new Thread(myTread).start();
定义和启动线程
new Thread(new Runnable){
@Override
public void run(){
}
}
利用线程改变Ui
MainActivity
package com.example.administrator.androidthreadtest;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView textView;
public static final int UPDATE_TEXT = 1;
private Handler handler = new Handler(){
public void handleMessage(Message message){
switch (message.what){
case UPDATE_TEXT:
textView.setText("Nice to meet you");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textview);
Button changText = (Button)findViewById(R.id.change_text);
changText.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.change_text:
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
break;
default:
break;
}
}
}
activity_main_layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/change_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Change Text"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"
android:text="Hello World!"
/>
</RelativeLayout>
运行效果
此处输入图片的描述
-
异步消息处理机制
如图
用AsyncTask更好地实现了子线程UI的操作。
三个参数 - Params:执行时传入的参数。
- Progress:指定泛型的进度单位。
- Result:执行后返回的结果。
//自定义AsyncTask类
class DownloadTask extends AsyncTask<Void,Integer,Boolean>{
}
还需要重写一些方法:onPreExecute(),doInBackground(params...),onProgressUpdate(Progress...),
onPostExcute(Result).
class DownloadTask extends AsyncTask<Void,Integer,Boolean>{
@Override
protected void onPreExecute(){
progressDialog.show();//显示进度条
}
@Override
protected Boolean doInBackground <Void ...params){
try{
while(true){
int downloadPercent = doDownload();
publishProgress(downloadPercent);
if(downloadPercent >= 100){
break;
}
}
}catch(Exception e){
return false;
}
return true;
}
@Override
protected void onProgressUpdate (Integer ...values){
progressDialog.setMessage("Finish"+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();
}
}
}
AsyncTask的核心是:doInBackground执行耗时的任务,onProgressUpdate进行UI操作,在onPostExecute执行返回结果的一些操作,如弹出下载完成对话框的动作。
new DownloadTask().execute()
启动任务(下载)
Service
定义一个服务,新建service
新建服务
重写onCreate,onStartCommand,onDestory方法。
我们在activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动服务"
/>
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止服务"/>
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定服务"
/>
<Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解绑服务"
/>
</LinearLayout>
这里我们定义四个按钮:启动,停止,绑定,解绑.
MainActivity
package com.example.administrator.servicetest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MyService.DownloadBinder downloadBinder;//这里是Myservice中的内部类
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder)service;
downloadBinder.startDownload();//这是MyService中的方法。
downloadBinder.getProgress();//这是MyService中的方法。
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//设置点击事件观察服务的一些信息
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Start = (Button)findViewById(R.id.start_service);
Button Stop = (Button)findViewById(R.id.stop_service);
Button Bind = (Button)findViewById(R.id.bind_service);
Button unBind = (Button)findViewById(R.id.unbind_service);
Start.setOnClickListener(this);
Stop.setOnClickListener(this);
Bind.setOnClickListener(this);
unBind.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_service:
Intent intentOne = new Intent(this,MyService.class);
startService(intentOne);//启动服务
break;
case R.id.stop_service:
Intent intentTwo = new Intent(this,MyService.class);
stopService(intentTwo);//停止服务
break;
case R.id.bind_service:
Intent intentThree = new Intent(this,MyService.class);
bindService(intentThree,connection,BIND_AUTO_CREATE);//绑定服务
break;
case R.id.unbind_service:
Intent intentFour = new Intent(this,MyService.class);
unbindService(connection);//解绑服务
break;
default:
break;
}
}
}
MyService
package com.example.administrator.servicetest;
import android.app.DownloadManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService","开始下载");
}
public int getProgress(){
Log.d("MyService","getProgress");
return 0;
}
}
//构造方法
public MyService() {
}
//绑定服务
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return mBinder;
}
//服务的创建
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService","onCreate方法");//打印输出
}
//onCreate方法之后,多次执行,onCreate一次执行(观察logcat的打印)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService","onStartCommand方法");
return super.onStartCommand(intent, flags, startId);
}
//服务的销毁,类似Activity的生命周期方法。
@Override
public void onDestroy() {
Log.d("MyService","onDestroy方法");
super.onDestroy();
}
}
使用IntentService:运用Android多线程编程,给service新建一个子线程。
新建一个类继承于IntentService类:
package com.example.administrator.servicetest;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyIntentService extends IntentService {
public MyIntentService(){
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService","Thread id is"+Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService","onDestroy方法2");
}
}
MainActivity中:
package com.example.administrator.servicetest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Start = (Button)findViewById(R.id.start_service);
Button Stop = (Button)findViewById(R.id.stop_service);
Button Bind = (Button)findViewById(R.id.bind_service);
Button unBind = (Button)findViewById(R.id.unbind_service);
Button StartIntentService = (Button) findViewById(R.id.start_intent_service);
Start.setOnClickListener(this);
Stop.setOnClickListener(this);
Bind.setOnClickListener(this);
unBind.setOnClickListener(this);
StartIntentService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_service:
Intent intentOne = new Intent(this,MyService.class);
startService(intentOne);//启动服务
break;
case R.id.stop_service:
Intent intentTwo = new Intent(this,MyService.class);
stopService(intentTwo);//停止服务
break;
case R.id.bind_service:
Intent intentThree = new Intent(this,MyService.class);
bindService(intentThree,connection,BIND_AUTO_CREATE);//绑定服务
break;
case R.id.unbind_service:
Intent intentFour = new Intent(this,MyService.class);
unbindService(connection);//解绑服务
break;
case R.id.start_intent_service:
Log.d("Mainctivity","Thread id is" + Thread.currentThread().getId());
Intent intentService = new Intent(this,MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}
}