Android InstantApp: Foreground service

房东的猫 提交于 2019-12-21 05:57:29

问题


Unable to use foreground service inside InstantApp feature module. Getting below runtime security exception.

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

Android document says,

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.

Code:

// 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();
    }
}

回答1:


Your code is correct but Foreground services are not working at the moment due to a known issue in Instant Apps supervisor.



来源:https://stackoverflow.com/questions/44656049/android-instantapp-foreground-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!