首页 > 解决方案 > 从活动更新通知服务

问题描述

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

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

这是我的代码:

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);
}

}

标签: androidservicenotifications

解决方案


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

NotificationManagerCompat.notify()

在此处阅读详细信息: https ://developer.android.com/training/notify-user/build-notification

您需要在创建和更新时使用相同的通知 ID。


推荐阅读