Android 即时应用程序 : Foreground service

标签 android service android-instant-apps foreground-service

无法在 InstantApp 功能模块内使用前台服务。低于运行时安全异常。

java.lang.RuntimeException: Unable to start activity ComponentInfo{..XYZActivity}: java.lang.SecurityException: Method class android.app.ActivityManagerProxy.getServices not available to instant apps

Android 文档说,

Restricted features: Run on the device without users being aware. Foreground services are available. Instant apps can only be started through activities that support App Links, so services, content providers or broadcast receivers won't be able to start your app.

代码:

// Starting service
getAppContext().startService(new Intent(getAppContext(), FirebaseAuthService.class));


// Foreground service class
public class FirebaseAuthService extends Service {

    private static final String TAG = "FirebaseAuthService";
    private boolean isRunning = false;

    private String mUserId;
    private FirebaseAuth mAuth;

    @Override
    public void onCreate() {
        Log.d(TAG, "Service onCreate");

        startForeground();
        isRunning = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Service onStartCommand");

        new Thread(new Runnable() {
            @Override
            public void run() {
                myTask();
            }
        }).start();

        return Service.START_STICKY;
    }


    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "Service onBind");
        return null;
    }

    @Override
    public void onDestroy() {
        isRunning = false;
        Log.i(TAG, "Service onDestroy");
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, HomeActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.noti_logo)
                .setContentTitle("Title")
                .setContentText("Preparing...")
                .setContentIntent(pendingIntent).build();

        startForeground(1337, notification);
    }

    private void myTask() {
         // At end
        // Stop service once it finishes its task
        stopSelf();
    }
}

最佳答案

您的代码是正确的,但由于即时应用程序主管中的已知问题,前台服务目前无法运行。

关于Android 即时应用程序 : Foreground service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656049/

相关文章:

android - 单击链接时未启动 InstantApp

android - 无法运行 React-Native UIExplorer 示例项目

android - 我的应用程序安装在模拟器中,但它不会自动启动

android - Enemy Animator unity3d(2d) 返回未初始化的动画师

java - 获取 gdata 服务时出现 NoSuchMethod 错误

android - 如何使用具有功能模块结构的 Realm ?

android - 链接在某些设备上未作为即时应用程序打开

android - 为什么我不能将任何物体带出屏幕

ios - iOS 中的位置服务

c# - 在 ConfigureServices() 中添加 AddMvc() 服务两次是 Asp.Net Core 中的一个好习惯吗?