会显示通知,但单击通知无法跳转到页面



目标:点击按钮跳出通知,用户可以从通知跳转到另一个页面

会显示通知,但单击通知无法跳转到页面。

我认为PendingIntent是错误的。

如何修复?

public class MainActivity extends AppCompatActivity {
private String CHANNEL_ID = "Coder";
NotificationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "DemoCode", NotificationManager.IMPORTANCE_DEFAULT);
manager = getSystemService(NotificationManager.class);
assert manager != null;
manager.createNotificationChannel(channel);
}

Button btDefault,btCustom;
btDefault = findViewById(R.id.button_DefaultNotification);
btCustom = findViewById(R.id.button_CustomNotification);
btDefault.setOnClickListener(onDefaultClick);
}

private final View.OnClickListener onDefaultClick = new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent nextIntent = new Intent(MainActivity.this, secondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, nextIntent,PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
builder.setContentTitle("Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.ic_baseline_accessible_forward_24);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
manager.notify(1, builder.build());
}

检查这是否适用。如android api 中所述

您应该考虑用户期望的导航体验。因此,为了使用pendingIntentNotification进行最佳导航,您应该执行以下操作:

1.首先在AndroidManifest.xml:中定义应用程序的层次结构

<activity
android:name=".MainActivity"
... >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- MainActivity is the parent for SecondActivity -->
<activity
android:name=".SecondActivity"
android:parentActivityName=".MainActivity" />
...
</activity>

现在,您告诉android,当单击通知时,当用户向上导航时,SecondActivity将是MainActivity的子代。

2.使用TaskStackBuilder:创建PendingIntent

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pendingIntent = TaskStackBuilder.create(MainActivity.this)
.addNextIntentWithParentStack(intent)
.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)

然后,您可以将我们创建的PendingIntent设置为通知。现在,如果用户触摸了通知,安卓系统会将他导航到SecondActivity,同时将MainActivity放在后堆栈中。

相关内容

  • 没有找到相关文章

最新更新