Android四大组件之Service示例
一个很简单的service示例,没有太多要讲解的。
有一个地方需要注意的是getRunningServices 已经被google标记为deprecated, 所以对于27(oreo)及以后的版本,如果要达到类似效果,可以使用isMyServiceRunning来代替isRunning(),如例子中所标记的那样。
我这里使用的是stopService来停止service,作为示例,其中也使用了stopSelf。
使用stopSelf(startId)的话,startID就是onStartCommand所传进来的那个。在service创建实例之后,每startService一次,这个startID就会+1。当stopService->onDestroy运行之后,不管有多少个Thread在运行,全部都会终止,如下图所示,
下面是本例全部的源码,
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spacesoftwares.servicedemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/bt_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/start_service"/>
<Button
android:id="@+id/bt_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/stop_service"/>
</LinearLayout>
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<ActivityManager.RunningServiceInfo> runningService =
(ArrayList<ActivityManager.RunningServiceInfo>) activityManager.getRunningServices(40);
for(int i=0; i<runningService.size();i++){
String name = runningService.get(i).service.getClassName().toString();
if(name.equals("com.spacesoftwares.servicedemo.MyService")){
return true;
}
}
return false;
}
}
res->values->strings.xml
<resources>
<string name="app_name">ServiceDemo</string>
<string name="start_service">StartServiceDemo</string>
<string name="stop_service">StopServiceDemo</string>
</resources>