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無法接收廣播