Android四大组件之Service示例

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

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

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

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

Android四大组件之Service示例_第1张图片

下面是本例全部的源码,

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

 

你可能感兴趣的:(android,debug,一步步学习Android)