Service

部署运行你感兴趣的模型镜像

Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行与后天的一种服务程序。

启动方式:

第一种:

被开启的service通过其他组件调用startService()被创建。

这种service可以无线运行下去,必须调用stopSelf方法后者其他组件调用stopService()方法停止它。

当service被停止时,系统会销毁它。

第二种 

被绑定的service是当其他组件(一个客户)调用bindservice来创建的。

客户可以通过一个IBinder接口和service进行通信。

客户可以通过unbindservice()方法来关闭这种链接。

一个service可以同时和多个绑定,当多个客户都解除绑定之后,系统会销毁service。

生命周期:

service整体的生命时间是从onCreate()被调用开始,到onDestroy()方法返回为止。和activity一样,service在onCreate()中进行它的初始化工作,在onDestroy()中释放残留资源。

比如,一个音乐播放service可以在onCreate()中创建播放音乐的线程,在onDestroy()中停止这个线程。

onCreate()和onDestroy()会被所有的service调用,不论service是通过startService()还是bindService()建立。

public void intentServicedown(View view) {
        Intent intent1 = new Intent(this,MyIntentService.class);
        Bundle bundle = new Bundle();
        bundle.putString("url","http://vfx.mtime.cn/Video/2019/03/18/mp4/190318214226685784.mp4");
        bundle.putString("path","/sdcard/Movies/www.mp4");
        intent1.putExtras(bundle);
        startService(intent1);
    }
@Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        String url = extras.getString("url");
        String path = extras.getString("path");
        Log.i("---show", "onHandleIntent: "+url+path);
        try {
            URL url1 = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url1.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(2000);
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode()==200)
            {
                InputStream inputStream = httpURLConnection.getInputStream();
                int len = 0;
                byte[] buff = new byte[1024];
                FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
                int max = httpURLConnection.getContentLength();
                int progress = 0;
                while ((len = inputStream.read(buff))!= -1)
                {
                    fileOutputStream.write(buff,0,len);
                    progress+=len;
                    sendNotification(max,progress);
                }
                Intent intent1 = new Intent();
                intent1.setAction("com.bw.is");
                sendBroadcast(intent1);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendNotification(int max,int progress){
        RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.item);
        remoteViews.setProgressBar(R.id.pro,max,progress,false);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setCustomContentView(remoteViews);
        Notification notification = builder.build();
        startForeground(1,notification);
    }

POST

 public void postintentServicedown2(View view) {
        Intent intent1 = new Intent(this,MyIntentService3.class);
        Bundle bundle = new Bundle();
        bundle.putString("path","http://43.143.146.165:7777/foods/postFoods");
        bundle.putString("paren","pageSize=10&currentPage=1");
        intent1.putExtras(bundle);
        startService(intent1);
    }
@Override
    protected void onHandleIntent(Intent intent) {
        String path = intent.getExtras().getString("path");
        String paren = intent.getExtras().getString("paren");
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.setConnectTimeout(2000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(paren.getBytes());
            outputStream.flush();
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String str="";
                StringBuilder stringBuilder = new StringBuilder();
                while ((str=bufferedReader.readLine())!=null)
                {
                    stringBuilder.append(str);
                }
                Log.i("---bb", "onHandleIntent: "+stringBuilder.toString());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

您可能感兴趣的与本文相关的镜像

GPT-SoVITS

GPT-SoVITS

AI应用

GPT-SoVITS 是一个开源的文本到语音(TTS)和语音转换模型,它结合了 GPT 的生成能力和 SoVITS 的语音转换技术。该项目以其强大的声音克隆能力而闻名,仅需少量语音样本(如5秒)即可实现高质量的即时语音合成,也可通过更长的音频(如1分钟)进行微调以获得更逼真的效果

### Service生命周期和状态 ServiceAndroid系统中可以分为两种主要状态:启动状态和绑定状态。当一个Service被启动后,它会在后台长时间运行,即使启动它的组件已经被销毁,Service仍然可以继续运行[^2]。如果一个Service既被启动又被绑定,那么它会同时处于这两种状态。 ### Service生命周期方法 自定义的Service需要继承`Service`基类,并且通常需要重写一些生命周期方法来实现特定的功能: - `onCreate()`:当Service第一次创建时调用。如果Service已经存在,则不会调用此方法。 - `onStartCommand(Intent intent, int flags, int startId)`:当其他组件通过调用`startService()`方法请求启动Service时调用。在这个方法里可以处理长时间运行的操作。 - `onBind(Intent intent)`:当其他组件通过调用`bindService()`方法绑定到Service时调用。该方法返回一个`IBinder`接口,允许客户端与Service进行通信。 - `onUnbind(Intent intent)`:当所有绑定到Service的客户端都解绑后调用。 - `onDestroy()`:当Service不再使用并被销毁时调用。这是释放资源的好时机。 ### 启动状态下的Service 当一个Service通过调用`startService()`方法启动时,它进入启动状态。在这种状态下,Service独立于启动它的组件运行,直到它自己停止或被系统终止。要停止这样的Service,可以在Service内部调用`stopSelf()`方法,或者从外部组件调用`stopService()`方法[^1]。 ### 绑定状态下的Service 当组件通过调用`bindService()`方法绑定Service时,Service进入绑定状态。此时,组件可以通过`ServiceConnection`对象获取到Service提供的`IBinder`对象,从而与Service进行交互。绑定状态下的Service可以被多个组件绑定,只有当所有绑定的组件都解绑后,Service才会被销毁[^3]。 ### Service的声明 无论哪种类型的Service,都需要在`AndroidManifest.xml`文件中声明。声明格式如下: ```xml <service android:name=".Demo2Service" /> ``` 其中`.Demo2Service`是你的Service类名[^2]。 ### Service的绑定过程 为了与Service进行交互,组件需要创建一个`ServiceConnection`实例,并实现其`onServiceConnected()`和`onServiceDisconnected()`回调方法。例如: ```java private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 这里 IBinder类型的service 就是我们要绑定的那个service // 通过这个service,Activity就可以调用MyBindService.MyBinder中的方法 } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "onServiceDisconnected: "); } }; ``` 然后,组件可以通过调用`bindService()`方法来绑定Service,并在不需要时调用`unbindService()`方法来解绑[^5]。 ### Service的应用场景 Service非常适合用来执行那些不需要用户界面但需要长时间运行的任务。比如播放音乐、下载文件、处理网络请求等。此外,Service还可以与其他组件进行交互,包括跨进程通信(IPC)[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值