我正在尝试生成一直保持活动的服务,即使用户关闭了应用程序也是如此。根据这些线程
Keep location service alive when the app is closed
Android Service Stops When App Is Closed
Android: keep Service running when app is killed
这可以使用IntentServices或Service.START_STICKY
来完成然而,我尝试了两种类型的服务而没有成功。换句话说,当用户关闭应用程序时,我的服务就会被杀死。有人可以指出这是否可以做到以及如何做?这是我尝试过的没有成功的事情:
使用IntentService:
public class MyIntentService extends IntentService {
private final int mPollingTimeMS = 500;
private int mInitializationPollingCount = 0;
private Thread mPollThread;
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
mPollThread = new Thread() {
public void run() {
while (true) {
try {
Log.e(Constants.Engine.LOGGER_TAG_DEV,
"SDK Service Running: " +
mInitializationPollingCount * mPollingTimeMS +
"ms have elapsed");
mInitializationPollingCount++;
sleep(mPollingTimeMS);
} catch (Exception e) {
StackTraceElement trace = new Exception().getStackTrace()[0];
Logger.e(Constants.Engine.LOGGER_TAG_APP, "[Exception:" + e.toString() + "]" +
trace.getClassName() + "->" + trace.getMethodName() + ":" + trace.getLineNumber());
}
}
}
};
mPollThread.start();
}
}
和服务:
public class MyService extends Service {
public MyService() {
}
private final int mPollingTimeMS = 500;
private int mInitializationPollingCount = 0;
private Thread mPollThread;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPollThread = new Thread() {
public void run() {
while (true) {
try {
Log.e(Constants.Engine.LOGGER_TAG_DEV,
"SDK Service Running: " +
mInitializationPollingCount * mPollingTimeMS +
"ms have elapsed");
mInitializationPollingCount++;
sleep(mPollingTimeMS);
} catch (Exception e) {
StackTraceElement trace = new Exception().getStackTrace()[0];
Logger.e(Constants.Engine.LOGGER_TAG_APP, "[Exception:" + e.toString() + "]" +
trace.getClassName() + "->" + trace.getMethodName() + ":" + trace.getLineNumber());
}
}
}
};
mPollThread.start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// I tried to return null here, but this
// service gets killed no matter what.
return null;
}
}
这是清单:
<service
android:name=".mycompany.MyService"
android:enabled="true"
android:exported="true"
android:process=":process1">
</service>
<service
android:name=".mycompany.MyIntentService"
android:process=":process2"
android:exported="false">
</service>
我将补充说,我正在关闭测试应用程序,而不是使用关闭按钮,而是使用Android OS应用程序管理器。见下图
最后,司机活动(那里不多)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent1 = new Intent(getBaseContext(), MyService.class);
startService(intent1);
Intent intent2 = new Intent(getBaseContext(), MyIntentService.class);
startService(intent2);
}
}
我还尝试添加通知并将其作为前台服务,但仍然是相同的。关闭应用程序的那一刻,一切都被杀死了。这就是我添加的内容:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
...etc..
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
int iconId = R.mipmap.ic_launcher;
int uniqueCode = new Random().nextInt(Integer.MAX_VALUE);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(iconId)
.setContentText("Context Text")
.setContentIntent(pendingIntent).build();
startForeground(uniqueCode, notification);
}
答案 0 :(得分:13)
以下是我使用的前台服务示例,它可以正常运行,当应用关闭时它仍处于活动状态。当然,它也必须启动,对于该任务,应用程序必须乍一看,或者必须设置启动事件的接收器,但这是另一个故事。
public class MyService extends Service {
static final int NOTIFICATION_ID = 543;
public static boolean isServiceRunning = false;
@Override
public void onCreate() {
super.onCreate();
startServiceWithNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
startServiceWithNotification();
}
else stopMyService();
return START_STICKY;
}
// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
isServiceRunning = false;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}
void startServiceWithNotification() {
if (isServiceRunning) return;
isServiceRunning = true;
Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
notificationIntent.setAction(C.ACTION_MAIN); // A string containing the action name
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.my_string))
.setSmallIcon(R.drawable.my_icon)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(contentPendingIntent)
.setOngoing(true)
// .setDeleteIntent(contentPendingIntent) // if needed
.build();
notification.flags = notification.flags | Notification.FLAG_NO_CLEAR; // NO_CLEAR makes the notification stay when the user performs a "delete all" command
startForeground(NOTIFICATION_ID, notification);
}
void stopMyService() {
stopForeground(true);
stopSelf();
isServiceRunning = false;
}
}
然后我用
运行它 Intent startIntent = new Intent(getApplicationContext(), MyService.class);
startIntent.setAction(C.ACTION_START_SERVICE);
startService(startIntent);
请注意用作Actions的两个常量,这些是必须以包名开头的字符串。
答案 1 :(得分:5)
使用IntentService
可能不是最佳方法。默认情况下,IntentService
在onHandleIntent(Intent)
返回后停止,并且没有任何工作要做(即请求队列为空)。这在official docs of IntentService:
当处理完所有请求后,IntentService会自行停止,因此您不应该调用stopSelf()。
在你的情况下,onHandleIntent(Intent)
会创建一个线程,但会立即返回,这会让它自行停止。
只要您在单独的进程上运行该服务,就应该使用前台模式中的常规Service
。为此,您需要:
onStartCommand()
返回START_STICKY
。onCreate()
。android:process=":something"
)。根据帖子,您似乎已经单独尝试了其中一些步骤,但从未同时尝试过所有这些步骤。
答案 2 :(得分:0)
您只需在活动中的onStop()方法中调用您的服务即可。 即使用户停止了应用程序,服务仍将继续运行。
答案 3 :(得分:0)
如果以上回答中的无有效,则可能是制造商特定的问题。例如,某些 MI 手机会在用户通过任务管理器终止应用程序时终止前台服务。
我建议您在虚拟设备上测试该应用程序,以便您检查是否是这种问题。
希望有帮助!
答案 4 :(得分:0)