前台服务和后台服务的最大区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。
先来看下程序的效果图:
现在来看下代码:
服务类的代码如下:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("前台服务")
.setContentText("正在运行中")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.build();
// 调用startForeground()方法会让MyService变成一个前台服务,并在状态栏显示出来
startForeground(1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}
}
可以看到,我只是在onCreate()方法中加了创建通知的代码,只不过最后是调用了startForeground()方法将通知显示出来。
MainActivity的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/btn_start_service"
android:text="启动服务"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_stop_service"
android:text="停止服务"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity的java代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_startService;
private Button btn_stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_startService = findViewById(R.id.btn_start_service);
btn_stopService = findViewById(R.id.btn_stop_service);
btn_startService.setOnClickListener(this);
btn_stopService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 开启服务
break;
case R.id.btn_stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务
break;
}
}
}