Android的service两种开启方式和UI操作(子线程)2020-09-07

这篇博客介绍了Android中Service的两种启动方式,包括startService和stopService以及通过Binder的绑定服务。同时,文章探讨了如何在服务中异步处理UI操作,避免主线程阻塞,并提到了使用子线程和AsyncTask来更新UI的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android的两种开启关闭Service和异步处理UI控件

这其中包括5个按钮startService,stopService,binderService,unBinderService,changeTextView,前两个按钮是为了展示第一种开启服务的方法,带binder的是第二种绑定binder开启服务的方法,最后一个是强制修改控件的Text的文本内容:
代码:我创建了两个Service
第一个MyService(startService,stopService):
package com.example.snake.startservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;

public class MyService extends Service {
private static final String TAG = “MyService”;
public MyService() {
}

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "onCreate executed: ");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand executed: ");
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy executed: ");
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

}
第二MyServiceBinder(binderService,unBinderService):
package com.example.snake.startservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyServiceBinder extends Service {
public static final String TAG = “MyServiceBinder”;
private DownloadBinder mbinder = new DownloadBinder();

    class DownloadBinder extends Binder{
        public void startDownload(){
            Log.d(TAG, "startDownload executed: ");
        }
        public int getProgress(){
            Log.d(TAG, "getProgress executed: ");
            return 0;
        }
}
public MyServiceBinder() {
}

@Override
public IBinder onBind(Intent intent) {
    return mbinder;
}

}
主界面:
package com.example.snake.startservice;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private static final String TAG = "MainActivity";

private Handler handler =new Handler(){
    public void handlerMessgae(Message message){
        switch (message.what){
            case 1:
                textView.setText("I have changed");
                break;
            default:
                break;
        }

    }
};
private MyServiceBinder.DownloadBinder downloadBinder;
private ServiceConnection connection =new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        downloadBinder = (MyServiceBinder.DownloadBinder) service;
        downloadBinder.startDownload();
        downloadBinder.getProgress();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button starService =(Button)findViewById(R.id.startService);
    Button stopService =(Button)findViewById(R.id.stopService);
    Button binderService =(Button)findViewById(R.id.binderservice);
    Button unbinderService =(Button)findViewById(R.id.unbinderservice);
    Button changeViewText =(Button)findViewById(R.id.startService);
    textView = (TextView)findViewById(R.id.textview);
    starService.setOnClickListener(this);
    stopService.setOnClickListener(this);
    binderService.setOnClickListener(this);
    unbinderService.setOnClickListener(this);
    changeViewText.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.startService:
            Intent intent = new Intent(this,MyService.class);
            startService(intent);
            break;
        case R.id.stopService:
            Intent stopintent =new Intent(this,MyService.class);
            stopService(stopintent);
            break;
        case R.id.binderservice:
            Intent binderIntent = new Intent(this, MyServiceBinder.class);
            bindService(binderIntent, connection, BIND_AUTO_CREATE);
            break;
        case R.id.unbinderservice:
            unbindService(connection);
            break;
        case R.id.changeViewText:
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            }).start();
            break;
        default:
            break;
    }

}

}
我这里的Service都是默认构建的,你若是自己创建的,请别忘了去AndroidManifest.xml里添加配置

最后一个键是为了可以强制修改UI的属性,因为服务依赖主进程,要是逻辑过多会导致程序崩溃,这里用了一个子线程避免了这方面的尴尬,其实Android对子线程中UI操作还提供了更好用的工具AsyncTask<Void, Intener, Boolen>要是有兴趣可以自己去了解一下。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值