2014-06-30 90 views
1
 //HERE ARE THE CODE 

import android.app.Activity; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.Toast; 

public class MainActivity extends Activity { 
    private class Receiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      Toast.makeText(getApplicationContext(), "received message in  activity..!", Toast.LENGTH_SHORT).show(); 
      Button b=(Button)findViewById(R.id.button); 
      b.setText("received"); 
     } 
    }; 

    private static final String ACTION_STRING_ACTIVITY = "ToActivity"; 
    private Receiver activityReceiver; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     activityReceiver=new Receiver(); 

     if (activityReceiver != null) { 
      IntentFilter intentFilter = new  IntentFilter(ACTION_STRING_ACTIVITY); 
      intentFilter.addDataScheme("file"); 
      registerReceiver(activityReceiver, intentFilter); 
     } 



     findViewById(R.id.button).setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       Button b=(Button)findViewById(R.id.button); 
       sendBroadcast(); 
       Log.d("SampleActivity", "broadcast sent"); 
      } 
     }); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Log.d("Service", "onDestroy"); 
     unregisterReceiver(activityReceiver); 
    } 

    private void sendBroadcast() { 

     Intent new_intent = new Intent(); 
     new_intent.setAction(ACTION_STRING_ACTIVITY); 
     new_intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 
     sendBroadcast(new_intent); 
     Button b=(Button)findViewById(R.id.button); 
    } 
} 

我正在測試Android BroadcastReceiver,但我正在爲此工作一整天 但仍無法使其工作。我在我的MainActivity中定義了一個接收器,當我點擊 這個按鈕時,它應該接收廣播,並將按鈕上的文本設置爲 「received」。Android BroadcastReceiver無法接收廣播

回答

0

確保您的清單中有以下內容:

<receiver 
     android:name="com.<your_package>.MainActivity.Receiver" 
     android:enabled="true" 
     android:exported="false" > 
     <intent-filter> 
      <action android:name="com.<your_package>.ToActivity" /> 
     </intent-filter> 
</receiver> 

好吧,我知道了。我刪除了「intentFilter.addDataScheme(」file「);」,那麼它的工作原理 但是,我沒有在清單代碼中註冊接收器。

非常感謝你