Android 在不重新启动服务的情况下将数据获取到服务
我有一个服务,在随机时间发送通知,告诉我按下一个按钮。需要快速按下此按钮,因为2分钟后它将再次消失。但是在那两分钟之后,我不知道我怎么能看到按钮是否被按下 不知何故,我需要从我的MainActivity到我的服务中获得类似布尔值的东西,但我不相信我可以有目的地这样做,因为这样我就会重新启动我的服务 我一直在寻找答案,但没有找到解决方案,任何帮助都将不胜感激 我的服务: `package com.example.pressme_alpha } `扩展服务(而非IntentService)是您想要做的事情,因为它将一直运行,直到您通过stopService(Intent)方法明确告诉它停止,或者如果服务本身调用stopSelf()。 您可以通过startService(Intent)方法向服务发送信号。这将在第一次调用服务时(当服务未运行时)启动该服务,并在以后调用时向其发送数据 如果您在服务中执行繁重的处理,请确保生成新线程,因为这将在主线程(或UI线程,具体取决于您要调用它的名称)上运行。您不想阻止主线程。扩展服务(不是IntentService)是您想要做的,因为它将一直运行,直到您通过stopService(Intent)方法明确告诉它停止,或者如果服务在其自身上调用stopSelf()。 您可以通过startService(Intent)方法向服务发送信号。这将在第一次调用服务时(当服务未运行时)启动该服务,并在以后调用时向其发送数据Android 在不重新启动服务的情况下将数据获取到服务,android,android-intent,service,Android,Android Intent,Service,我有一个服务,在随机时间发送通知,告诉我按下一个按钮。需要快速按下此按钮,因为2分钟后它将再次消失。但是在那两分钟之后,我不知道我怎么能看到按钮是否被按下 不知何故,我需要从我的MainActivity到我的服务中获得类似布尔值的东西,但我不相信我可以有目的地这样做,因为这样我就会重新启动我的服务 我一直在寻找答案,但没有找到解决方案,任何帮助都将不胜感激 我的服务: `package com.example.pressme_alpha } `扩展服务(而非IntentService)是您想要做
如果您在服务中执行繁重的处理,请确保生成新线程,因为这将在主线程(或UI线程,具体取决于您要调用它的名称)上运行。您不希望阻止主线程。IntentService在onHandleIntent完成后立即停止运行。为什么要将值传递给当前不在后台工作的服务?我想在onHandleIntent方法中检查它。就在我睡觉后。我将编辑帖子,使其更清晰。OnHandleContent完成后,IntentService立即停止运行。为什么要将值传递给当前不在后台工作的服务?我想在onHandleIntent方法中检查它。就在我睡觉后。我会编辑这篇文章,让它更清晰。
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class ButtonAlarmService extends IntentService{
private static final String INTENT_NAME = "notification";
private NotificationManager nm;
private Notification notification;
public ButtonAlarmService() {
super("Imma button!");
}
@SuppressWarnings("static-access")
@Override
protected void onHandleIntent(Intent intent) {
nm = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent newIntent = new Intent(this.getApplicationContext(), MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.putExtra(INTENT_NAME, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
notification = notifBuilder.setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Press me - alpha").setContentText("You need to press the button!").build();
notifBuilder.setAutoCancel(true);
nm.notify(0, notification);
startActivity(newIntent);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Check if the button is pressed here
ButtonAlarmReceiver.completeWakefulIntent(intent);
}