博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android四大组件之Service示例
阅读量:4182 次
发布时间:2019-05-26

本文共 4107 字,大约阅读时间需要 13 分钟。

一个很简单的service示例,没有太多要讲解的。

有一个地方需要注意的是getRunningServices 已经被google标记为deprecated, 所以对于27(oreo)及以后的版本,如果要达到类似效果,可以使用isMyServiceRunning来代替isRunning(),如例子中所标记的那样。

我这里使用的是stopService来停止service,作为示例,其中也使用了stopSelf。

使用stopSelf(startId)的话,startID就是onStartCommand所传进来的那个。在service创建实例之后,每startService一次,这个startID就会+1。当stopService->onDestroy运行之后,不管有多少个Thread在运行,全部都会终止,如下图所示,

下面是本例全部的源码,

AndroidManifest.xml

activity_main.xml

MainActivity.java

package com.spacesoftwares.servicedemo;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity {    private Button mBtnStart;    private Button mBtnStop;    private Intent intent;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mBtnStart = findViewById(R.id.bt_start);        mBtnStop = findViewById(R.id.bt_stop);        setListener();    }    private void setListener(){        OnClick onClick = new OnClick();        mBtnStart.setOnClickListener(onClick);        mBtnStop.setOnClickListener(onClick);    }    private class  OnClick implements View.OnClickListener{        @Override        public void onClick(View view) {            int view_id = view.getId();            if(view_id == R.id.bt_start){                if(null == intent)                    intent = new Intent(MainActivity.this, MyService.class);                startService(intent);                MyService.isMyServiceRunning = true;            }else if(view_id == R.id.bt_stop){                if(null != intent){                    stopService(intent);                    MyService.isMyServiceRunning = false;                }            }        }    }}

MyService.java

package com.spacesoftwares.servicedemo;import android.app.Activity;import android.app.ActivityManager;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.IBinder;import android.util.Log;import java.util.ArrayList;public class MyService extends Service {    public static boolean isMyServiceRunning = false;    public MyService() {    }    private String TAG = "MyService";    @Override    public void onCreate() {        super.onCreate();        Log.i(TAG, "service created");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i(TAG, "service start command");        new Thread(new Runnable() {            @Override            public void run() {                int i = 0;                while(isRunning()) // or, you can use while(isMyServiceRunning) here instead of isRunning                {                    Log.i(TAG, "SERVICE IS RUNNING for " + String.valueOf(i++) + " seconds");                    try {                        Thread.sleep(1000);                    }catch (InterruptedException e){                        e.printStackTrace();                    }                }            }        }).start();        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        Log.i(TAG, "service destroyed");    }    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.        throw new UnsupportedOperationException("Not yet implemented");    }    // 请注意getRunningServices 已经标记为deprecated, 如果要达到类似效果,请使用isMyServiceRunning来代替isRunning()    public boolean isRunning(){        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);        ArrayList
runningService = (ArrayList
) activityManager.getRunningServices(40); for(int i=0; i

res->values->strings.xml

ServiceDemo
StartServiceDemo
StopServiceDemo

 

你可能感兴趣的文章
GC参数
查看>>
类装载器
查看>>
性能监控工具
查看>>
Java堆分析
查看>>
Spring Boot 开发环境搭建和项目启动
查看>>
SpringBoot搭建开发框架
查看>>
Leetcode Maximum XOR of Two Numbers in an Array
查看>>
Leetcode Remove Sub-Folders from the Filesystem
查看>>
Leetcode 332. Reconstruct Itinerary
查看>>
Leetcode 1238 Circular Permutation in Binary Representation 格雷码 gray code
查看>>
Leetcode 220. Contains Duplicate III 桶排序
查看>>
Leetcode Contain Virus
查看>>
Leetcode 785 Is Graph Bipartite? 图着色
查看>>
Leetcode 1278. Palindrome Partitioning III
查看>>
Leetcode 352. Data Stream as Disjoint Intervals
查看>>
Leetcode 1005. Maximize Sum Of Array After K Negations
查看>>
Leetcode 519. Random Flip Matrix
查看>>
Leetcode 839. Similar String Groups 并查集
查看>>
Leetcode 928. Minimize Malware Spread II
查看>>
Leetcode 336. Palindrome Pairs
查看>>