【问题标题】:How to keep an app running when screen goes off(latest android)屏幕熄灭时如何保持应用程序运行(最新的android)
【发布时间】:2019-06-24 11:18:10
【问题描述】:

我有一个应用程序(活动)。即使屏幕关闭,我也希望它继续运行,但旧的解决方案不起作用。据我了解,唯一的解决方案是提供服务。但是将 Activity 转换为服务容易吗?带有唤醒锁的方法不能再使用了,因为它已被弃用。

【问题讨论】:

  • 我会使用ForegroundService 以最大限度地兼容最新的 Android 版本。此外,最终用户可能需要为您的应用程序禁用电池优化。 “但是将 Activity 转换为服务很容易吗?” 这取决于您在 Activity 中的代码。应该不会太难吧。但无论如何都需要这样做。
  • 使用 JonScheduler 或 ForgroundService 或 JobIntentService

标签: android service


【解决方案1】:

如下创建前台服务。

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

public class ForegroundService extends Service {
    public static final String CHANNEL_ID = "ForegroundServiceChannel";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");
        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(input)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1001, notification);



        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }
}

不要忘记在清单中声明服务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多