2013-08-02 68 views
1

如果我通過getBroadcast(someArgs)創建PendionIntent,BroadCastReceiver不起作用; 但如果我通過getServie創建()和onStartCommand捕捉事件()它做工精細broadcastReceiver無法通知(pendingIntent)

public class someClass extends Service 
{ 
    Notification createNotif() 
    { 
     RemoteViews views = new RemoteViews(getPackageName(),R.layout.notif); 
     ComponentName componentName = new ComponentName(this,someClass.class); 
     Intent intentClose = new Intent("someAction"); 
     intentClose.setComponent(componentName); 
     views.setOnClickPendingIntent(R.id.notifClose, PendingIntent.getBroadcast(this, 0, intentClose, PendingIntent.FLAG_UPDATE_CURRENT)); 
     Notification notification = new Notification(); 
     notification.contentView = views; 
     notification.flags |= Notification.FLAG_ONGOING_EVENT; 
     return notification; 
    } 

    @Override 
    public void onCreate() 
    { 
     super.onCreate(); 
     BroadcastReceiver broadcastReceiver = new BroadcastReceiver() 
     { 

      @Override 
      public void onReceive(Context context, Intent intent) 
      { 
       if(intent.getAction().equals("someAction")) 
        someMethod(); 
      } 
     }; 
     IntentFilter intentFilter = new IntentFilter("someAction"); 
     intentFilter.addAction("anyAction"); 
     registerReceiver(broadcastReceiver,intentFilter); 
    } 
} 

回答

1

你的廣播接收器是onCreate()方法中的局部變量。一旦你退出該方法模塊,就沒有任何東西保持到BroadcastReceiver,它將被垃圾收集。

您應該改爲創建一個單獨的類來擴展BroadcastReceiver並在AndroidManifest.xml中聲明它。

<application ... 
    ... 
    <receiver android:name=".MyReceiver" > 
     <intent-filter> 
      <action android:name="someAction" /> 
     </intent-filter> 
    </receiver> 
</application> 
+1

我發送數據從服務到活動,我創建broadcastReseiver在我的代碼示例,它的工作,爲什麼在服務它不工作? – doomed