android service 简书,Android Service

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

android:layout_width="match_parent"

android:layout_height="match_parent"

>

android:id="@+id/change_text"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Change Text"/>

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!"

/>

运行效果

8b48c6c79babe7b2112ac923c7e748f0.png

此处输入图片的描述

异步消息处理机制

4f5518c7181b4e6ac60fd424d820ad62.png

如图

用AsyncTask更好地实现了子线程UI的操作。

三个参数

Params:执行时传入的参数。

Progress:指定泛型的进度单位。

Result:执行后返回的结果。

//自定义AsyncTask类

class DownloadTask extends AsyncTask{

}

还需要重写一些方法:onPreExecute(),doInBackground(params...),onProgressUpdate(Progress...),

onPostExcute(Result).

class DownloadTask extends AsyncTask{

@Override

protected void onPreExecute(){

progressDialog.show();//显示进度条

}

@Override

protected Boolean doInBackground

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

a71caf0f7ec3d315e60b448fa29a8df2.png

新建服务

重写onCreate,onStartCommand,onDestory方法。

我们在activity_main:

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent"

>

android:id="@+id/start_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="启动服务"

/>

android:id="@+id/stop_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="停止服务"/>

android:id="@+id/bind_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="绑定服务"

/>

android:id="@+id/unbind_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="解绑服务"

/>

这里我们定义四个按钮:启动,停止,绑定,解绑.

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值