android - 从活动更新通知服务
问题描述
我有一个通知服务,它在应用程序启动时启动,并且主要活动中有 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);
}
}
解决方案
您必须使用与创建相同的方式,然后使用此方法使用您需要的任何内容对其进行更新:
NotificationManagerCompat.notify()
在此处阅读详细信息: https ://developer.android.com/training/notify-user/build-notification
您需要在创建和更新时使用相同的通知 ID。
推荐阅读
- javascript - javascript 中的 N+1 未按预期工作
- python - 类中的Python二叉树属性问题
- python - 在 ubuntu 系统上执行 python 脚本后没有释放 RAM 内存
- webstorm - Deno 的路径不正确 WebStorm
- netsuite - 下面的代码在控制台中运行,但是在套件脚本 2.0 中不起作用。脚本给出错误“无效的量词?” 在第 7 行
- javascript - 我想获取对象并在课堂上使用它。它在 then 语句中运行良好,但之后它会寻找它不想出现
- angular - TEMP_DATA 值必须相同但它正在改变
- botframework - 是否可以在我的聊天机器人的团队应用程序中禁用输入
- api - 有没有办法在使用 twitter 流时请求更大的参数列表?
- chart.js - Blazor 服务器端 Chartjs