Android KitKat在应用程序进入后台后不显示Toast
我正在从我的Android测试应用程序运行一个服务,它需要显示toast from counter值,该值在服务中不断增加 这是一个很好的开始,并展示了祝酒词。但是,一旦我按下back/home(返回/主页)按钮将应用程序置于后台,祝酒词就不再显示。当我再次将应用程序带到前台时,祝酒词再次开始可见 这个问题发生在Kitkat。但在果冻豆及以下,其工作良好 这是我的清单文件Android KitKat在应用程序进入后台后不显示Toast,android,android-4.4-kitkat,toast,Android,Android 4.4 Kitkat,Toast,我正在从我的Android测试应用程序运行一个服务,它需要显示toast from counter值,该值在服务中不断增加 这是一个很好的开始,并展示了祝酒词。但是,一旦我按下back/home(返回/主页)按钮将应用程序置于后台,祝酒词就不再显示。当我再次将应用程序带到前台时,祝酒词再次开始可见 这个问题发生在Kitkat。但在果冻豆及以下,其工作良好 这是我的清单文件 <?xml version="1.0" encoding="utf-8"?> <manifest xmln
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rtrgroup.mysms"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="19"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true">
<activity
android:name="com.rtrgroup.mysms.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.rtrgroup.mysms.MyService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
这是我的服务代码MyService.java:
package com.rtrgroup.mysms;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.*;
import android.widget.Toast;
public class MyService extends Service {
Handler handler;
int count = 0;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
handler.postDelayed(test, 1000);
return START_NOT_STICKY;
}
Runnable test = new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "TOAST count = " + String.valueOf(count), Toast.LENGTH_SHORT).show();
count++;
handler.postDelayed(test, 5000);
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
那么,如何使toast始终可见,即使应用程序在后台并且服务正在运行?请解释。如果要检测用户何时将应用程序置于后台,请覆盖此方法
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:
// do your magic here
break;
}
}
检查文档
此外,您还可以在“前台”模式下启动此项检查的服务
或者,您可以显示通知,而不是祝酒。为什么不使用通知?这是做这件事的正确方法。。
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:
// do your magic here
break;
}
}