Android 从活动更新通知服务

Android 从活动更新通知服务,android,service,notifications,Android,Service,Notifications,我有一个通知服务,它在应用程序启动时启动 在主活动中有两个按钮,我想通过单击每个按钮来更新通知,例如,如果我触摸开始按钮,通知服务中的文本视图应该显示:您触摸了开始按钮和 我想从我的活动中更新通知 我该怎么做 这是我的密码: public class MainActivity extends AppCompatActivity { Button btn_start,btn_end; @Override protected void onCreate(Bundle savedInstanceS

我有一个通知服务,它在应用程序启动时启动 在主活动中有两个按钮,我想通过单击每个按钮来更新通知,例如,如果我触摸开始按钮,通知服务中的文本视图应该显示:您触摸了开始按钮和

我想从我的活动中更新通知 我该怎么做

这是我的密码:

public class MainActivity extends AppCompatActivity {

Button btn_start,btn_end;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    btn_start = (Button) findViewById(R.id.btn_start);
    btn_end = (Button) findViewById(R.id.btn_end);


    Intent serviceIntent = new Intent(MainActivity.this, NotificationService.class);
    serviceIntent.setAction("startforeground");
    startService(serviceIntent);


}
public class NotificationService extends Service {
Notification status;
public static int FOREGROUND_SERVICE = 101;

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    if (intent.getAction().equals("startforeground")) {
        showNotification();
    }

    return START_STICKY;
}

private void showNotification() {
    RemoteViews views = new RemoteViews(getPackageName(), R.layout.status_bar);
    RemoteViews bigViews = new RemoteViews(getPackageName(), R.layout.status_bar_expanded);
    status = new Notification.Builder(this).build();
    status.contentView = views;
    status.bigContentView = bigViews;
    status.flags = Notification.FLAG_ONGOING_EVENT;
    status.icon = R.drawable.ic_launcher;
    startForeground(FOREGROUND_SERVICE, status);
}

}

您必须使用与创建一个相同的方法,然后使用此方法使用您需要的任何内容对其进行更新:

NotificationManagerCompat.notify()

请阅读此处的详细信息:

创建和更新时需要使用相同的通知id