如何在通知点击时调用非活动方法

Ezi*_*zio 4 notifications android android-intent android-pendingintent

我有一个Java类MyClass,其中包含一个称为的方法callMethod。当用户单击通知时,我想调用此方法

以下是我用于生成通知的代码

public class MainActivity extends AppCompatActivity {

    Button button;
    NotificationManager mNotifyMgr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        mNotifyMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MyClass.class), PendingIntent.FLAG_UPDATE_CURRENT);
                Notification notification =
                    new NotificationCompat.Builder(MainActivity.this)
                            .setContentTitle("Notification")
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setContentText("Downloaded")
                            .setContentIntent(pendingIntent)
                            .build();

                mNotifyMgr.notify(1,notification);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是执行 MyClass

public class MyClass {
    public void callMethod(){
        System.out.println("Notification clicked");
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮忙,我暂时陷入了困境

Dav*_*ser 5

您可以执行以下操作:

创建您PendingIntent要放入的内容时Notification

Intent notificationIntent = new Intent(MainActivity.this, MyClass.class);
notificationIntent.putExtra("fromNotification", true);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,
         PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)

现在,在MyClass.onCreate()

if (getIntent().hasExtra("fromNotification")) {
    callMethod();
}
Run Code Online (Sandbox Code Playgroud)

  • 单击“通知”会触发“意图”。就是这样。您需要一些东西来接收“意图”并执行您想要完成的操作。只有 Android 组件(“Activity”、“Service”或“BroadcastReceiver”)可以接收“Intent”。所以看起来你需要编写一个“Activity”、“Service”或“BroadcastReceiver”来接收“Intent”,然后调用“MyClass.callMethod()”。 (2认同)