我的解决方案是使用广播,并在 android manifest 中注册一个接收器。
在 AndroidManifest 中:
<receiver android:name=".MyReceiver" >
<intent-filter >
<action android:name="showtoast" />
</intent-filter>
</receiver>
发送广播:
public static void BroadcastMessage(Context context, Bundle extra)
{
Intent intent = new Intent();
intent.setPackage(context.getPackageName());
intent.setAction("showtoast");
if (extra != null)
intent.putExtras(extra);
context.sendBroadcast(intent);
}
接收器如下:
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if ("showtoast".equalsIgnoreCase(intent.getAction()) && (bundle != null)
{
String title = bundle.getString("title", "");
View view;
TextView mTextView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_toast_layout, null);
mTextView = (TextView) view.findViewById(R.id.tv_title);
mTextView.setText(title);
Toast toast = new Toast(context.getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
}
}