2014-11-01 61 views
0

我有在随机时间发送一个通知,告诉我按一个按钮的服务。这个按钮需要快速按下,因为2分钟后它会再次消失。但在这2分钟后,我不知道如何查看按钮是否已被按下。获取数据到服务,而不需要重启

不知怎的,我需要从我的MainActivity像一个布尔值,我的服务,但我不相信我能做到这一点,意图,因为这样我会重新开始我的服务。

我一直在寻求一个答案,但没能找到解决的办法,任何帮助将非常感激!

我的服务:

`包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

IntentService停止运行onHandleIntent完成之后。为什么你想传递价值服务,目前不在后台工作? – 2014-11-01 14:48:04

+0

我想检查它在onHandleIntent方法。在我把线程睡觉之后。我将编辑帖子,使其更清晰。 – Solver 2014-11-01 14:56:47

回答

4

扩展服务(不IntentService)是你想做的事,因为它会保持乳宁直到你明确告诉它通过stopService停止(意图)的方法是什么,或者在服务在其自身上调用stopSelf()。 您可以通过startService(意向)方法将信号发送到服务。这将在服务第一次被调用时(服务未运行时)启动该服务,并且如果被调用后续时间,则仅向其发送数据。

确保产生一个新的线程,如果你是在做服务重等待处理,因为这将主线程(或取决于你想叫什么UI线程)上运行。你不想阻塞主线程。

相关问题