我有一个随机发送通知的服务,告诉我按下按钮。需要快速按下此按钮,因为2分钟后它会再次消失。但是在那2分钟之后,我不知道如何按下或没有按下按钮。
不知怎的,我需要从我的MainActivity获得类似布尔值的东西到我的服务,但我不相信我能用意图做到这一点,因为那样我就会重启我的服务。
我已经找到了答案,但无法找到解决方案,我们将非常感谢您的帮助!
我的服务:
`package com.example.pressme_alpha;
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);
}
} `
答案 0 :(得分:4)
扩展服务(不是IntentService)是你想要做的事情,因为它会一直运行,直到你明确告诉它通过stopService(Intent)方法停止或者服务调用它自己的stopSelf()。 您可以通过startService(Intent)方法向服务发送信号。这将在第一次调用它时启动服务(当服务未运行时),如果后续调用,则只向其发送数据。
如果你在服务中进行大量处理,请确保生成一个新线程,因为这将在主线程(或UI线程,取决于你想要调用它)上运行。你不想阻止主线程。