0

我在偵聽器服務中有NotificationManager,我想在按下肯定按鈕時啓動服務。到目前爲止,這不起作用,我懷疑它可能與上下文有關。NotificationManager未啓動服務

//NotificationManager in GCM listener service 

public class MyGcmListenerService extends GcmListenerService 
{ 

    private static final String TAG = "MyGcmListenerService"; 
    private NotificationManager notificationManager; 


    @Override 
    public void onCreate() 
    { 
     notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

    } 

    @Override 
    public void onMessageReceived(String from, Bundle data) 
    { 
     Log.i(TAG, "IP : " + (String) data.get("ip")); 

     Intent acceptCryptoService = new Intent(this, CryptoService.class); 
     acceptCryptoService.putExtra(StringResources.CRYPTO_ACTION, true); 
     PendingIntent acceptPendingIntent = PendingIntent.getService(this, 0, acceptCryptoService, 0); 

     Intent declineCryptoService = new Intent(this, CryptoService.class); 
     declineCryptoService.putExtra(StringResources.CRYPTO_ACTION, false); 
     PendingIntent declinePendingIntent = PendingIntent.getService(this, 0, declineCryptoService, 0); 

     NotificationCompat.Action acceptAction = new NotificationCompat.Action 
       .Builder(android.R.drawable.arrow_up_float, "Grant", acceptPendingIntent).build(); 

     NotificationCompat.Action declineAction = new NotificationCompat.Action 
       .Builder(android.R.drawable.arrow_down_float, "Decline", declinePendingIntent).build(); 

     NotificationCompat.Builder notification = new NotificationCompat.Builder(this) 
       .setContentTitle("New Password Request From " + (String) data.get("ip")) 
       .addAction(acceptAction) 
       .addAction(declineAction) 
       .setSmallIcon(android.R.drawable.arrow_up_float) 
       .setSmallIcon(android.R.drawable.arrow_down_float); 

     notificationManager.notify(1, notification.build()); 
    } 

這是密碼服務

public class CryptoService extends Service 
{ 
    String TAG = "CryptoService"; 

    @Override 
    public void onCreate() 
    { 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
     boolean acceptCrypto = intent.getBooleanExtra(StringResources.CRYPTO_ACTION, false); 
     Log.i(TAG, "accept crypt: " + acceptCrypto); //Not getting called 
     return Service.START_NOT_STICKY; 
    } 


    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) 
    { 
     return null; 
    } 

    @Override 
    public void onDestroy() 
    { 

    } 

} 

我在MainActivity開始CryptoService。所以後續的StartService調用應該調用onStartCommand。但是,這不是發生。

回答

0

您缺少在acceptCryptoService和declineCryptoService意圖中設置操作。

acceptPendingIntent.setAction(StringResources.CRYPTO_ACTION); 
declineCryptoService.setAction(StringResources.CRYPTO_ACTION); 
+0

操作不用於明確的'意圖'。另外,看起來'CRYPTO_ACTION'是'Intent'額外的關鍵,而不是'Intent'動作。 –