Android startet neu, wenn ich versuche, einen Service -Vordergrund zu setzen
-
25-10-2019 - |
Frage
Ich habe in meiner App ein seltsames Verhalten geschlagen: Wenn ich versuche, einen Service -Vordergrund zu setzen, startet das Mobilteil (HTC G1 + Cyanogen Mod) neu.
Es funktioniert, wenn ich nicht versuche, diesen Service in den Vordergrund zu stellen.
Hier ist der belastete Code:
Notification notification = new Notification(R.drawable.icon,
getText(R.string.ticker_text), System.currentTimeMillis());
startForeground(SERVICE_NOTIFICATION_ID, notification);
Log.v(TAG, "Control service foregrounded.");
Können Sie sehen, wo das Problem ist?
Wenn Sie mehr Daten benötigen, finden Sie das gesamte Projekt auf GitHub: https://github.com/rbochet/serval-video-discovery/tree/network-remote
Vielen Dank.
Lösung
Schauen Sie sich diese Android -API -Demo an hier. Beachten Sie, dass anstatt anzurufen startForeground()
, es ruft startForegroundCompat()
, eine Wrapper, die Ihre Anfrage abhängig von der neuen/alten Startforder -API bearbeitet.
void handleCommand(Intent intent) {
if (ACTION_FOREGROUND.equals(intent.getAction())) {
...
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label),
text, contentIntent);
startForegroundCompat(R.string.foreground_service_started, notification);
...
}
Hier ist startForegroundCompat()
:
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod(mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean.TRUE;
invokeMethod(mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
}