I want to play this link but i m unable to play this link in my exoplayer
I will be able to play this link only when this referer will be added in the exoplayer but i m unable to add this referer. I dont know how can i add this referer to my exoplayer
Referer: http://nbajunkie.xyz/jp1/
https://reels2watch.com/hls/s1.m3u8
dataSourceFactory.getDefaultRequestProperties().set("Referer", "https://yourdomain.com");
I dont know how to add this referer in the header can someone help me about it or Anyone can do it for me ? Because i don’t know much about java kindly let me know how to solve this issue.
import static com.google.android.exoplayer2.util.Util.getUserAgent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.mediarouter.app.MediaRouteButton;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.DefaultMediaSourceFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.util.Util;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaLoadOptions;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.cast.framework.CastButtonFactory;
import com.google.android.gms.cast.framework.CastContext;
import com.google.android.gms.cast.framework.CastSession;
import com.google.android.gms.cast.framework.CastState;
import com.google.android.gms.cast.framework.CastStateListener;
import com.google.android.gms.cast.framework.SessionManagerListener;
import com.google.android.gms.cast.framework.media.RemoteMediaClient;
import com.google.firebase.FirebaseApp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.Myapp.hd.Steaming.R;
import com.Myapp.hd.Steaming.HelperClass;
import com.Myapp.hd.Steaming.BaseActivity;
import com.Myapp.hd.Steaming.Location;
import com.Myapp.hd.Steaming.sessionManager.SessionManager;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class Exo_Player extends BaseActivity {
private static final String TAG = "Exo_Player";
String url, userAgent;
boolean tokenEnable = false;
private InterstitialAd interstitial;
private PlayerView playerView;
private SimpleExoPlayer player;
private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
private DataSource.Factory mediaDataSourceFactory;
private Handler mainHandler;
private ProgressBar progressBar;
FirebaseFirestore db;
SessionManager sessionManager;
FirebaseFirestore firebaseFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
//////////////////////////////////////////////////////
setContentView(R.layout.exo_player_ui);
castContext = CastContext.getSharedInstance(this);
initCast();
db = FirebaseFirestore.getInstance();
sessionManager = new SessionManager(this);
FirebaseApp.initializeApp(this);
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Exo_Player.this, sessionManager.getBackads(), adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
interstitial = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
interstitial = null;
}
});
progressBar = findViewById(R.id.progressBar);
processToken();
listenCast();
}
MediaRouteButton mediaRouteButton;
CastContext castContext;
RemoteMediaClient remoteMediaClient;
public boolean initCast() {
url = getIntent().getStringExtra(getString(R.string.url));
userAgent = getIntent().getStringExtra(getString(R.string.user_agent));
tokenEnable = getIntent().getBooleanExtra(getString(R.string.t_enable), false);
mediaRouteButton = (MediaRouteButton) findViewById(R.id.media_route_button);
CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), mediaRouteButton);
if (castContext == null)
castContext = CastContext.getSharedInstance(this);
castContext.addCastStateListener(new CastStateListener() {
#Override
public void onCastStateChanged(int state) {
/*if (state == CastState.NO_DEVICES_AVAILABLE) {
// mediaRouteButton.setVisibility(View.GONE);
}
else if(state==CastState.CONNECTING) {
showToast("Connecting");
} else*/ if (state == CastState.CONNECTED) {
// showToast("Connected");
// castMetadata();
openCastPlayer();
}/* else if (mediaRouteButton.getVisibility() == View.GONE) {
mediaRouteButton.setVisibility(View.VISIBLE);
}*/
}
});
if (castContext.getCastState() == CastState.CONNECTED) {
openCastPlayer();
return true;
} else {
// showToast("not connected");
}
if (castContext.getCastState() != CastState.NO_DEVICES_AVAILABLE)
mediaRouteButton.setVisibility(View.VISIBLE);
return false;
}
private void registerListener() {
if (mCastContext != null) {
mCastContext.getSessionManager().addSessionManagerListener(
mSessionManagerListener, CastSession.class);
}
}
private void unRegisterListener() {
if (mCastContext != null) {
mCastContext.getSessionManager().removeSessionManagerListener(
mSessionManagerListener, CastSession.class);
}
}
private void showToast(String connecting) {
Toast.makeText(this, connecting, Toast.LENGTH_SHORT).show();
}
private void processToken() {
if (!HelperClass.isValid(url) || !tokenEnable) {
init("");
return;
}
HashMap<String, Object> hashMap = new HashMap<>();
enqueue(getLocInterface().getLoc(sessionManager.getToken(), hashMap), new CallBack<Location>() {
#Override
public void onComplete() {
super.onComplete();
}
#Override
public void onError(Throwable e) {
super.onError(e);
Toast.makeText(Exo_Player.this,
"Failed to process url", Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(#NotNull Location location) {
super.onNext(location);
if (location.appendResult != null)
init(location.appendResult);
}
});
}
private void init(String s) {
url += s;
Log.e(TAG, "init: new url is " + url);
mediaDataSourceFactory = buildDataSourceFactory(true);
mainHandler = new Handler();
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
RenderersFactory renderersFactory = new DefaultRenderersFactory(this);
// TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
// TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
// TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
player = new SimpleExoPlayer.Builder(this, renderersFactory).setLoadControl(loadControl).build();
playerView = findViewById(R.id.exoPlayerView);
playerView.setPlayer(player);
playerView.setUseController(true);
playerView.requestFocus();
Uri uri = Uri.parse(url);
final MediaSource mediaSource = buildMediaSource(uri, null);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
player.addListener(new Player.Listener() {
#Override
public void onTracksChanged(#NotNull TrackGroupArray trackGroups, #NotNull TrackSelectionArray trackSelections) {
Log.d(TAG, "onTracksChanged: " + trackGroups.length);
}
#Override
public void onIsLoadingChanged(boolean isLoading) {
Log.d(TAG, "onLoadingChanged: " + isLoading);
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
Log.d(TAG, "onPlayerStateChanged: " + playWhenReady);
if (playbackState == PlaybackStateCompat.STATE_PLAYING) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(#NotNull PlaybackException error) {
Log.e(TAG, "onPlayerError: ", error);
player.stop();
// errorDialog();
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}
#Override
public void onPositionDiscontinuity(int reason) {
Log.d(TAG, "onPositionDiscontinuity: true");
}
#Override
public void onPlaybackParametersChanged(#NotNull PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
Log.d("INFO", "ActivityVideoPlayer");
}
private void pausePlayer() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
private void startPlayer() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
protected void onPause() {
super.onPause();
try {
unRegisterListener();
pausePlayer();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
/////////////////////////////////////////////
try {
registerListener();
if (HelperClass.vpn(this)) {
finish();
}
startPlayer();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG, "onDestroy()...");
if (player != null)
player.release();
}
private MediaSource buildMediaSource(Uri uri, String overrideExtension) {
int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri)
: Util.inferContentType("." + overrideExtension);
switch (type) {
case C.TYPE_SS:
return new SsMediaSource.Factory(new DefaultSsChunkSource.Factory(mediaDataSourceFactory), buildDataSourceFactory(false)).createMediaSource(uri);
case C.TYPE_DASH:
return new DashMediaSource.Factory(new DefaultDashChunkSource.Factory(mediaDataSourceFactory), buildDataSourceFactory(false)).createMediaSource(uri);
case C.TYPE_HLS:
return new HlsMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);
case C.TYPE_OTHER:
return new ProgressiveMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
}
public DataSource.Factory buildDataSourceFactory(DefaultBandwidthMeter bandwidthMeter) {
return new DefaultDataSourceFactory(this, bandwidthMeter,
buildHttpDataSourceFactory(bandwidthMeter));
}
public HttpDataSource.Factory buildHttpDataSourceFactory(DefaultBandwidthMeter bandwidthMeter) {
String s = "xxxxx";
if (userAgent != null && !userAgent.isEmpty()) {
s = userAgent;
}
return new DefaultHttpDataSourceFactory(getUserAgent2(this, s), bandwidthMeter);
}
public static String getUserAgent2(Context context, String applicationName) {
return applicationName
+ "";
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (interstitial != null) {
interstitial.show(Exo_Player.this);
}
if (player != null)
player.stop();
}
// public void errorDialog() {
// new AlertDialog.Builder(this)
// .setIcon(android.R.drawable.ic_dialog_alert)
// .setTitle(getResources().getString(R.string.msg_oops))
// .setCancelable(false)
// .setMessage(getResources().getString(R.string.msg_failed))
// .setPositiveButton(getResources().getString(R.string.option_retry), new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// retryLoad();
// z }
//
// })
// .setNegativeButton(getResources().getString(R.string.option_no), new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialogInterface, int i) {
// finish();
// }
// })
// .show();
// }
// public void retryLoad() {
// Uri uri = Uri.parse(url);
// MediaSource mediaSource = buildMediaSource(uri, null);
// player.prepare(mediaSource);
// player.setPlayWhenReady(true);
// }
public void castplayer(String name, String link, String unique, String img) {
if (!isCastApiAvailable()) {
return;
}
Context context = this;
CastSession castSession = CastContext.getSharedInstance(context).getSessionManager()
.getCurrentCastSession();
if (castSession.isConnected()) {
MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_GENERIC);
movieMetadata.putString(MediaMetadata.KEY_TITLE, name);
MediaInfo mediaInfo = new MediaInfo.Builder(link)
.setMetadata(movieMetadata)
.setEntity(unique)
.build();
final RemoteMediaClient remoteMediaClient = castSession.getRemoteMediaClient();
if (remoteMediaClient == null) {
// Timber.tag(TAG).w("showQueuePopup(): null RemoteMediaClient");
return;
}
if (remoteMediaClient.isPlaying()) {
MediaInfo curMedia = remoteMediaClient.getMediaInfo();
if (curMedia != null && curMedia.getEntity().equals(unique)) {
return;
}
}
if (remoteMediaClient.isLoadingNextItem() || remoteMediaClient.isBuffering()) {
return;
}
// final QueueDataProvider provider = QueueDataProvider.getInstance(context);
// PopupMenu popup = new PopupMenu(context, binding.epLayout);
// popup.getMenuInflater().inflate(
// provider.isQueueDetached() || provider.getCount() == 0
// ? R.menu.detached_popup_add_to_queue
// : R.menu.popup_add_to_queue, popup.getMenu());
// PopupMenu.OnMenuItemClickListener clickListener = menuItem -> {
// QueueDataProvider provider1 = QueueDataProvider.getInstance(context);
// MediaQueueItem queueItem = new MediaQueueItem.Builder(mediaInfo).setAutoplay(
// false).setPreloadTime(2).build();
// MediaQueueItem[] newItemArray = new MediaQueueItem[]{queueItem};
// String toastMessage = null;
// if (provider1.isQueueDetached() && provider1.getCount() > 0) {
// if ((menuItem.getItemId() == R.id.action_play_now)
// || (menuItem.getItemId() == R.id.action_add_to_queue)) {
// MediaQueueItem[] items = Utils
// .rebuildQueueAndAppend(provider1.getItems(), queueItem);
// remoteMediaClient.queueLoad(items, provider1.getCount(),
// MediaStatus.REPEAT_MODE_REPEAT_OFF, null);
// } else {
// return false;
// }
// } else {
// if (provider1.getCount() == 0) {
// remoteMediaClient.queueLoad(newItemArray, 0,
// MediaStatus.REPEAT_MODE_REPEAT_OFF, null);
// } else {
// int currentId = provider1.getCurrentItemId();
//// if (menuItem.getItemId() == R.id.action_play_now) {
// remoteMediaClient.queueInsertAndPlayItem(queueItem, currentId, null);
remoteMediaClient.load(mediaInfo, new MediaLoadOptions.Builder().build());
// } else if (menuItem.getItemId() == R.id.action_play_next) {
// int currentPosition = provider1.getPositionByItemId(currentId);
// if (currentPosition == provider1.getCount() - 1) {
// //we are adding to the end of queue
// remoteMediaClient.queueAppendItem(queueItem, null);
// } else {
// int nextItemId = provider1.getItem(currentPosition + 1).getItemId();
// remoteMediaClient.queueInsertItems(newItemArray, nextItemId, null);
// }
// toastMessage = context.getString(
// R.string.queue_item_added_to_play_next);
// } else if (menuItem.getItemId() == R.id.action_add_to_queue) {
// remoteMediaClient.queueAppendItem(queueItem, null);
// toastMessage = context.getString(R.string.queue_item_added_to_queue);
// } else {
// return false;
// }
// }
// }
// if (menuItem.getItemId() == R.id.action_play_now) {
Intent intent = new Intent(context, ExpandedControlsActivity.class);
context.startActivity(intent);
// }
// if (!TextUtils.isEmpty(toastMessage)) {
// Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
// }
// return true;
// };
// popup.setOnMenuItemClickListener(clickListener);
// popup.show();
// }
} else {
Toast.makeText(context,
"Not Connected", Toast.LENGTH_SHORT).show();
}
}
private CastContext mCastContext;
private CastSession mCastSession;
private SessionManagerListener<CastSession> mSessionManagerListener;
private void listenCast() {
if (!isCastApiAvailable()) {
return;
}
setupCastListener();
mCastContext = CastContext.getSharedInstance(this);
mCastSession = mCastContext.getSessionManager().getCurrentCastSession();
}
private void setupCastListener() {
mSessionManagerListener = new SessionManagerListener<CastSession>() {
#Override
public void onSessionEnded(CastSession session, int error) {
onApplicationDisconnected();
mCastContext = null;
mCastSession = null;
}
#Override
public void onSessionResumed(CastSession session, boolean wasSuspended) {
onApplicationConnected(session);
}
#Override
public void onSessionResumeFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarted(CastSession session, String sessionId) {
onApplicationConnected(session);
}
#Override
public void onSessionStartFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarting(CastSession session) {
}
#Override
public void onSessionEnding(CastSession session) {
}
#Override
public void onSessionResuming(CastSession session, String sessionId) {
}
#Override
public void onSessionSuspended(CastSession session, int reason) {
}
private void onApplicationConnected(CastSession castSession) {
mCastSession = castSession;
openCastPlayer();
invalidateOptionsMenu();
}
private void onApplicationDisconnected() {
invalidateOptionsMenu();
}
};
}
private void openCastPlayer() {
castplayer(getString(R.string.app_name), url, url, url);
finish();
}
}
I remember that was changed with the newer updates at some point last year. Now you need to pass a map to setDefaultRequestProperties after building a HttpDataSource. Using a DefaultHttpDataSource.Factory should be enough if you are not considering using a custom one.
Related
Pls, I'm having problems having a steady connection between my android app and my smartwatch, anytime the app connect with the watch, it connect and disconnect immediately. I actually use a custom crrp sdk for the project
This is the scan activity
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.crrepa.ble.CRPBleClient;
import com.crrepa.ble.conn.CRPBleDevice;
import com.crrepa.ble.conn.listener.CRPBleFirmwareUpgradeListener;
import com.crrepa.ble.scan.bean.CRPScanDevice;
import com.crrepa.ble.scan.callback.CRPScanCallback;
import com.crrepa.ble.trans.upgrade.bean.HSFirmwareInfo;
import com.crrepa.sdk.sample.PermissionUtils;
import com.crrepa.sdk.sample.R;
import com.crrepa.sdk.sample.SampleApplication;
import com.crrepa.sdk.sample.device.DeviceActivity;
import java.io.File;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ScanActivity extends AppCompatActivity {
private static final String TAG = "ScanActivity";
private static final int SCAN_PERIOD = 10 * 1000;
private static final int REQUEST_UPDATEBANDCONFIG = 4;
private static final String[] PERMISSION_UPDATEBANDCONFIG = new String[] {
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.ACCESS_COARSE_LOCATION"};
#BindView(R.id.btn_scan_toggle)
Button scanToggleBtn;
#BindView(R.id.scan_results)
RecyclerView scanResults;
#BindView(R.id.tv_firmware_fix_state)
TextView tvFirmwareFixState;
private CRPBleClient mBleClient;
private ScanResultsAdapter mResultsAdapter;
private boolean mScanState = false;
private static final String UPGRADE_APP_FILE_PATH = Environment.getExternalStorageDirectory().getPath()
+ File.separator + "crrepa" + File.separator + "app_band-hs.bin";
private static final String UPGRADE_USER_FILE_PATH = Environment.getExternalStorageDirectory().getPath()
+ File.separator + "crrepa" + File.separator + "usr.bin";
private static final String USER_START_ADDRESS = "23000";
// private static final String BAND_ADDRESS = "C1:C4:7C:DE:44:5B";
// private static final String BAND_ADDRESS = "D9:4D:C2:BB:F3:F4";
private static final String BAND_ADDRESS = "FB:09:C5:C7:1A:90";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
ButterKnife.bind(this);
mBleClient = SampleApplication.getBleClient(this);
configureResultList();
requestPermissions();
}
#Override
protected void onPause() {
super.onPause();
cancelScan();
}
#OnClick({R.id.btn_scan_toggle, R.id.btn_firmware_fix, R.id.btn_hs_upgrade})
public void onViewClicked(View view) {
if (!mBleClient.isBluetoothEnable()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
return;
}
switch (view.getId()) {
case R.id.btn_scan_toggle:
if (mScanState) {
cancelScan();
} else {
startScan();
}
break;
case R.id.btn_firmware_fix:
break;
case R.id.btn_hs_upgrade:
CRPBleClient bleClient = SampleApplication.getBleClient(this);
CRPBleDevice bleDevice = bleClient.getBleDevice(BAND_ADDRESS);
HSFirmwareInfo upgradeInfo = new HSFirmwareInfo();
upgradeInfo.setAppFilePath(UPGRADE_APP_FILE_PATH);
upgradeInfo.setUserFilePath(UPGRADE_USER_FILE_PATH);
upgradeInfo.setUserStartAddress(USER_START_ADDRESS);
break;
}
}
private void startScan() {
boolean success = mBleClient.scanDevice(new CRPScanCallback() {
#Override
public void onScanning(final CRPScanDevice device) {
Log.d(TAG, "address: " + device.getDevice().getAddress());
if (TextUtils.isEmpty(device.getDevice().getName())) {
return;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mResultsAdapter.addScanResult(device);
}
});
}
#Override
public void onScanComplete(List<CRPScanDevice> results) {
if (mScanState) {
mScanState = false;
updateButtonUIState();
}
}
}, SCAN_PERIOD);
if (success) {
mScanState = true;
updateButtonUIState();
mResultsAdapter.clearScanResults();
}
}
private void cancelScan() {
mBleClient.cancelScan();
}
private void configureResultList() {
scanResults.setHasFixedSize(true);
LinearLayoutManager recyclerLayoutManager = new LinearLayoutManager(this);
scanResults.setLayoutManager(recyclerLayoutManager);
mResultsAdapter = new ScanResultsAdapter();
scanResults.setAdapter(mResultsAdapter);
mResultsAdapter.setOnAdapterItemClickListener(new ScanResultsAdapter.OnAdapterItemClickListener() {
#Override
public void onAdapterViewClick(View view) {
final int childAdapterPosition = scanResults.getChildAdapterPosition(view);
final CRPScanDevice itemAtPosition = mResultsAdapter.getItemAtPosition(childAdapterPosition);
onAdapterItemClick(itemAtPosition);
}
});
}
private void onAdapterItemClick(CRPScanDevice scanResults) {
final String macAddress = scanResults.getDevice().getAddress();
mBleClient.cancelScan();
final Intent intent = new Intent(this, DeviceActivity.class);
intent.putExtra(DeviceActivity.DEVICE_MACADDR, macAddress);
startActivity(intent);
}
private void updateButtonUIState() {
scanToggleBtn.setText(mScanState ? R.string.stop_scan : R.string.start_scan);
}
CRPBleFirmwareUpgradeListener mFirmwareUpgradeListener = new CRPBleFirmwareUpgradeListener() {
#Override
public void onFirmwareDownloadStarting() {
Log.d(TAG, "onFirmwareDownloadStarting");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_download_starting));
}
#Override
public void onFirmwareDownloadComplete() {
Log.d(TAG, "onFirmwareDownloadComplete");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_download_complete));
}
#Override
public void onUpgradeProgressStarting() {
Log.d(TAG, "onUpgradeProgressStarting");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_starting));
}
#Override
public void onUpgradeProgressChanged(int percent, float speed) {
Log.d(TAG, "onUpgradeProgressChanged: " + percent);
String status = String.format(getString(R.string.dfu_status_uploading_part), percent);
updateTextView(tvFirmwareFixState, status);
}
#Override
public void onUpgradeCompleted() {
Log.d(TAG, "onUpgradeCompleted");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_completed));
}
#Override
public void onUpgradeAborted() {
Log.d(TAG, "onUpgradeAborted");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_aborted));
}
#Override
public void onError(int errorType, String message) {
Log.d(TAG, "onError: " + errorType);
updateTextView(tvFirmwareFixState, message);
}
};
void updateTextView(final TextView view, final String con) {
runOnUiThread(new Runnable() {
#Override
public void run() {
view.setText(con);
}
});
}
void requestPermissions() {
if (!PermissionUtils.hasSelfPermissions(this, PERMISSION_UPDATEBANDCONFIG)) {
ActivityCompat.requestPermissions(
this, PERMISSION_UPDATEBANDCONFIG, REQUEST_UPDATEBANDCONFIG);
}
}
}
and the device activity here where data is transferred between the watch and the app
private static final String TAG = "DeviceActivity";
public static final String DEVICE_MACADDR = "device_macaddr";
private static final String UI_FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "crrepa" + File.separator + "ota" + File.separator
+ "eaf49ccb4dbe5df51af35803662867d5.bin";
ProgressDialog mProgressDialog;
CRPBleClient mBleClient;
CRPBleDevice mBleDevice;
CRPBleConnection mBleConnection;
boolean isUpgrade = false;
#BindView(R.id.tv_connect_state)
TextView tvConnectState;
#BindView(R.id.tv_firmware_version)
TextView tvFirmwareVersion;
#BindView(R.id.tv_battery)
TextView tvBattery;
#BindView(R.id.tv_step)
TextView tvStep;
#BindView(R.id.tv_distance)
TextView tvDistance;
#BindView(R.id.tv_calorie)
TextView tvCalorie;
#BindView(R.id.tv_restful)
TextView tvRestful;
#BindView(R.id.tv_light)
TextView tvLight;
#BindView(R.id.tv_heart_rate)
TextView tvHeartRate;
#BindView(R.id.tv_blood_pressure)
TextView tvBloodPressure;
#BindView(R.id.tv_upgrade_state)
TextView tvUpgradeState;
#BindView(R.id.btn_ble_connect_state)
Button btnBleDisconnect;
#BindView(R.id.tv_blood_oxygen)
TextView tvBloodOxygen;
#BindView(R.id.tv_new_firmware_version)
TextView tvNewFirmwareVersion;
private String bandFirmwareVersion;
private List<Integer> supportWatchFaceList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device);
ButterKnife.bind(this);
initView();
mProgressDialog = new ProgressDialog(this);
String macAddr = getIntent().getStringExtra(DEVICE_MACADDR);
//BluetoothDevice device = BluetoothAdapter.
if (TextUtils.isEmpty(macAddr)) {
finish();
return;
}
mBleClient = SampleApplication.getBleClient(this);
mBleDevice = mBleClient.getBleDevice(macAddr);
if (mBleDevice != null && !mBleDevice.isConnected()) {
connect();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBleDevice != null) {
mBleDevice.disconnect();
}
}
void initView() {
updateStepInfo(0, 0, 0);
updateSleepInfo(0, 0);
}
void connect() {
mProgressDialog.show();
mBleDevice.connect();
mBleConnection = mBleDevice.connect();
mBleConnection.setConnectionStateListener(new CRPBleConnectionStateListener() {
#Override
public void onConnectionStateChange(int newState) {
Log.d(TAG, "onConnectionStateChange: " + newState);
int state = -1;
switch (newState) {
case CRPBleConnectionStateListener.STATE_CONNECTED:
DeviceActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// state = R.string.state_connected;
mProgressDialog.dismiss();
updateTextView(btnBleDisconnect, getString(R.string.disconnect));
Toast.makeText(DeviceActivity.this, "connected", Toast.LENGTH_SHORT).show();
}
});
testSet();
break;
case CRPBleConnectionStateListener.STATE_CONNECTING:
state = R.string.state_connecting;
break;
case CRPBleConnectionStateListener.STATE_DISCONNECTED:
//closeGatt();
state = R.string.state_disconnected;
mProgressDialog.dismiss();
updateTextView(btnBleDisconnect, getString(R.string.connect));
break;
}
updateConnectState(state);
}
});
mBleConnection.setStepChangeListener(mStepChangeListener);
mBleConnection.setSleepChangeListener(mSleepChangeListener);
mBleConnection.setHeartRateChangeListener(mHeartRateChangListener);
mBleConnection.setBloodPressureChangeListener(mBloodPressureChangeListener);
mBleConnection.setBloodOxygenChangeListener(mBloodOxygenChangeListener);
mBleConnection.setFindPhoneListener(mFindPhoneListener);
mBleConnection.setECGChangeListener(mECGChangeListener, CRPEcgMeasureType.TI);
mBleConnection.setStepsCategoryListener(mStepsCategoryChangeListener);
mBleConnection.setSleepActionChangeListener(mSleepActionChangeListener);
mBleConnection.setMovementStateListener(mMovementStateListener);
mBleConnection.setTempChangeListener(mTempChangeListener);
mBleConnection.setContactListener(mContactListener);
mBleConnection.setHrvChangeListener(mHrvChangeListener);
}
private void closeGatt() {
if (mBleConnection != null) {
mBleConnection.close();
}
}```
I'm building video chat application using webrtc. when i started video call some error is coming. how to resolve that issue.
E/RoomRTCClient: Room connection error: HTTP POST to https://appr.tc/join/E52U8KA error: Unacceptable certificate: CN=COMODO RSA Certification Authority, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB.
E/WSRTCClient: HTTP POST to https://appr.tc/join/E52U8KA error: Unacceptable certificate: CN=COMODO RSA Certification Authority, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.UiThread;
import com.skillatwill.skillatwill.R;
import org.appspot.apprtc.AppRTCClient;
import org.appspot.apprtc.PeerConnectionClient;
import org.appspot.apprtc.WebSocketRTCClient;
import org.webrtc.Camera2Enumerator;
import org.webrtc.CameraEnumerator;
import org.webrtc.IceCandidate;
import org.webrtc.Logging;
import org.webrtc.RendererCommon.ScalingType;
import org.webrtc.SessionDescription;
import org.webrtc.StatsReport;
import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoCapturer;
import org.webrtc.VideoFrame;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoSink;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
/**
* Activity for peer connection call setup, call waiting
* and call view.
*/
public class CallActivity extends Activity implements AppRTCClient.SignalingEvents,
PeerConnectionClient.PeerConnectionEvents {
private static final String TAG = "CallActivity";
private static final String APPRTC_URL = "https://appr.tc";
private static final String UPPER_ALPHA_DIGITS = "ACEFGHJKLMNPQRUVWXY123456789";
// Peer connection statistics callback period in ms.
private static final int STAT_CALLBACK_PERIOD = 1000;
private final ProxyRenderer remoteProxyRenderer = new ProxyRenderer();
private final ProxyVideoSink localProxyVideoSink = new ProxyVideoSink();
private final List<VideoRenderer.Callbacks> remoteRenderers = new ArrayList<>();
private PeerConnectionClient peerConnectionClient = null;
private AppRTCClient appRtcClient;
private AppRTCClient.SignalingParameters signalingParameters;
private SurfaceViewRenderer pipRenderer;
private SurfaceViewRenderer fullscreenRenderer;
private Toast logToast;
private boolean activityRunning;
private AppRTCClient.RoomConnectionParameters roomConnectionParameters;
private PeerConnectionClient.PeerConnectionParameters peerConnectionParameters;
private boolean iceConnected;
private boolean isError;
private long callStartedTimeMs = 0;
private boolean micEnabled = true;
private boolean isSwappedFeeds;
// Control buttons for limited UI
private ImageButton disconnectButton;
private ImageButton cameraSwitchButton;
private ImageButton toggleMuteButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
iceConnected = false;
signalingParameters = null;
// Create UI controls.
pipRenderer = findViewById(R.id.pip_video_view);
fullscreenRenderer = findViewById(R.id.fullscreen_video_view);
disconnectButton = findViewById(R.id.button_call_disconnect);
cameraSwitchButton = findViewById(R.id.button_call_switch_camera);
toggleMuteButton = findViewById(R.id.button_call_toggle_mic);
// Add buttons click events.
disconnectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onCallHangUp();
}
});
cameraSwitchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onCameraSwitch();
}
});
toggleMuteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
boolean enabled = onToggleMic();
toggleMuteButton.setAlpha(enabled ? 1.0f : 0.3f);
}
});
// Swap feeds on pip view click.
pipRenderer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setSwappedFeeds(!isSwappedFeeds);
}
});
remoteRenderers.add(remoteProxyRenderer);
// Create peer connection client.
peerConnectionClient = new PeerConnectionClient();
// Create video renderers.
pipRenderer.init(peerConnectionClient.getRenderContext(), null);
pipRenderer.setScalingType(ScalingType.SCALE_ASPECT_FIT);
fullscreenRenderer.init(peerConnectionClient.getRenderContext(), null);
fullscreenRenderer.setScalingType(ScalingType.SCALE_ASPECT_FILL);
pipRenderer.setZOrderMediaOverlay(true);
pipRenderer.setEnableHardwareScaler(true /* enabled */);
fullscreenRenderer.setEnableHardwareScaler(true /* enabled */);
// Start with local feed in fullscreen and swap it to the pip when the call is connected.
setSwappedFeeds(true /* isSwappedFeeds */);
// Generate a random room ID with 7 uppercase letters and digits
String randomRoomID = randomString(7, UPPER_ALPHA_DIGITS);
// Show the random room ID so that another client can join from https://appr.tc
TextView roomIdTextView = findViewById(R.id.roomID);
roomIdTextView.setText(getString(R.string.room_id_caption) + randomRoomID);
Log.d(TAG, getString(R.string.room_id_caption) + randomRoomID);
// Connect video call to the random room
connectVideoCall(randomRoomID);
}
// Create a random string
private String randomString(int length, String characterSet) {
StringBuilder sb = new StringBuilder(); //consider using StringBuffer if needed
for (int i = 0; i < length; i++) {
int randomInt = new SecureRandom().nextInt(characterSet.length());
sb.append(characterSet.substring(randomInt, randomInt + 1));
}
return sb.toString();
}
// Join video call with randomly generated roomId
private void connectVideoCall(String roomId) {
Uri roomUri = Uri.parse(APPRTC_URL);
int videoWidth = 0;
int videoHeight = 0;
peerConnectionParameters =
new PeerConnectionClient.PeerConnectionParameters(true,
false,
false,
videoWidth,
videoHeight,
0,
Integer.parseInt(getString(R.string.pref_maxvideobitratevalue_default)),
getString(R.string.pref_videocodec_default),
true,
false,
Integer.parseInt(getString(R.string.pref_startaudiobitratevalue_default)),
getString(R.string.pref_audiocodec_default),
false,
false,
false,
false,
false,
false,
false,
false,
null);
// Create connection client. Use the standard WebSocketRTCClient.
// DirectRTCClient could be used for point-to-point connection
appRtcClient = new WebSocketRTCClient(this);
// Create connection parameters.
roomConnectionParameters =
new AppRTCClient.RoomConnectionParameters(
roomUri.toString(),
roomId,
false,
null);
peerConnectionClient.createPeerConnectionFactory(
getApplicationContext(), peerConnectionParameters, CallActivity.this);
startCall();
}
public void onCallHangUp() {
disconnect();
}
public void onCameraSwitch() {
if (peerConnectionClient != null) {
peerConnectionClient.switchCamera();
}
}
public boolean onToggleMic() {
if (peerConnectionClient != null) {
micEnabled = !micEnabled;
peerConnectionClient.setAudioEnabled(micEnabled);
}
return micEnabled;
}
private void startCall() {
if (appRtcClient == null) {
Log.e(TAG, "AppRTC client is not allocated for a call.");
return;
}
callStartedTimeMs = System.currentTimeMillis();
// Start room connection.
logAndToast(getString(R.string.connecting_to, roomConnectionParameters.roomUrl));
appRtcClient.connectToRoom(roomConnectionParameters);
}
#UiThread
private void callConnected() {
final long delta = System.currentTimeMillis() - callStartedTimeMs;
Log.i(TAG, "Call connected: delay=" + delta + "ms");
if (peerConnectionClient == null || isError) {
Log.w(TAG, "Call is connected in closed or error state");
return;
}
// Enable statistics callback.
peerConnectionClient.enableStatsEvents(true, STAT_CALLBACK_PERIOD);
setSwappedFeeds(false /* isSwappedFeeds */);
}
// Disconnect from remote resources, dispose of local resources, and exit.
private void disconnect() {
activityRunning = false;
remoteProxyRenderer.setTarget(null);
localProxyVideoSink.setTarget(null);
if (appRtcClient != null) {
appRtcClient.disconnectFromRoom();
appRtcClient = null;
}
if (pipRenderer != null) {
pipRenderer.release();
pipRenderer = null;
}
if (fullscreenRenderer != null) {
fullscreenRenderer.release();
fullscreenRenderer = null;
}
if (peerConnectionClient != null) {
peerConnectionClient.close();
peerConnectionClient = null;
}
if (iceConnected && !isError) {
setResult(RESULT_OK);
} else {
setResult(RESULT_CANCELED);
}
finish();
}
private void disconnectWithErrorMessage(final String errorMessage) {
if (!activityRunning) {
Log.e(TAG, "Critical error: " + errorMessage);
disconnect();
} else {
new AlertDialog.Builder(this)
.setTitle(getText(R.string.channel_error_title))
.setMessage(errorMessage)
.setCancelable(false)
.setNeutralButton(R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
disconnect();
}
})
.create()
.show();
}
}
// Log |msg| and Toast about it.
private void logAndToast(String msg) {
Log.d(TAG, msg);
if (logToast != null) {
logToast.cancel();
}
logToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
logToast.show();
}
private void reportError(final String description) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isError) {
isError = true;
disconnectWithErrorMessage(description);
}
}
});
}
// Create VideoCapturer
private VideoCapturer createVideoCapturer() {
final VideoCapturer videoCapturer;
Logging.d(TAG, "Creating capturer using camera2 API.");
videoCapturer = createCameraCapturer(new Camera2Enumerator(this));
if (videoCapturer == null) {
reportError("Failed to open camera");
return null;
}
return videoCapturer;
}
// Create VideoCapturer from camera
private VideoCapturer createCameraCapturer(CameraEnumerator enumerator) {
final String[] deviceNames = enumerator.getDeviceNames();
// First, try to find front facing camera
Logging.d(TAG, "Looking for front facing cameras.");
for (String deviceName : deviceNames) {
if (enumerator.isFrontFacing(deviceName)) {
Logging.d(TAG, "Creating front facing camera capturer.");
VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
if (videoCapturer != null) {
return videoCapturer;
}
}
}
// Front facing camera not found, try something else
Logging.d(TAG, "Looking for other cameras.");
for (String deviceName : deviceNames) {
if (!enumerator.isFrontFacing(deviceName)) {
Logging.d(TAG, "Creating other camera capturer.");
VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
if (videoCapturer != null) {
return videoCapturer;
}
}
}
return null;
}
private void setSwappedFeeds(boolean isSwappedFeeds) {
Logging.d(TAG, "setSwappedFeeds: " + isSwappedFeeds);
this.isSwappedFeeds = isSwappedFeeds;
localProxyVideoSink.setTarget(isSwappedFeeds ? fullscreenRenderer : pipRenderer);
remoteProxyRenderer.setTarget(isSwappedFeeds ? pipRenderer : fullscreenRenderer);
fullscreenRenderer.setMirror(isSwappedFeeds);
pipRenderer.setMirror(!isSwappedFeeds);
}
// -----Implementation of AppRTCClient.AppRTCSignalingEvents ---------------
// All callbacks are invoked from websocket signaling looper thread and
// are routed to UI thread.
private void onConnectedToRoomInternal(final AppRTCClient.SignalingParameters params) {
final long delta = System.currentTimeMillis() - callStartedTimeMs;
signalingParameters = params;
logAndToast("Creating peer connection, delay=" + delta + "ms");
VideoCapturer videoCapturer = null;
if (peerConnectionParameters.videoCallEnabled) {
videoCapturer = createVideoCapturer();
}
peerConnectionClient.createPeerConnection(
localProxyVideoSink, remoteRenderers, videoCapturer, signalingParameters);
if (signalingParameters.initiator) {
logAndToast("Creating OFFER...");
// Create offer. Offer SDP will be sent to answering client in
// PeerConnectionEvents.onLocalDescription event.
peerConnectionClient.createOffer();
} else {
if (params.offerSdp != null) {
peerConnectionClient.setRemoteDescription(params.offerSdp);
logAndToast("Creating ANSWER...");
// Create answer. Answer SDP will be sent to offering client in
// PeerConnectionEvents.onLocalDescription event.
peerConnectionClient.createAnswer();
}
if (params.iceCandidates != null) {
// Add remote ICE candidates from room.
for (IceCandidate iceCandidate : params.iceCandidates) {
peerConnectionClient.addRemoteIceCandidate(iceCandidate);
}
}
}
}
#Override
public void onConnectedToRoom(final AppRTCClient.SignalingParameters params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
onConnectedToRoomInternal(params);
}
});
}
#Override
public void onRemoteDescription(final SessionDescription sdp) {
final long delta = System.currentTimeMillis() - callStartedTimeMs;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (peerConnectionClient == null) {
Log.e(TAG, "Received remote SDP for non-initilized peer connection.");
return;
}
logAndToast("Received remote " + sdp.type + ", delay=" + delta + "ms");
peerConnectionClient.setRemoteDescription(sdp);
if (!signalingParameters.initiator) {
logAndToast("Creating ANSWER...");
// Create answer. Answer SDP will be sent to offering client in
// PeerConnectionEvents.onLocalDescription event.
peerConnectionClient.createAnswer();
}
}
});
}
#Override
public void onRemoteIceCandidate(final IceCandidate candidate) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (peerConnectionClient == null) {
Log.e(TAG, "Received ICE candidate for a non-initialized peer connection.");
return;
}
peerConnectionClient.addRemoteIceCandidate(candidate);
}
});
}
#Override
public void onRemoteIceCandidatesRemoved(final IceCandidate[] candidates) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (peerConnectionClient == null) {
Log.e(TAG, "Received ICE candidate removals for a non-initialized peer connection.");
return;
}
peerConnectionClient.removeRemoteIceCandidates(candidates);
}
});
}
#Override
public void onChannelClose() {
runOnUiThread(new Runnable() {
#Override
public void run() {
logAndToast("Remote end hung up; dropping PeerConnection");
disconnect();
}
});
}
#Override
public void onChannelError(final String description) {
reportError(description);
}
// -----Implementation of PeerConnectionClient.PeerConnectionEvents.---------
// Send local peer connection SDP and ICE candidates to remote party.
// All callbacks are invoked from peer connection client looper thread and
// are routed to UI thread.
#Override
public void onLocalDescription(final SessionDescription sdp) {
final long delta = System.currentTimeMillis() - callStartedTimeMs;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (appRtcClient != null) {
logAndToast("Sending " + sdp.type + ", delay=" + delta + "ms");
if (signalingParameters.initiator) {
appRtcClient.sendOfferSdp(sdp);
} else {
appRtcClient.sendAnswerSdp(sdp);
}
}
if (peerConnectionParameters.videoMaxBitrate > 0) {
Log.d(TAG, "Set video maximum bitrate: " + peerConnectionParameters.videoMaxBitrate);
peerConnectionClient.setVideoMaxBitrate(peerConnectionParameters.videoMaxBitrate);
}
}
});
}
#Override
public void onIceCandidate(final IceCandidate candidate) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (appRtcClient != null) {
appRtcClient.sendLocalIceCandidate(candidate);
}
}
});
}
#Override
public void onIceCandidatesRemoved(final IceCandidate[] candidates) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (appRtcClient != null) {
appRtcClient.sendLocalIceCandidateRemovals(candidates);
}
}
});
}
#Override
public void onIceConnected() {
final long delta = System.currentTimeMillis() - callStartedTimeMs;
runOnUiThread(new Runnable() {
#Override
public void run() {
logAndToast("ICE connected, delay=" + delta + "ms");
iceConnected = true;
callConnected();
}
});
}
#Override
public void onIceDisconnected() {
runOnUiThread(new Runnable() {
#Override
public void run() {
logAndToast("ICE disconnected");
iceConnected = false;
disconnect();
}
});
}
#Override
public void onPeerConnectionClosed() {
}
#Override
public void onPeerConnectionStatsReady(final StatsReport[] reports) {
}
#Override
public void onPeerConnectionError(final String description) {
reportError(description);
}
// Activity interfaces
#Override
public void onStop() {
super.onStop();
activityRunning = false;
if (peerConnectionClient != null) {
peerConnectionClient.stopVideoSource();
}
}
#Override
public void onStart() {
super.onStart();
activityRunning = true;
// Video is not paused for screencapture. See onPause.
if (peerConnectionClient != null) {
peerConnectionClient.startVideoSource();
}
}
#Override
protected void onDestroy() {
Thread.setDefaultUncaughtExceptionHandler(null);
disconnect();
if (logToast != null) {
logToast.cancel();
}
activityRunning = false;
super.onDestroy();
}
private static class ProxyRenderer implements VideoRenderer.Callbacks {
private VideoRenderer.Callbacks target;
#Override
synchronized public void renderFrame(VideoRenderer.I420Frame frame) {
if (target == null) {
Logging.d(TAG, "Dropping frame in proxy because target is null.");
VideoRenderer.renderFrameDone(frame);
return;
}
target.renderFrame(frame);
}
synchronized public void setTarget(VideoRenderer.Callbacks target) {
this.target = target;
}
}
private static class ProxyVideoSink implements VideoSink {
private VideoSink target;
#Override
synchronized public void onFrame(VideoFrame frame) {
if (target == null) {
Logging.d(TAG, "Dropping frame in proxy because target is null.");
return;
}
target.onFrame(frame);
}
synchronized public void setTarget(VideoSink target) {
this.target = target;
}
}
}
You are using a demo signaling server operated by an entity (Google) that does not consider this demo signaling server a production system. The certificate expired a week ago.
Run your own server, instructions can be found here: https://github.com/webrtc/apprtc
I am following the this ExampleMediaController tutorial.
This is VideoControlView.java,
package com.otwar.deepak.video_styling;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Formatter;
import java.util.Locale;
public class VideoControllerView extends FrameLayout {
private static final String TAG = "VideoControllerView";
private MediaPlayerControl mPlayer;
private Context mContext;
private ViewGroup mAnchor;
private View mRoot;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
private OnClickListener mNextListener, mPrevListener;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mFfwdButton;
private ImageButton mRewButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private ImageButton mFullscreenButton;
private Handler mHandler = new MessageHandler(this);
public VideoControllerView(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = null;
mContext = context;
mUseFastForward = true;
mFromXml = true;
Log.i(TAG, TAG);
}
public VideoControllerView(Context context, boolean useFastForward) {
super(context);
mContext = context;
mUseFastForward = useFastForward;
Log.i(TAG, TAG);
}
public VideoControllerView(Context context) {
this(context, true);
Log.i(TAG, TAG);
}
#Override
public void onFinishInflate() {
if (mRoot != null)
initControllerView(mRoot);
}
public void setMediaPlayer(MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
updateFullScreen();
}
/**
* Set the view that acts as the anchor for the control view.
* This can for example be a VideoView, or your Activity's main view.
* #param view The view to which to anchor the controller when it is visible.
*/
public void setAnchorView(ViewGroup view) {
mAnchor = view;
LayoutParams frameParams = new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
/**
* Create the view that holds the widgets that control playback.
* Derived classes can override this to create their own.
* #return The controller view.
* #hide This doesn't work as advertised
*/
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View v) {
mPauseButton = (ImageButton) v.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mFullscreenButton = (ImageButton) v.findViewById(R.id.fullscreen);
if (mFullscreenButton != null) {
mFullscreenButton.requestFocus();
mFullscreenButton.setOnClickListener(mFullscreenListener);
}
mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
if (mFfwdButton != null) {
mFfwdButton.setOnClickListener(mFfwdListener);
if (!mFromXml) {
mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
mRewButton = (ImageButton) v.findViewById(R.id.rew);
if (mRewButton != null) {
mRewButton.setOnClickListener(mRewListener);
if (!mFromXml) {
mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
// By default these are hidden. They will be enabled when setPrevNextListeners() is called
mNextButton = (ImageButton) v.findViewById(R.id.next);
if (mNextButton != null && !mFromXml && !mListenersSet) {
mNextButton.setVisibility(View.GONE);
}
mPrevButton = (ImageButton) v.findViewById(R.id.prev);
if (mPrevButton != null && !mFromXml && !mListenersSet) {
mPrevButton.setVisibility(View.GONE);
}
mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = (TextView) v.findViewById(R.id.time);
mCurrentTime = (TextView) v.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
installPrevNextListeners();
}
/**
* Show the controller on screen. It will go away
* automatically after 3 seconds of inactivity.
*/
public void show() {
show(sDefaultTimeout);
}
/**
* Disable pause or seek buttons if the stream cannot be paused or seeked.
* This requires the control interface to be a MediaPlayerControlExt
*/
private void disableUnsupportedButtons() {
if (mPlayer == null) {
return;
}
try {
if (mPauseButton != null && !mPlayer.canPause()) {
mPauseButton.setEnabled(false);
}
if (mRewButton != null && !mPlayer.canSeekBackward()) {
mRewButton.setEnabled(false);
}
if (mFfwdButton != null && !mPlayer.canSeekForward()) {
mFfwdButton.setEnabled(false);
}
} catch (IncompatibleClassChangeError ex) {
// We were given an old version of the interface, that doesn't have
// the canPause/canSeekXYZ methods. This is OK, it just means we
// assume the media can be paused and seeked, and so we don't disable
// the buttons.
}
}
/**
* Show the controller on screen. It will go away
* automatically after 'timeout' milliseconds of inactivity.
* #param timeout The timeout in milliseconds. Use 0 to show
* the controller until hide() is called.
*/
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
disableUnsupportedButtons();
LayoutParams tlp = new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
mAnchor.addView(this, tlp);
mShowing = true;
}
updatePausePlay();
updateFullScreen();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
}
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
public void hide() {
if (mAnchor == null) {
return;
}
try {
mAnchor.removeView(this);
mHandler.removeMessages(SHOW_PROGRESS);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return true;
}
#Override
public boolean onTrackballEvent(MotionEvent ev) {
show(sDefaultTimeout);
return false;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (mPlayer == null) {
return true;
}
int keyCode = event.getKeyCode();
final boolean uniqueDown = event.getRepeatCount() == 0
&& event.getAction() == KeyEvent.ACTION_DOWN;
if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_SPACE) {
if (uniqueDown) {
doPauseResume();
show(sDefaultTimeout);
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
if (uniqueDown && !mPlayer.isPlaying()) {
mPlayer.start();
updatePausePlay();
show(sDefaultTimeout);
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
if (uniqueDown && mPlayer.isPlaying()) {
mPlayer.pause();
updatePausePlay();
show(sDefaultTimeout);
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
|| keyCode == KeyEvent.KEYCODE_VOLUME_UP
|| keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
// don't show the controls for volume adjustment
return super.dispatchKeyEvent(event);
} else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
if (uniqueDown) {
hide();
}
return true;
}
show(sDefaultTimeout);
return super.dispatchKeyEvent(event);
}
private OnClickListener mPauseListener = new OnClickListener() {
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private OnClickListener mFullscreenListener = new OnClickListener() {
public void onClick(View v) {
doToggleFullscreen();
show(sDefaultTimeout);
}
};
public void updatePausePlay() {
if (mRoot == null || mPauseButton == null || mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPauseButton.setImageResource(R.drawable.ic_media_pause);
} else {
mPauseButton.setImageResource(R.drawable.ic_media_play);
}
}
public void updateFullScreen() {
if (mRoot == null || mFullscreenButton == null || mPlayer == null) {
return;
}
if (mPlayer.isFullScreen()) {
mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_shrink);
}
else {
mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_stretch);
}
}
private void doPauseResume() {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private void doToggleFullscreen() {
if (mPlayer == null) {
return;
}
mPlayer.toggleFullScreen();
}
// There are two scenarios that can trigger the seekbar listener to trigger:
//
// The first is the user using the touchpad to adjust the posititon of the
// seekbar's thumb. In this case onStartTrackingTouch is called followed by
// a number of onProgressChanged notifications, concluded by onStopTrackingTouch.
// We're setting the field "mDragging" to true for the duration of the dragging
// session to avoid jumps in the position in case of ongoing playback.
//
// The second scenario involves the user operating the scroll ball, in this
// case there WON'T BE onStartTrackingTouch/onStopTrackingTouch notifications,
// we will simply apply the updated position without suspending regular updates.
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
mDragging = true;
// By removing these pending progress messages we make sure
// that a) we won't update the progress while the user adjusts
// the seekbar and b) once the user is done dragging the thumb
// we will post one of these messages to the queue again and
// this ensures that there will be exactly one message queued up.
mHandler.removeMessages(SHOW_PROGRESS);
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (mPlayer == null) {
return;
}
if (!fromuser) {
// We're not interested in programmatically generated changes to
// the progress bar's position.
return;
}
long duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
// Ensure that progress is properly updated in the future,
// the call to show() does not guarantee this because it is a
// no-op if we are already showing.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
}
};
#Override
public void setEnabled(boolean enabled) {
if (mPauseButton != null) {
mPauseButton.setEnabled(enabled);
}
if (mFfwdButton != null) {
mFfwdButton.setEnabled(enabled);
}
if (mRewButton != null) {
mRewButton.setEnabled(enabled);
}
if (mNextButton != null) {
mNextButton.setEnabled(enabled && mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setEnabled(enabled && mPrevListener != null);
}
if (mProgress != null) {
mProgress.setEnabled(enabled);
}
disableUnsupportedButtons();
super.setEnabled(enabled);
}
private OnClickListener mRewListener = new OnClickListener() {
public void onClick(View v) {
if (mPlayer == null) {
return;
}
int pos = mPlayer.getCurrentPosition();
pos -= 5000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private OnClickListener mFfwdListener = new OnClickListener() {
public void onClick(View v) {
if (mPlayer == null) {
return;
}
int pos = mPlayer.getCurrentPosition();
pos += 15000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private void installPrevNextListeners() {
if (mNextButton != null) {
mNextButton.setOnClickListener(mNextListener);
mNextButton.setEnabled(mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setEnabled(mPrevListener != null);
}
}
public void setPrevNextListeners(OnClickListener next, OnClickListener prev) {
mNextListener = next;
mPrevListener = prev;
mListenersSet = true;
if (mRoot != null) {
installPrevNextListeners();
if (mNextButton != null && !mFromXml) {
mNextButton.setVisibility(View.VISIBLE);
}
if (mPrevButton != null && !mFromXml) {
mPrevButton.setVisibility(View.VISIBLE);
}
}
}
public interface MediaPlayerControl {
void start();
void pause();
int getDuration();
int getCurrentPosition();
void seekTo(int pos);
boolean isPlaying();
int getBufferPercentage();
boolean canPause();
boolean canSeekBackward();
boolean canSeekForward();
boolean isFullScreen();
void toggleFullScreen();
}
private static class MessageHandler extends Handler {
private final WeakReference<VideoControllerView> mView;
MessageHandler(VideoControllerView view) {
mView = new WeakReference<VideoControllerView>(view);
}
#Override
public void handleMessage(Message msg) {
VideoControllerView view = mView.get();
if (view == null || view.mPlayer == null) {
return;
}
int pos;
switch (msg.what) {
case FADE_OUT:
view.hide();
break;
case SHOW_PROGRESS:
pos = view.setProgress();
if (!view.mDragging && view.mShowing && view.mPlayer.isPlaying()) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 1000 - (pos % 1000));
}
break;
}
}
}
}
My videoPlayerActivity.java
package com.otwar.deepak.video_styling;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import java.io.IOException;
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
controller = new VideoControllerView(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
player.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
#Override
public int getDuration() {
return player.getDuration();
}
#Override
public boolean isPlaying() {
return player.isPlaying();
}
#Override
public void pause() {
player.pause();
}
#Override
public void seekTo(int i) {
player.seekTo(i);
}
#Override
public void start() {
player.start();
}
#Override
public boolean isFullScreen() {
return false;
}
#Override
public void toggleFullScreen() {
}
// End VideoMediaController.MediaPlayerControl
}
I have small problem. My problem is auto refresh to list messages.
How can instantly check data such as WhatsApp ?
If you would like to automatically update data came from.
I do not know exactly how I can do , so I'm waiting for your help .
Code
MessagingActivity.java
package com.socialnetwork.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.socialnetwork.R;
import com.socialnetwork.adapters.MessagesAdapter;
import com.socialnetwork.animation.ViewAudioProxy;
import com.socialnetwork.api.APIService;
import com.socialnetwork.api.ChatAPI;
import com.socialnetwork.api.UsersAPI;
import com.socialnetwork.data.MessagesItem;
import com.socialnetwork.data.userItem;
import com.socialnetwork.helpers.M;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MessagingActivity extends AppCompatActivity implements OnClickListener {
public Intent mIntent = null;
private MediaRecorder recorder = null;
private String outFile = null;
private TextView recordTimeText;
private ImageButton audioSendButton;
private View recordPanel;
private View slideText;
private float startedDraggingX = -1;
private float distCanMove = dp(80);
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private Timer timer;
public int RECIPIENT_ID = 0,
CONVERSATION_ID = 0;
public LinearLayoutManager layoutManager;
private EditText messageField;
private String messageBody, USERNAME;
private MessagesAdapter messageAdapter;
private List<MessagesItem> mMessages = new ArrayList<MessagesItem>();
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
Bundle data = intent.getBundleExtra("data");
if (Integer.parseInt(data.getString("ownerID")) == RECIPIENT_ID) {
MessagesItem newMsg = new MessagesItem();
newMsg.setOwnerName(data.getString("ownerName"));
newMsg.setId(Integer.parseInt(data.getString("id")));
newMsg.setMessage(data.getString("message"));
newMsg.setDate(data.getString("date"));
newMsg.setOwnerUsername(data.getString("ownerUsername"));
newMsg.setOwnerPicture(data.getString("ownerPicture"));
newMsg.setOwnerID(Integer.parseInt(data.getString("ownerID")));
newMsg.setConversationID(Integer.parseInt(data.getString("conversationID")));
addMessage(newMsg);
} else {
Intent resultIntent = new Intent(MessagingActivity.this, MessagingActivity.class);
resultIntent.putExtra("data", intent);
M.showNotification(MessagingActivity.this, resultIntent,
data.getString("ownerUsername"),
data.getString("message"),
Integer.parseInt(data.getString("conversationID")));
}
}
};
private RecyclerView messagesList;
private LinearLayout attachLayout;
private RelativeLayout recordPannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
setContentView(R.layout.messaging);
initializer();
if (getIntent().hasExtra("conversationID")) {
CONVERSATION_ID = getIntent().getExtras().getInt("conversationID");
}
if (getIntent().hasExtra("recipientID")) {
RECIPIENT_ID = getIntent().getExtras().getInt("recipientID");
}
getUser();
getMessages();
}
}
public void initializer() {
messagesList = (RecyclerView) findViewById(R.id.listMessages);
messageAdapter = new MessagesAdapter(this, mMessages);
messagesList.setAdapter(messageAdapter);
//
layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
messagesList.setLayoutManager(layoutManager);
messageField = (EditText) findViewById(R.id.messageField);
attachLayout = (LinearLayout) findViewById(R.id.attachLayout);
recordPannel = (RelativeLayout) findViewById(R.id.record_pannel);
recordPanel = findViewById(R.id.record_panel);
recordTimeText = (TextView) findViewById(R.id.recording_time_text);
slideText = findViewById(R.id.slideText);
audioSendButton = (ImageButton) findViewById(R.id.chat_audio_send_button);
TextView textView = (TextView) findViewById(R.id.slideToCancelTextView);
textView.setText("Slide To Cancel");
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.attachBtn).setOnClickListener(this);
findViewById(R.id.sendBtn).setOnClickListener(this);
findViewById(R.id.micBtn).setOnClickListener(this);
audioSendButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
startRecording();
audioSendButton.getParent()
.requestDisallowInterceptTouchEvent(true);
recordPanel.setVisibility(View.VISIBLE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP
|| motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
startedDraggingX = -1;
stopRecording();
recordPannel.setVisibility(View.GONE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
float x = motionEvent.getX();
if (x < -distCanMove) {
stopRecording();
}
x = x + ViewAudioProxy.getX(audioSendButton);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
if (startedDraggingX != -1) {
float dist = (x - startedDraggingX);
params.leftMargin = dp(30) + (int) dist;
slideText.setLayoutParams(params);
float alpha = 1.0f + dist / distCanMove;
if (alpha > 1) {
alpha = 1;
} else if (alpha < 0) {
alpha = 0;
}
ViewAudioProxy.setAlpha(slideText, alpha);
}
if (x <= ViewAudioProxy.getX(slideText) + slideText.getWidth()
+ dp(30)) {
if (startedDraggingX == -1) {
startedDraggingX = x;
distCanMove = (recordPanel.getMeasuredWidth()
- slideText.getMeasuredWidth() - dp(48)) / 2.0f;
if (distCanMove <= 0) {
distCanMove = dp(80);
} else if (distCanMove > dp(80)) {
distCanMove = dp(80);
}
}
}
if (params.leftMargin > dp(30)) {
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
}
}
view.onTouchEvent(motionEvent);
return true;
}
});
}
private void getUser() {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(RECIPIENT_ID, new Callback<userItem>() {
#Override
public void success(userItem userItem, retrofit.client.Response response) {
if (userItem.getName() != null) {
getSupportActionBar().setTitle(userItem.getName());
} else {
getSupportActionBar().setTitle(userItem.getUsername());
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
messageAdapter.stop();
}
public void getMessages() {
M.showLoadingDialog(this);
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.getMessages(CONVERSATION_ID, RECIPIENT_ID, 1, new Callback<List<MessagesItem>>() {
#Override
public void success(List<MessagesItem> messagesItems, Response response) {
mMessages = messagesItems;
messageAdapter.setMessages(messagesItems);
M.hideLoadingDialog();
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.L(getString(R.string.ServerError));
}
});
}
private void sendMessage() {
messageBody = messageField.getText().toString().trim();
if (!messageBody.isEmpty()) {
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.addMessage(messageBody, CONVERSATION_ID, RECIPIENT_ID, new Callback<MessagesItem>() {
#Override
public void success(MessagesItem messagesItem, Response response) {
if (messagesItem != null) {
mMessages.add(messagesItem);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
messageField.setText("");
} else {
M.T(MessagingActivity.this, getString(R.string.SomethingWentWrong));
}
}
#Override
public void failure(RetrofitError error) {
M.T(MessagingActivity.this, getString(R.string.ServerError));
}
});
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.attachBtn) {
if (attachLayout.getVisibility() == View.GONE) {
attachLayout.setVisibility(View.VISIBLE);
} else {
attachLayout.setVisibility(View.GONE);
}
if (recordPannel.getVisibility() == View.VISIBLE) {
recordPannel.setVisibility(View.GONE);
}
} else if (v.getId() == R.id.sendBtn) {
sendMessage();
} else if (v.getId() == R.id.micBtn) {
attachLayout.setVisibility(View.GONE);
recordPannel.setVisibility(View.VISIBLE);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter("update_messages_list"));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mMessageReceiver);
}
public void addMessage(MessagesItem newMsg) {
mMessages.add(newMsg);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
}
private void startRecording() {
try {
startRecordingAudio();
} catch (IOException e) {
e.printStackTrace();
}
startTime = SystemClock.uptimeMillis();
timer = new Timer();
MyTimerTask myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 1000, 1000);
vibrate();
}
private void stopRecording() {
if (timer != null) {
timer.cancel();
}
if (recordTimeText.getText().toString().equals("00:00")) {
return;
}
recordTimeText.setText("00:00");
vibrate();
Toast.makeText(getApplicationContext(), "Stop Recording", Toast.LENGTH_SHORT).show();
stopRecordingAudio();
}
public void startRecordingAudio() throws IOException {
Toast.makeText(getApplicationContext(), "Start Recording...", Toast.LENGTH_SHORT).show();
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH.mm.ss");
String fileName = "audio_" + timeStampFormat.format(new Date())
+ ".mp3";
outFile = "/sdcard/";// Environment.getExternalStorageDirectory().getAbsolutePath();
stopRecordingAudio();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outFile + fileName);
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
recorder.prepare();
recorder.start();
}
public void stopRecordingAudio() {
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private void vibrate() {
// TODO Auto-generated method stub
try {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int dp(float value) {
return (int) Math.ceil(1 * value);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
final String hms = String.format(
"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(updatedTime)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(updatedTime)),
TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime)));
long lastsec = TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime));
System.out.println(lastsec + " hms " + hms);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (recordTimeText != null)
recordTimeText.setText(hms);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
}
}
MessagesFragment.java
public class MessagesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public RecyclerView conversationList;
public ConversationsAdapter mConversationsAdapter;
public List<ConversationItem> mConversations = new ArrayList<ConversationItem>();
public Intent mIntent = null;
public int currentPage = 1;
public LinearLayoutManager layoutManager;
private View mView;
private SwipeRefreshLayout mSwipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_messages, container, false);
conversationList = (RecyclerView) mView
.findViewById(R.id.conversationsList);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_messages);
initializeView();
conversationList.setOnScrollListener(new HidingScrollListener(layoutManager) {
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onLoadMore(int currentPage) {
setCurrentPage(currentPage);
getConversations();
}
});
mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeMessages);
mSwipeRefreshLayout.setOnRefreshListener(this);
getConversations();
return mView;
}
public void initializeView() {
mConversationsAdapter = new ConversationsAdapter(getActivity(),
mConversations);
conversationList.setAdapter(mConversationsAdapter);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
conversationList.setLayoutManager(layoutManager);
}
public void getConversations() {
M.showLoadingDialog(getActivity());
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(getActivity()));
mChatAPI.getConversations(getCurrentPage(), new Callback<List<ConversationItem>>() {
#Override
public void success(List<ConversationItem> conversationItems, retrofit.client.Response response) {
M.L(response.getBody().mimeType());
mConversationsAdapter.setConversations(conversationItems);
M.hideLoadingDialog();
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
}
});
}
#Override
public void onRefresh() {
setCurrentPage(1);
getConversations();
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
WhatsApp is not instant check. It's is more like:
Screen off, check 10x after 30s, next 10x after 1m, next 3x after 5m and so on. and start again if the screen turns off again. WhatsApp is checkin in the background also when you close the app. They are using a service.
I have an activity with uses onOptionsItemSelected(MenuItem item) method in FolderActivity and I want to call this method on another activity (MainActivity)
the main activity uses CMU Sphinx - Speech Recognition Toolkit.
I need to call some methods from FolderActivity to MainActivity.
package com.evolution.filemanager.folders;
import static android.widget.Toast.makeText;
import java.io.File;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.evolution.filemanager.FileManagerApplication;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.clipboard.Clipboard;
import com.evolution.filemanager.clipboard.Clipboard.ClipboardListener;
import com.evolution.filemanager.clipboard.ClipboardFileAdapter;
import com.evolution.filemanager.favourites.FavouritesManager;
import com.evolution.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.evolution.filemanager.nav_drawer.NavDrawerAdapter;
import com.evolution.utils.FontApplicator;
import com.evolution.utils.ListViewUtils;
import edu.cmu.pocketsphinx.demo.R;
public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
public static class FolderNotOpenException extends Exception
{
}
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
public static Activity FOLDERACTIVITY;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_folder);
setupDrawers();
Clipboard.getInstance().addListener(this);
FOLDERACTIVITY = this;
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
#Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
#Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
public void setActionbarVisible(boolean visible)
{
ActionBar actionBar = getActionBar();
if (actionBar == null) return;
if (visible)
{
actionBar.show();
setSystemBarTranslucency(false);
}
else
{
actionBar.hide();
setSystemBarTranslucency(true);
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void setSystemBarTranslucency(boolean translucent)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
if (translucent)
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else
{
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setAttributes(params);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;
#Override
public void onDrawerOpened(View drawerView)
{
makeText(getApplicationContext(), "drawer open", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
makeText(getApplicationContext(), "drawer close", Toast.LENGTH_SHORT).show();
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
drawerLayout.setFocusableInTouchMode(false);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
#Override
public void onBackPressed()
{
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else if (drawerLayout.isDrawerOpen(GravityCompat.END))
drawerLayout.closeDrawer(GravityCompat.END);
else
super.onBackPressed();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
// add listview header to push items below the actionbar
ListView navListView = (ListView) findViewById(R.id.listNavigation);
ListViewUtils.addListViewPadding(navListView, this, true);
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
ListViewUtils.addListViewHeader(clipboardListView, this);
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
makeText(getApplicationContext(), "unsa ni?", Toast.LENGTH_SHORT).show();
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
public File getCurrentFolder() throws FolderNotOpenException
{
FolderFragment folderFragment = getFolderFragment();
if (folderFragment == null)
throw new FolderNotOpenException();
else return folderFragment.currentDir;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerAdapter.NavDrawerItem item = (NavDrawerAdapter.NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
FolderFragment folderFragment = getFolderFragment();
if (folderFragment != null)
{
// TODO: paste single file
}
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
#Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
#Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event)
{
Log.d("Key Long Press", event.toString());
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
return true;
}
else return super.onKeyLongPress(keyCode, event);
}
}
and the activity where I want to call
package edu.cmu.pocketsphinx.demo;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.folders.FolderActivity;
import com.evolution.utils.DataClearer;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
public class MainActivity extends Activity implements
RecognitionListener {
public AnimationDrawable rocketAnimation;
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "frost";
private static final String GO_BACK = "back";
private static final String PREVIOUS = "previous";
private static final String OPEN_FILE_MANAGER = "open file manager";
private static final String OPEN_ABOUT = "open about";
private static final String OPEN_MUSIC = "open music";
private static final String OPEN_PICTURES = "open pictures";
private static final String OPEN_VIDEOS = "open videos";
private static final String SHOW_COMMANDS = "show commands";
private static final String CLOSE_FILE_MANAGER = "close file manager";
private static final String CLOSE_ABOUT = "close about";
private static final String CLOSE_MUSIC = "close music";
private static final String CLOSE_PICTURES = "close pictures";
private static final String CLOSE_VIDEOS = "close videos";
private static final String CLOSE_COMMANDS = "close commands";
private static final String SHOW_DRAWER = "show drawer";
private static final String HIDE_DRAWER = "hide drawer";
public static boolean isOPEN_FILE_MANAGER = false;
private static boolean isOPEN_ABOUT = false;
private static boolean isOPEN_MUSIC = false;
private static boolean isOPEN_PICTURES = false;
private static boolean isOPEN_VIDEOS = false;
private static boolean isSHOW_COMMANDS = false;
private static boolean isSHOW_DRAWER = false;
private static String MENU_CAPTION;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
ImageView rocketImage = (ImageView) findViewById(R.id.imageViewAnim);
rocketImage.setBackgroundResource(R.drawable.heart_animation);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
TextView tv = ((TextView) findViewById(R.id.caption_text));
if (text.equals(KEYPHRASE))
{
switchSearch(MENU_SEARCH);
rocketAnimation.start();
}
else if (text.equals(OPEN_FILE_MANAGER))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , FolderActivity.class);
startActivity(intent);
isOPEN_FILE_MANAGER = true;
}
else if (text.equals(CLOSE_FILE_MANAGER))
{
if(isOPEN_FILE_MANAGER == true)
{
switchSearch(KWS_SEARCH);
FolderActivity.FOLDERACTIVITY.finish();
isOPEN_FILE_MANAGER = false;
}
}
else if (text.equals(SHOW_COMMANDS))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , Commands.class);
startActivity(intent);
isSHOW_COMMANDS = true;
}
else if (text.equals(CLOSE_COMMANDS))
{
if(isSHOW_COMMANDS == true)
{
switchSearch(KWS_SEARCH);
Commands.SHOWCOMMANDS.finish();
}
}
else if (text.equals(OPEN_PICTURES))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , AboutActivity.class);
startActivity(intent);
}
else if(text.equals(OPEN_ABOUT))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent(PocketSphinxActivity.this, AboutActivity.class);
startActivity(intent);
isOPEN_ABOUT = true;
}
else if(text.equals(CLOSE_ABOUT))
{
if (isOPEN_ABOUT == true)
{
switchSearch(KWS_SEARCH);
AboutActivity.ABOUTACTIVITY.finish();
}
}
else if(text.equals(GO_BACK) || text.equals(PREVIOUS))
{
if(isOPEN_FILE_MANAGER == true )
{
FolderActivity.FOLDERACTIVITY//where i want to call onOptionsItemSelected
switchSearch(KWS_SEARCH);
}
}
else
{
switchSearch(KWS_SEARCH);
((TextView) findViewById(R.id.result_text)).setText(text);
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName())
|| OPEN_FILE_MANAGER.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/menu.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this); //clear cache to minimize the app size
DataClearer.getInstance().clearApplicationData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
the FolderActivity runs on top of the MainActivty but the voice recognition in MainActivity is still active and I want the voice itself do some manipulation in the FolderActivity
Here's a few suggestions:
Have FolderActivity register a BroadcastReceiver as a listener for a certain Intent. When MainActivity wants to do something in FolderActivity, it can send a broadcast Intent which will be seen by the BroadcastReceiver in FolderActivity, which can then call the appropriate method in the `Activity.
When MainActivity wants to do something in FolderActivity, it can launch FolderActivity again using an Intent with flag Intent.FLAG_ACTIVITY_SINGLE_TOP and some "extra" that describes what FolderActivity should do. In FolderActivity override onNewIntent(), read the passed Intent parameter and use it to determine what method to call in FolderActivity. Because the Activity was launched withIntent.FLAG_ACTIVITY_SINGLE_TOP, Android won't create a new instance of the Activity, it will just callonNewIntent()` on the existing instance.
Have FolderActivity set a public static variable of type Activity to a reference to itself in onCreate(). MainActivity can then call a method on FolderActivity by doing something like FolderActivity.activityReference.doSomething()
Method 3 is not the preferred method, since you need to make sure that you set the public static variable to null in FolderActivity.onDestroy() and there are other concerns (timing issues, memory leaks, etc.) that need to be dealt with properly.
NOTE: You probably don't want to call onOptionsItemSelected() directly. This method is called by the Android framework when an options item is selected by the user. You should call directly the method that actually does something, not this framework callback method.