2016-06-18 10 views
1

今日私はアンドロイドのための執筆を始めました。私は、特定のタイトルの通知を待ってから何かをするシンプルな(私は思う)アプリが欲しいです。 onNotificationPostedは動作しない NotificationListenerServiceの起動方法は?

<service 
      android:name=".NotificationListener" 
      android:enabled="true" 
      android:label="@string/app_name" 
      android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> 
      <intent-filter> 
       <action android:name="android.service.notification.NotificationListenerService" /> 
      </intent-filter> 
     </service> 

がついにMainActivityのonCreate() startService(new Intent(context, NotificationListener.class));

でサービスを開始しました:私はその後マニフェストにこれを追加

import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import android.support.v4.content.LocalBroadcastManager; import android.widget.Toast; public class NotificationListener extends NotificationListenerService { Context context; public int onStartCommand(Intent intent, int flags, int startId) { // Let it continue running until it is stopped. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); return START_STICKY; } @Override public void onCreate() { Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show(); super.onCreate(); context = getApplicationContext(); } @Override public void onNotificationPosted(StatusBarNotification sbn) { String pack = sbn.getPackageName(); Toast.makeText(this,"NOTIFICATION",Toast.LENGTH_SHORT).show(); String text = ""; String title = ""; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { Bundle extras = extras = sbn.getNotification().extras; text = extras.getCharSequence("android.text").toString(); title = extras.getString("android.title"); } Log.i("Package",pack); Log.i("Title",title); Log.i("Text",text); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Toast.makeText(this,"NOTIFICATION removed",Toast.LENGTH_SHORT).show(); Log.i("Msg","Notification was removed"); } } 

サービス

ために、このコードを試してみました。 onStartCommandとonCreateのトーストが表示されたため、サービスが正しく開始されたようです。私はエミュレータと実際のデバイスを試しました。私は設定の通知アクセスも許可しました。助けてください、私は5時間を無駄にしました。

答えて

関連する問題