【发布时间】:2019-09-05 18:59:34
【问题描述】:
我尝试制作一个 Android 服务。
所以我使用了一个服务扩展类。
public class DelayedToast extends IntentService {
private final static boolean Debug = true;
private final static String TAG = "ALT";
public DelayedToast() {
super("DelayedToast");
}
@Override
protected void onHandleIntent(Intent intent) {
final int delay = intent.getIntExtra("delay", -1);
if (Debug) Log.i(TAG, "DelayedToast:onHandleIntent delay: " + delay);
if (delay > 0) {
SystemClock.sleep(delay * 1000);
if (Debug) Log.i(TAG, "Wake up !! ");
// Intent broadcastIntent = new Intent();
Intent broadcastIntent = new Intent(getApplicationContext(), Receiver.class); // Need to be explicit for Broadcast : https://stackoverflow.com/questions/55610977/why-a-static-broadcastreceiver-not-working
broadcastIntent.setAction(getString(R.string.intent_action));
broadcastIntent.putExtra("delay", delay);
sendBroadcast(broadcastIntent);
if (Debug) Log.i(TAG, "sendBroadcast");
showToast("toast Service: " + delay);
}
}
// https://stackoverflow.com/a/34832674
protected void showToast(final String msg) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (Debug) Log.i(TAG, msg);
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
}
我已经在 Manifest 上声明了这一点。
<service
android:name=".DelayedToast"
android:enabled="true"
android:exported="true"
android:process=":DelayedToast" />
我使用按钮启动服务:
public void onClickStart(View v) {
EditText editText = findViewById(R.id.delay);
final String str_delay = editText.getText().toString();
if (Debug) Log.i(TAG, "MainActivity:onClickStart str: " + str_delay);
if (!str_delay.isEmpty()) {
final int delay = Integer.parseInt(str_delay);
if (Debug) Log.i(TAG, "Q1_MainActivity:onClickStart delay: " + delay);
if (delay > 0) {
Intent intent = new Intent(this, DelayedToast.class);
intent.putExtra("delay", delay);
startService(intent);
}
}
}
C:\Users\dark_vidor>adb shell "ps | grep tp08" // 这里 应用程序没有启动
C:\Users\dark_vidor>adb shell "ps | grep tp08" // 应用程序正在运行
u0_a246 20032 3012 2569888 132044 0 0 S test.tp08
C:\Users\dark_vidor>adb shell "ps | grep tp08" // 我是 启动“延迟吐司”(服务)
u0_a246 20032 3012 2573316 135404 0 0 S test.tp08
u0_a246 20090 3012 2324660 79876 0 0 S test.tp08:DelayedToast
C:\Users\dark_vidor>adb shell "ps | grep tp08" // 我 有接收者一个广播互联网
u0_a246 20032 3012 2580964 137252 0 0 S test.tp08
u0_a246 20090 3012 2326168 96376 0 0 S test.tp08:DelayedToast
u0_a246 20127 3012 2325228 99696 0 0 S test.tp08:接收器
C:\Users\dark_vidor>adb shell "ps | grep tp08" // 这里 我已经关闭了应用程序,服务也被杀死了
C:\Users\dark_vidor>
我遵循了一些教程,但我不明白我忘记了什么以及为什么我的服务在我退出我的应用程序后被杀死,而他应该留下直到我停止它 我正在使用三星 A8,我的应用程序是 Java,SDK min 24
你有什么办法解决这个问题吗?
【问题讨论】: