2011-06-21 17 views
21

通知からサービスを開始することは可能です。 アクティビティを開始する通常の方法は完全に動作していますが、実際にアプリを起動する前にデータの事前確認が必要です。通知からサービスを開始

通知の意図に有効なサービスを含めてテストしましたが、何も起こりません。

答えて

65

通知からサービスを開始することは可能です。

pendingIntent.getActivityの代わりにPendingIntent.getServiceを使用する必要があります。 BroadCastReceiverとティップのための

Intent notificationIntent = new Intent(mContext, HandleNotificationClickService.class); 
PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, notificationIntent, 0); 

Notification notification = new Notification(icon, tickerText,System.currentTimeMillis()); 
notification.setLatestEventInfo(mContext,contentTitle , contentText, pendingIntent); 
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT; 

NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); 

notificationManager.notify(CALLER_ID_NOTIFICATION_ID, notification); 
+3

それは間違いなく受け入れられた答えでなければなりません! "pendingIntent.getActivityの代わりにPendingIntent.getService"が正しい方法です! – Christian

+0

@ notification通知でpendingIntentを使用してサービスを一時停止する方法。サービスクラスのstopメソッドを呼び出す必要があります。 –

+0

上記のようなサービスを起動すると、ランタイム例外が発生します。Thread [<1> main(Suspended(例外RuntimeException)) - - ActivityThread.handleCreateService(ActivityThread $ CreateServiceData)行:2561 - ActivityThread .access $ 1600(ActivityThread、ActivityThread $ CreateServiceData)行:141 – samo

5

ブロードキャスト受信者を作成し、通知からメッセージを受信して​​サービスを開始します。

+0

感謝。それにすべての小切手を入れることができましたので、もうサービスは必要ありません。 – AlexVogel

1
private void createNotification(String message) 

{ 

    Intent intent = new Intent(this, Yourservice.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    PendingIntent pendingIntent = PendingIntent.getService(this, 0 /* Request code */, intent, 
     0); 

    NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
     .setSmallIcon(R.drawable.icond) 
     .setContentTitle("Start Launcher") 
     .setContentText(message) 
     .setAutoCancel(true) 
     .setOngoing(true) 
     .setWhen(System.currentTimeMillis()) 
     .setContentIntent(pendingIntent); 

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationManager.notify(ID_NOTIFICATION , notificationBuilder.build()); 

} 
+3

説明を追加 –

+0

メソッド呼び出しでメッセージ文字列を渡すだけです。このcreateNotification( "test"); .setContentTitle( "Start Launcher")は、通知のタイトルです。Yourservice.classは、作成したサービスのサービス名です。 –

関連する問題