Service初步
一、StartService启动Service的调用顺序
MainActivity.java
package com.example.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button start;
private Button stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.btnstart);
stop = (Button) findViewById(R.id.btnstop);
//创建启动Service的Intent,以及Intent属性
Intent intent = new Intent();
intent.setAction("com.example.test2.TEST_SERVICE1");
intent.setPackage(getPackageName());
//Intent intent = new Intent(this,TestService1.class);
//为两个按钮设置点击事件,分别是启动与停止service
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(intent);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(intent);
}
});
}
}
TestService1.java
package com.example.test2;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.security.Provider;
public class TestService1 extends Service {
private final String TAG = "TestService1";
public IBinder onBind(Intent intent) {
System.out.println("onBind方法被调用!");
Log.i(TAG, "onBind方法被调用!");
return null;
}
public void onCreate() {
System.out.println("onCreate方法被调用!");
Log.i(TAG, "onCreate方法被调用!");
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand方法被调用!");
Log.i(TAG, "onStartCommand方法被调用!");
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
System.out.println("onDestory方法被调用!");
Log.i(TAG, "onDestory方法被调用!");
super.onDestroy();
}
}
AndroidManifest.xml
<service android:name=".TestService1"
android:exported="true">
<intent-filter>
<action android:name="com.example.test2.TEST_SERVICE1"/>
</intent-filter>
</service>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:id="@+id/btnstart"
android:layout_gravity="center_horizontal"
android:text="开始服务" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnstop"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="停止服务" />
</LinearLayout>
二. BindService启动Service的顺序
MainActivity.java
package com.example.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button btnbind;
private Button btncancel;
private Button btnstatus;
//保持所启动的Service的IBinder对象,同时定义一个ServiceConnection对象
TestService2.MyBinder binder;
private ServiceConnection conn = new ServiceConnection() {
//Activity与Service断开连接时回调该方法
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("------Service DisConnected-------");
}
//Activity与Service连接成功时回调该方法
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("------Service Connected-------");
binder = (TestService2.MyBinder) service;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnbind = (Button) findViewById(R.id.btnbind);
btncancel = (Button) findViewById(R.id.btncancel);
btnstatus = (Button) findViewById(R.id.btnstatus);
Intent intent = new Intent();
intent.setAction("com.example.test2.TEST_SERVICE2");
intent.setPackage(getPackageName());
btnbind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//绑定service
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
btncancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//解除service绑定
unbindService(conn);
}
});
btnstatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Service的count的值为:"
+ binder.getCount(), Toast.LENGTH_SHORT).show();
}
});
}
}
TestService2.java
package com.example.test2;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class TestService2 extends Service {
private final String TAG = "TestService2";
private int count;
private boolean quit;
//定义onBinder方法所返回的对象
private MyBinder binder = new MyBinder();
public class MyBinder extends Binder {
public int getCount() {
return count;
}
}
//必须实现的方法,绑定改Service时回调该方法
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind方法被调用!");
return binder;
}
//Service被创建时回调
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate方法被调用!");
//创建一个线程动态地修改count的值
new Thread() {
public void run() {
while(!quit) {
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
count++;
}
};
}.start();
}
//Service断开连接时回调
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind方法被调用!");
return true;
}
//Service被关闭前回调
@Override
public void onDestroy() {
super.onDestroy();
this.quit = true;
Log.i(TAG, "onDestroyed方法被调用!");
}
@Override
public void onRebind(Intent intent) {
Log.i(TAG, "onRebind方法被调用!");
super.onRebind(intent);
}
}
AndroidManifest.xml
<service android:name=".TestService2"
android:exported="true">
<intent-filter>
<action android:name="com.example.test2.TEST_SERVICE2"/>
</intent-filter>
</service>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:id="@+id/btnbind"
android:layout_gravity="center_horizontal"
android:text="锁定Service" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btncancel"
android:layout_marginTop="50dp"
android:layout_gravity="center_horizontal"
android:text="解除锁定" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnstatus"
android:layout_marginTop="50dp"
android:layout_gravity="center_horizontal"
android:text="获取Service状态" />
</LinearLayout>
Service进阶
MainActivity.java
package com.example.test2;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent it1 = new Intent("com.example.test2.TEST_SERVICE3");
it1.setPackage(getPackageName());
Bundle b1 = new Bundle();
b1.putString("param", "s1");
it1.putExtras(b1);
Intent it2 = new Intent("com.example.test2.TEST_SERVICE3");
it2.setPackage(getPackageName());
Bundle b2 = new Bundle();
b2.putString("param", "s2");
it2.putExtras(b2);
Intent it3 = new Intent("com.example.test2.TEST_SERVICE3");
it3.setPackage(getPackageName());
Bundle b3 = new Bundle();
b3.putString("param", "s3");
it3.putExtras(b3);
//接着启动多次IntentService,每次启动,都会新建一个工作线程
//但始终只有一个IntentService实例
startService(it1);
startService(it2);
startService(it3);
}
}
TestService3.java
package com.example.test2;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class TestService3 extends IntentService {
private final String TAG = "TestService3";
//必须实现父类的构造方法
public TestService3() {
super("TestService3");
}
//必须重写的核心方法
@Override
protected void onHandleIntent(Intent intent) {
//Intent是从Activity发过来的,携带识别参数,根据参数不同执行不同的任务
String action = intent.getExtras().getString("param");
if(action.equals("s1"))Log.i(TAG,"启动service1");
else if(action.equals("s2"))Log.i(TAG,"启动service2");
else if(action.equals("s3"))Log.i(TAG,"启动service3");
//让服务休眠2秒
try{
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}
}
//重写其他方法,用于查看方法的调用顺序
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG,"onBind");
return super.onBind(intent);
}
@Override
public void onCreate() {
Log.i(TAG,"onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void setIntentRedelivery(boolean enabled) {
super.setIntentRedelivery(enabled);
Log.i(TAG,"setIntentRedelivery");
}
@Override
public void onDestroy() {
Log.i(TAG,"onDestroy");
super.onDestroy();
}
}
https://www.runoob.com/w3cnote/android-tutorial-service-1.html