1
、在前一个应用程序基础上,采用绑定方式使用及管理服务。启动后应用程序
主界面如图
4
所示。
2、创建后台服务,基本功能同前;增加两个公共方法,分别用于加快、减慢图
标更新速率,加快时将更新间隔缩短至原来的二分之一,减慢时将更新间隔加长
至二倍。
3
、点击界面上的“服务绑定”按钮,绑定服务。在服务绑定后,通知栏上出现
图标并按照预设间隔交替更新;点击“加速”按钮后,更新速度加快;点击“减
速”按钮后,更新速度减慢;点击“取消绑定”按钮可以解除服务的绑定关系,
在取消绑定后,服务停止,通知栏图标被清除。
4.2在4.1的基础上完成的,所以这里直接给代码吧。。。。
布局文件很简单,就是四个按钮:
<?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:orientation="vertical"
android:layout_height="match_parent"
app:layout_goneMarginTop="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定服务"/>
<Button
android:id="@+id/button2"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解除服务"/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加速"/>
<Button
android:id="@+id/button4"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="减速"/>
</LinearLayout>
主函数代码如下:
package com.example.myapplication4_2;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn1, btn2, btn3, btn4;
private Intent serviceIntent;//异步服务
private MyService.localBinder mService;
private boolean isBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = (MyService.localBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "chat"; //保证全局唯一性下可以随意更改
String channelName = "狗子"; //渠道名称是给用户看的,需要能够表达清楚这个渠道的用途
int importance = NotificationManager.IMPORTANCE_HIGH;
createNotificationChannel(channelId, channelName, importance);
}
btn1 = findViewById(R.id.button1);
btn2 = findViewById(R.id.button2);
btn3 = findViewById(R.id.button3);
btn4 = findViewById(R.id.button4);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isBound){
serviceIntent = new Intent(MainActivity.this,MyService.class);
bindService(serviceIntent,mConnection, Context.BIND_AUTO_CREATE);
isBound = true;
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isBound){
unbindService(mConnection);
isBound = false;
mService = null;
}
}
});
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mService != null)
mService.accelerate();
else{
Toast.makeText(MainActivity.this,"服务没有绑定",Toast.LENGTH_LONG).show();
}
}
});
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mService != null)
mService.slow();
else{
Toast.makeText(MainActivity.this,"服务没有绑定",Toast.LENGTH_LONG).show();
}
}
});
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
package com.example.myapplication4_2;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
public class MyService extends Service {
private final IBinder mBinder = new localBinder();
private NotificationCompat.Builder builder;
private NotificationManager nm;
private boolean quit = false;
private static final String TAG = "MyService";
private int interval = 500;
public MyService() {
}
public class localBinder extends Binder {
public void accelerate() {
interval /= 2;
}
public void slow() {
interval *= 2;
}
}
public void notifyMe(){
nm=(NotificationManager)getApplicationContext().getSystemService( Context.NOTIFICATION_SERVICE );
builder=new NotificationCompat.Builder(getApplicationContext(),"chat");
builder.setContentTitle("狗子")
.setContentText(getApplicationContext() .getString(R.string.app_name))
.setSmallIcon(R.drawable.leftted)
.setSound(null)
.setAutoCancel(true);
Notification notification=builder.build();
nm.notify(1,notification);
}
@Override
public void onCreate() {
super.onCreate();
notifyMe();
workThread = new Thread(backgroundWork);
workThread.start();
Log.e(TAG, "onCreate: ");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!workThread.isAlive()) {
workThread.start();
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
this.quit = true;
nm.cancel(1);
}
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind: ");
return mBinder;
}
private Thread workThread;
private Runnable backgroundWork = new Runnable() {
@Override
public void run() {
boolean flag = true;
while (!quit){
try {
if (flag){
builder.setSmallIcon(R.drawable.arrowright);
nm.notify(1,builder.build());
flag = false;
}else{
builder.setSmallIcon(R.drawable.leftted);
nm.notify(1,builder.build());
flag = true;
}
Thread.sleep(interval);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
};
}
效果图如下: