java如何通过单击通知转到活动?
我正在开发一个向用户显示通知和通知声音的应用程序。用户可以通过“设置”活动上的两个开关按钮选择是否要查看它们。我想在用户单击通知时打开活动访问者。我写了下面的代码,但这没有发生,我应该写什么来代替
import 安卓.annotation.SuppressLint;
import 安卓.annotation.TargetApi;
import 安卓.app.Notification;
import 安卓.app.NotificationChannel;
import 安卓.app.NotificationManager;
import 安卓.app.PendingIntent;
import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.graphics.Color;
import 安卓.os.Build;
import 安卓.os.Bundle;
import 安卓.support.v4.app.NotificationCompat;
import 安卓.support.v4.app.NotificationManagerCompat;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.view.View;
import 安卓.widget.CompoundButton;
import 安卓.widget.Switch;
import java.util.Set;
import 安卓x.annotation.RequiresApi;
import static 安卓.app.PendingIntent.getActivity;
import static 安卓.content.Context.NOTIFICATION_SERVICE;
import static com.example.myevents.R.drawable.notification;
public class Settings extends AppCompatActivity {
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
NotificationManager manager;
Notification myNotication;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleswitch1.setChecked(false);
simpleswitch2.setChecked(false);
simpleswitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){{
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = "channel 1";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
Intent intent = new Intent(Settings.this, Visitor.class);
intent.putExtra("yourpackage.notifyId", notifyID);
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create a notification and set the notification channel.
Notification notification =
new NotificationCompat.Builder(Settings.this)
.setSmallIcon(R.drawable.notification)
.setContentTitle("TITLE")
.setContentText("TEXT")
.setChannelId(CHANNEL_ID).build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
}
# 1 楼答案
正如Android文档中所述,您需要设置当用户点击构建器上的通知时将触发的意图:
见:https://developer.android.com/training/notify-user/build-notification#click