我已使用此答案中提供的解决方案Stopping & Starting music on incoming calls但无法弄清楚如何在我的代码中实现它。这就是我所做的 -
public class KameWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
MediaPlayer mPlay;
Context mContext;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.main);
Intent active = new Intent(context, KameWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.IBWidget, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
mPlay = MediaPlayer.create(context, R.raw.kamehameha);
mPlay.start();
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state,
String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING
|| state == TelephonyManager.CALL_STATE_OFFHOOK) {
mPlay.stop();
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) mContext
.getSystemService(Context.TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
} else {
}
super.onReceive(context, intent);
}
}
}