问题
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