我创建了一个应用程序,您按下“开始记录”,启动定期记录数据的服务。该按钮更改为显示“停止记录”。然后,您最小化应用程序并允许它在您开展业务时登录后台。但是,我必须实现“startForeground”,因为应用程序将关闭/被销毁,并且“startForeground”需要通知。
现在,当我运行应用程序并最小化,然后重新打开应用程序时,它很好,但如果我尝试通过通知重新打开它会重置屏幕,以便按钮现在再次显示“开始记录”单击,再次开始记录(接管当前服务)。该服务仍然记录,即使它说“开始记录”,所以它与屏幕有关,而不是保存我假设的按钮状态?
我试过这个,但无济于事:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("message", (String) but1.getText());
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logorcheck);
System.out.println("goes in oncreate");
if (savedInstanceState != null) {
but1.setText(savedInstanceState.getString("message"));
以下是几个片段:
LoggingService.java
NotificationManager nm = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = this.getResources();
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.arrow_up_float)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.arrow_down_float))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("App")
.setContentText("Service running OK");
Notification n = builder.getNotification();
// !
startForeground(100, n);
return Service.START_STICKY;
LogOrCheck.java
if (isClicked) {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Please press 'MINIMIZE' at the top to continue logging.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 10, 55);
toast.show();
System.out.println("Start logging");
but1.setText("Stop Logging");
but1.setTextColor(Color.RED);
// START SERVICE, DONE. (STOP IS BELOW).
startService(myIntent);
isClicked = false;
}
else if (!isClicked) {
System.out.println("Stop Logging");
but1.setText("Start Logging");
// STOP SERVICE, DONE.
stopService(myIntent);
but1.setTextColor(Color.BLACK);
isClicked = true;
}
感谢您的帮助,这似乎是一个简单的解决方案,我无法弄清楚如何做到这一点,尤其是使用notificationBuilder。对不起,留言很长!感谢。
答案 0 :(得分:0)
您可以做的最简单的事情是在LoggingService.java中创建静态布尔变量,例如isLogging,并在发生更改时在服务中相应地设置它。
在活动的onResume()中访问该变量并相应地设置按钮状态。