下面列出了android.content.Context#sendOrderedBroadcast ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override public void onReceive(Context context, Intent intent) {
String messageType = mGCM.getMessageType(intent);
if (!messageType.equals(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE)) {
return;
}
try {
byte[] cipherText = Base64.decode(intent.getStringExtra("payload"), Base64.URL_SAFE | Base64.NO_WRAP);
byte[] iv = Base64.decode(intent.getStringExtra("iv"), Base64.URL_SAFE | Base64.NO_WRAP);
byte[] key = mPusherClient.getPushKey();
if (key == null) {
// I don't think this will ever happen
throw new Exception("Received push notification before receiving decryption key.");
}
JSONObject message = new JSONObject(new String(decrypt(cipherText, key, iv), "UTF-8"));
Intent broadcastIntent = new Intent(TapchatApp.ACTION_MESSAGE_NOTIFY);
addExtras(broadcastIntent, message);
context.sendOrderedBroadcast(broadcastIntent, null);
} catch (Exception ex) {
Log.e(TAG, "Error parsing push notification", ex);
}
}
/**
* android.media.IAudioService#dispatchMediaKeyEvent(KeyEvent), except if this
* method fails for any reason, fall back on broadcasting an event.
*/
public boolean dispatchMediaKeyEvent(Context mContext, int keyCode) {
// We'll try the public API for API 19+, then the reflected API, then
// finally we'll resort to broadcasting the action ourselves!
if (isHTC(mContext) || !_dispatchMediaKeyEvent(mManager, keyCode)) {
long eventtime = SystemClock.uptimeMillis();
KeyEvent keyDown = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0);
KeyEvent keyUp = KeyEvent.changeAction(keyDown, KeyEvent.ACTION_UP);
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyDown);
mContext.sendOrderedBroadcast(keyIntent, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyUp);
mContext.sendOrderedBroadcast(keyIntent, null);
return false;
}
return true;
}
private static void sendReply(Context context, Intent intent, String packageName, Intent outIntent) {
try {
if (intent != null && intent.hasExtra(EXTRA_MESSENGER)) {
Messenger messenger = intent.getParcelableExtra(EXTRA_MESSENGER);
Message message = Message.obtain();
message.obj = outIntent;
messenger.send(message);
return;
}
} catch (Exception e) {
Log.w(TAG, e);
}
outIntent.setPackage(packageName);
context.sendOrderedBroadcast(outIntent, null);
}
private static void answer(Context context) {
silence(context);
try {
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Method getITelephony = manager.getClass().getDeclaredMethod("getITelephony");
getITelephony.setAccessible(true);
Object iTelephony = getITelephony.invoke(manager);
Method answerRingingCall = iTelephony.getClass().getDeclaredMethod("answerRingingCall");
answerRingingCall.invoke(iTelephony);
} catch (Throwable throwable) {
Intent down = new Intent(Intent.ACTION_MEDIA_BUTTON);
down.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(down, "android.permission.CALL_PRIVILEGED");
Intent up = new Intent(Intent.ACTION_MEDIA_BUTTON);
up.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(up, "android.permission.CALL_PRIVILEGED");
}
}
/**
* android.media.IAudioService#dispatchMediaKeyEvent(KeyEvent), except if this
* method fails for any reason, fall back on broadcasting an event.
*/
public boolean dispatchMediaKeyEvent(Context mContext, int keyCode) {
// We'll try the public API for API 19+, then the reflected API, then
// finally we'll resort to broadcasting the action ourselves!
if (isHTC(mContext) || !_dispatchMediaKeyEvent(mManager, keyCode)) {
long eventtime = SystemClock.uptimeMillis();
KeyEvent keyDown = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0);
KeyEvent keyUp = KeyEvent.changeAction(keyDown, KeyEvent.ACTION_UP);
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyDown);
mContext.sendOrderedBroadcast(keyIntent, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyUp);
mContext.sendOrderedBroadcast(keyIntent, null);
return false;
}
return true;
}
/**
* 通知 Service 绑定成功
*/
public static void notifyServiceConnected(Context context, String serviceName) {
Intent intent = new Intent(IntentConstant.ACTION_SERVICE_CONNECTED);
intent.putExtra(IntentConstant.EXTRA_SERVICE_CLASS, serviceName);
// 在插件 activity 进程被回收以后恢复过程中,需要保证有序,具体参见恢复逻辑
context.sendOrderedBroadcast(intent, null);
}
public void sendKeyPressBroadcastString(Context context, int keycode, String packageName) {
Intent intent = new Intent("com.android.music.musicservicecommand");
switch (keycode) {
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
intent.putExtra("command", "previous");
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
intent.putExtra("command", "togglepause");
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
intent.putExtra("command", "pause");
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
intent.putExtra("command", "play");
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
intent.putExtra("command", "next");
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
intent.putExtra("command", "stop");
break;
default:
return;
}
if (packageName != null)
intent.setPackage(packageName);
context.sendOrderedBroadcast(intent, null);
}
/**
* Rewrite a number using a given plugin.
* Warning this should never be done on main thread otherwise will always fail due to thread issues.
*
* @param context The application context to use to talk to plugin
* @param componentName The fully qualified component name of the plugin
* @param number The number to rewrite
*/
public static String rewriteNumber(Context context, final String componentName, String number) {
ComponentName cn = ComponentName.unflattenFromString(componentName);
Intent it = new Intent(SipManager.ACTION_REWRITE_NUMBER);
it.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
it.setComponent(cn);
OnRewriteReceiver resultTreater = new OnRewriteReceiver(number);
context.sendOrderedBroadcast(it, permission.PROCESS_OUTGOING_CALLS, resultTreater, null,
Activity.RESULT_OK, null, null);
return resultTreater.getResult();
}
private void a(Context context, String str, String str2, String str3) {
z.b();
Intent intent = new Intent(z[3]);
intent.putExtra(z[5], str3);
intent.putExtra(z[2], str2);
intent.putExtra(z[4], str);
intent.putExtra(z[1], 1);
intent.addCategory(str2);
context.sendOrderedBroadcast(intent, str2 + z[0]);
z.b();
}
private void startBufferActivity(Buffer buffer) {
Context appContext = TapchatApp.get();
Intent intent = new Intent(TapchatApp.ACTION_OPEN_BUFFER);
intent.putExtra("cid", String.valueOf(buffer.getConnection().getId()));
intent.putExtra("bid", String.valueOf(buffer.getId()));
appContext.sendOrderedBroadcast(intent, null);
}
public static void broadCastBookInformationDownloadCanceled(@NonNull Context context, long id) {
Intent ftsIndexingEndedBroadCast =
new Intent(BROADCAST_ACTION)
.putExtra(EXTRA_DOWNLOAD_STATUS, DownloadsConstants.STATUS_BOOKINFORMATION_FAILED)
.putExtra(DownloadsConstants.EXTRA_DOWNLOAD_FAILLED_REASON, DownloadsConstants.REASON_CANCELED_BY_USER);
context.sendOrderedBroadcast(ftsIndexingEndedBroadCast, null);
}
/** Use to send {@link android.content.Intent#ACTION_MEDIA_BUTTON} to this application. */
public static void dispatchMediaKeyEventSelf(Context mContext, int keyCode) {
long eventtime = SystemClock.uptimeMillis();
KeyEvent keyDown = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0);
KeyEvent keyUp = KeyEvent.changeAction(keyDown, KeyEvent.ACTION_UP);
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.setPackage(mContext.getPackageName());
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyDown);
mContext.sendOrderedBroadcast(keyIntent, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyUp);
mContext.sendOrderedBroadcast(keyIntent, null);
}
public void sendOrderedBroadcastAsUser(Intent intent, VUserHandle user, String receiverPermission,
BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
String initialData, Bundle initialExtras) {
Context context = VirtualCore.get().getContext();
intent.putExtra("_VA_|_user_id_", user.getIdentifier());
// TODO: checkPermission
context.sendOrderedBroadcast(intent, null/* permission */, resultReceiver, scheduler, initialCode, initialData,
initialExtras);
}
private void sendBroadcast(final Context context,final Intent intent){
if(mIsOrder){
context.sendOrderedBroadcast(intent,mPermission);
}else {
if(TextUtils.isEmpty(mPermission)){
context.sendBroadcast(intent);
}else {
context.sendBroadcast(intent,mPermission);
}
}
}
/** Use to send {@link android.content.Intent#ACTION_MEDIA_BUTTON} to this application. */
public static void dispatchMediaKeyEventSelf(Context mContext, int keyCode) {
long eventtime = SystemClock.uptimeMillis();
KeyEvent keyDown = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0);
KeyEvent keyUp = KeyEvent.changeAction(keyDown, KeyEvent.ACTION_UP);
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.setPackage(mContext.getPackageName());
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyDown);
mContext.sendOrderedBroadcast(keyIntent, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyUp);
mContext.sendOrderedBroadcast(keyIntent, null);
}
/**
* Emulates hardware buttons' click via broadcast system.
*
* @see android.view.KeyEvent
*/
public static void broadcastMediaAction(@NonNull Context context, int action) {
int keyCode;
switch (action) {
case ACTION_PLAY_PAUSE:
keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
break;
case ACTION_STOP:
keyCode = KeyEvent.KEYCODE_MEDIA_STOP;
break;
case ACTION_SKIP_TO_NEXT:
keyCode = KeyEvent.KEYCODE_MEDIA_NEXT;
break;
case ACTION_SKIP_TO_PREVIOUS:
keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS;
break;
default:
throw new IllegalArgumentException();
}
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
KeyEvent keyDown = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
KeyEvent keyUp = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
context.sendOrderedBroadcast(intent.putExtra(Intent.EXTRA_KEY_EVENT, keyDown), null);
context.sendOrderedBroadcast(intent.putExtra(Intent.EXTRA_KEY_EVENT, keyUp), null);
}
/**
* Scan the program directory and check each book data base file against the StoredBooks Database
*/
public void refreshBooksDbWithDirectory(@NonNull Context context,
@Nullable SplashActivity.RefreshBooksProgressCallBack refreshBooksProgressCallBack) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BooksInformationDBContract.StoredBooks.COLUMN_NAME_FILESYSTEM_SYNC_FLAG,
VALUE_FILESYSTEM_SYNC_FLAG_NOT_PRESENT);
db.update(BooksInformationDBContract.StoredBooks.TABLE_NAME,
contentValues, null, null);
File booksDir = new File(StorageUtils.getIslamicLibraryShamelaBooksDir(context));
if (!(booksDir.exists() && booksDir.isDirectory())) {
booksDir.mkdirs();
} else {
String[] files = booksDir.list((dir, name) ->
name.endsWith(DATABASE_EXTENSION)
&&
!name.endsWith(DATABASE_JOURNAL)
&& !name.equals(DATABASE_FULL_NAME));
if (files.length == 0) {
return;
}
for (int i = 0; i < files.length; i++) {
String file = files[i];
String fullFilePath = booksDir + File.separator + file;
//validate file name against <integer>.sqlite
Matcher matcher = uncompressedBookFileRegex.matcher(file);
if (matcher.matches()) {
int book_id = Integer.parseInt(matcher.group(1));
checkFileInDbOrInsert(db, book_id, context, fullFilePath);
} else {
Matcher compressedMatcher = compressedBookFileRegex.matcher(file);
if (compressedMatcher.matches()) {
int bookId = Integer.parseInt(compressedMatcher.group(1));
Intent localIntent =
new Intent(BROADCAST_ACTION)
// Puts the status into the Intent
.putExtra(EXTRA_DOWNLOAD_STATUS, DownloadsConstants.STATUS_WAITING_FOR_UNZIP)
.putExtra(DownloadsConstants.EXTRA_DOWNLOAD_BOOK_ID, bookId);
context.sendOrderedBroadcast(localIntent, null);
Intent serviceIntent = new Intent(context, UnZipIntentService.class);
serviceIntent.putExtra(UnZipIntentService.EXTRA_FILE_PATH, fullFilePath);
context.startService(serviceIntent);
// Broadcasts the Intent to receivers in this app.
}
}
if (refreshBooksProgressCallBack != null) {
refreshBooksProgressCallBack.accept(i);
}
}
//delete book entries that doesn't have files in file system
db.delete(BooksInformationDBContract.StoredBooks.TABLE_NAME,
BooksInformationDBContract.StoredBooks.COLUMN_NAME_FILESYSTEM_SYNC_FLAG + "=?",
new String[]{String.valueOf(BooksInformationDBContract.StoredBooks.VALUE_FILESYSTEM_SYNC_FLAG_NOT_PRESENT)}
);
}
}
@Override public void onReceive(Context context, Intent intent) {
Intent broadcastIntent = new Intent(TapchatApp.ACTION_OPEN_BUFFER);
broadcastIntent.putExtras(intent.getExtras());
context.sendOrderedBroadcast(broadcastIntent, null);
}
@Override
public void onReceive(Context context, Intent intent) {
// handle cancel notification action on uploads
final String action = intent.getAction();
if (Constants.CANCEL.equals(action)) {
int notifId = intent.getIntExtra("id", 0);
try {
ZulipApp.get().getZulipActivity().cancelRequest(notifId);
} catch (NullPointerException e) {
ZLog.log("onReceive: app destroyed but notification visible");
return;
}
}
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that
* GCM will be extended in the future with new message types, just
* ignore any message types you're not interested in, or that you
* don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
Log.i(TAG, "Received: " + extras.toString());
if (extras.getString("event").equals("message")) {
Intent broadcast = new Intent(getGCMReceiverAction(context.getApplicationContext()));
broadcast.putExtras(extras);
context.sendOrderedBroadcast(broadcast, null);
}
}
}
setResultCode(Activity.RESULT_OK);
}
/**
* Forwards {@code keyCode} to receiver specified as two key events, one for
* up and one for down. Optionally launches the application for the
* receiver.
*
* @param context
* @param selectedReceiver
* @param launch
* @param keyCode
* @param cleanUpReceiver
*/
public static void forwardKeyCodeToComponent(Context context, ComponentName selectedReceiver, boolean launch,
int keyCode, BroadcastReceiver cleanUpReceiver) {
Intent mediaButtonDownIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
KeyEvent downKe = new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_DOWN,
keyCode, 0);
mediaButtonDownIntent.putExtra(Intent.EXTRA_KEY_EVENT, downKe);
Intent mediaButtonUpIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
KeyEvent upKe = new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_UP,
keyCode, 0);
mediaButtonUpIntent.putExtra(Intent.EXTRA_KEY_EVENT, upKe);
mediaButtonDownIntent.setComponent(selectedReceiver);
mediaButtonUpIntent.setComponent(selectedReceiver);
/* COMMENTED OUT FOR MARKET RELEASE Log.i(TAG, "Forwarding Down and Up intent events to " + selectedReceiver + " Down Intent: "
+ mediaButtonDownIntent + " Down key:" + downKe + " Up Intent: " + mediaButtonUpIntent + " Up key:"
+ upKe); */
// We start the selected application because some apps broadcast
// receivers won't do anything with the intents unless the
// application is open. (This this is only if the app isn't
// playing music and you want it to play music now)
// XXX Is that true? recheck..
// Another reason to launch the app is that if the app does
// AudioManager#registerMediaButtonEventReceiver
// on load, and we are unable to tell when this app is playing music,
// android's default behavior should be correct.
if (launch) {
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(
selectedReceiver.getPackageName());
if (launchIntent != null) {
context.startActivity(launchIntent);
}
}
context.sendOrderedBroadcast(mediaButtonDownIntent, null, cleanUpReceiver, null, Activity.RESULT_OK, null, null);
context.sendOrderedBroadcast(mediaButtonUpIntent, null, cleanUpReceiver, null, Activity.RESULT_OK, null, null);
}