使用前台服务

前台服务和后台服务的最大区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。

先来看下程序的效果图:
在这里插入图片描述
现在来看下代码:

服务类的代码如下:

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;

        }

    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当我们需要在Android应用中执行一些长时间运行的任务时,可以使用前台服务前台服务是一种在通知栏中显示持续运行通知的服务,以提醒用户应用正在后台执行任务。 以下是一个简单的Android前台服务的例子: 1. 创建一个Service类,继承自android.app.Service,并重写onCreate()、onStartCommand()和onDestroy()方法。 ```java public class MyForegroundService extends Service { private static final int NOTIFICATION_ID = 1; private static final String CHANNEL_ID = "ForegroundServiceChannel"; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { createNotificationChannel(); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Foreground Service") .setContentText("Running...") .setSmallIcon(R.drawable.ic_notification) .setContentIntent(pendingIntent) .build(); startForeground(NOTIFICATION_ID, notification); // 执行长时间运行的任务 return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); stopForeground(true); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT ); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } } } ``` 2. 在AndroidManifest.xml文件中注册前台服务。 ```xml <service android:name=".MyForegroundService" android:enabled="true" android:exported="false" /> ``` 3. 在需要启动前台服务的地方,使用以下代码启动服务。 ```java Intent serviceIntent = new Intent(this, MyForegroundService.class); ContextCompat.startForegroundService(this, serviceIntent); ``` 这样,当启动前台服务时,会在通知栏中显示一个持续运行的通知,告知用户应用正在后台执行任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值