這裏是代碼爲我的作品:
內部佈局:
<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));
}
}
好運.. 斯特凡Ronnkvist
當我在一個片段上嘗試時發生註銷錯誤。我面臨的問題是 - 我試圖註銷兩次。一旦onDestroy()和onPause()一次。我還在onCreate()上註冊了一次,在onResume()上註冊了一次。後來看片段的生命週期,我發現我只需要在onResume()上註冊並在onPause()上取消註冊。這足以在一個片段上註冊和取消註冊。 希望這可以幫助有人做與片段廣播。 :) –