我创建了一个应用程序,您可以在其中按“开始记录”,它会启动一个定期记录数据的服务。按钮更改为显示“停止记录”。然后,您将应用程序最小化并允许它在您开展业务时在后台登录。但是,我必须实现“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"));
以下是一些片段:
日志服务.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。对不起,很长的消息!谢谢。