这是对我有用的代码:
内部布局:
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendInternalBroadcast"
android:text="Broadcast"/>
片段布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Fragment One"
android:id="@+id/fragmentoneTextView1"/>
</LinearLayout>
主要活动内部:
public void sendInternalBroadcast(View view)
{
Intent intent = new Intent();
intent.setAction("com.codingbadly.stefanronnkvist.simplebroadcastreceiver.setup");
intent.putExtra("From", "sendInternalBroadcast");
sendBroadcast(intent);
}
分段:
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class FragmentOne extends Fragment
{
View view;
Context _context;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragmentone, container, false);
setup();
return view;
}
@Override
public void onAttach(Context context)
{
super.onAttach(context);
_context = context;
}
@Override
public void onDestroyView()
{
super.onDestroyView();
_context.unregisterReceiver(br);
}
private void setup()
{
br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent i)
{
TextView tv = (TextView)view.findViewById(R.id.fragmentoneTextView1);
tv.setText("onReceive");
}
};
_context.registerReceiver(br, new IntentFilter("com.codingbadly.stefanronnkvist.simplebroadcastreceiver.setup"));
pi = PendingIntent.getBroadcast(_context, 0, new Intent("com.codingbadly.stefanronnkvist.simplebroadcastreceiver.setup"), 0);
am = (AlarmManager)(_context.getSystemService(Context.ALARM_SERVICE));
}
}
祝你好运.. Stefan Ronnkvist