3

我有一個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); 
      } 
     }); 
    } 
} 

和下面的代碼是MyClass

public class MyClass { 
    public void callMethod(){ 
     System.out.println("Notification clicked"); 
    } 
} 

請幫助實現調用此方法,我陷入了這一段時間

+0

嘗試MyClass.callMethod(),它會工作,你可以有一個Util類來處理一些像這樣的泛型情況下 –

+0

@BabajideApata我在哪裏調用MyClass.callMethod()? – Ezio

+0

看着這條線PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,new Intent(MainActivity.this,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);它的作用是調用我的類,所以在這個類中,你可以調用你的方法,立即開始類 –

回答

1

你c烏爾德做這樣的事情:

在創建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); 

現在,在MyClass.onCreate()

if (getIntent().hasExtra("fromNotification")) { 
    callMethod(); 
} 
+0

MyClass不是一個活動類,MyClass中沒有onCreate()方法 – Ezio

+0

那麼,你不能這樣做:'PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,新的Intent(MainActivity.this,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT); '你發佈在你的代碼中! –

+0

點擊一個'Notification'觸發'Intent'。而已。你需要一些東西來接受'Intent'並執行你想要完成的動作。只有Android組件('Activity','Service'或'BroadcastReceiver')可以接收一個'Intent'。所以看起來你需要編寫一個'Activity','Service'或'BroadcastReceiver'來接收'Intent',然後調用'MyClass.callMethod()'。 –

1
@Override 
protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); 
    //notification callbacks here in activity 
    //Call method here from non activity class. 
    Classname.methodName(); 
}