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)
请帮忙,我暂时陷入了困境
您可以执行以下操作:
创建您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)
| 归档时间: |
|
| 查看次数: |
1863 次 |
| 最近记录: |