how to call onOptionsItemSelected on a different activity - java

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.

Related

How can we add referer in the exoplayer android java

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.

How to call another activity by menuitem? Android Studio Error: method call expected

I am completely new to Android Studio and just learned Object-oriented programming. My project requires me to build something on open-source code. I added a new menu item to a menu and want to start another activity once the user clicks the menu item with id: plot. I followed a recipe on the internet but got an error with it. It said 'method call expected' which means Terminal Fragment may be a method. I got confused, as I thought it is a class(an activity). Could anyone give me instructions to start an activity (turn to the next page with a different activity) in this case? What will be the simplest way to do this? Much Appreciated.
I added this in onOptionsItemSelected(MenuItem item).
if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}
TerminalFragment.java (entire code)
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {
receive(data);
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
menu_terminal.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/plot"
android:title="PLOTDATA"
app:showAsAction="always" />
<item
android:id="#+id/clear"
android:icon="#drawable/ic_delete_white_24dp"
android:title="Clear"
app:showAsAction="always" />
<item
android:id="#+id/newline"
android:title="Newline"
app:showAsAction="never" />
<item
android:id="#+id/hex"
android:title="HEX Mode"
android:checkable="true"
app:showAsAction="never" />
</menu>
Here, TerminalFragment is a fragment, not an activity. And so, instead of using TerminalFragment.this in new Intent(), you should use getActivity().
So, the final code would look something like this:
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
You can also check this: Intent from Fragment to Activity

Cannot have a steady connection with my Bluetooth smartwatch in android studio

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();
}
}```

How stop text to speech in Base adapter

I have a custom ListView with BaseAdapter. In this custom ListView when a user clicks on any particular text, it speaks the text but the problem is that when any user clicks on the back button how to stop this text from the BaseAdapter. I know how to stop from an Activity but don't know how to stop from BaseAdapter when the user presses back button. Here is my code:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.Inflater;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
public class BaseAdopter extends BaseAdapter implements TextToSpeech.OnInitListener{
public BaseAdopter(Context context, List<String> versenumber, List<String> verseid, List<String> verselist, List<String> refernce) {
this.context = context;
this.versenumber = versenumber;
this.verseid = verseid;
this.verselist = verselist;
this.refernce = refernce;
}
ALLVERSE allverse;
ArrayList<String> colors;
private Context context;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
#Override
public int getCount() {
return versenumber.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.versedisplayrow,parent,false);
textToSpeech = new TextToSpeech(context, this);
final TextView verseno;
final TextView verselistview;
ImageView share;
ToggleButton addfavoruite;
ImageView speakverse;
final LinearLayout linearLayout;
verseno=(TextView)view.findViewById(R.id.versenumber);
verseno.setText(versenumber.get(position));
verselistview=(TextView)view.findViewById(R.id.verse);
verselistview.setText(verselist.get(position));
addfavoruite=(ToggleButton)view.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)view.findViewById(R.id.layout);
share=(ImageView)view.findViewById(R.id.share);
speakverse=(ImageView)view.findViewById(R.id.speak);
if(DefaultSettings.nightmode(context)){
linearLayout.setBackgroundColor(Color.parseColor("#363437"));
verselistview.setTextColor(Color.parseColor("#ffffff"));
verseno.setTextColor(Color.parseColor("#ffffff"));
}
speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
singleverse(verselist.get(position).toString());
}
});
int a=position+1;
colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
SharedPreferences sharedPreferences=context.getSharedPreferences("DATA",MODE_PRIVATE);
int getverse=sharedPreferences.getInt("versenumber",1);
if(a==getverse){
if(DefaultSettings.highlight(context)){
DefaultSettings.color(context);
linearLayout.setBackgroundColor(DefaultSettings.colorpicked);
}
}
if(Checkisfavourite("favourite","id",verseid.get(position)))
{
if(verseid.get(position).equals(verseid.get(position))){
addfavoruite.setChecked(true);
}else {
addfavoruite.setChecked(false);
}
}
addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Toasty.success(context, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}
else {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(context, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(context, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position) +
+'\n' +'\n' +'\n' +"https://play.google.com/store/apps/details?id=bible.swordof.God");
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
});
/* linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("verseid",colors.get(position));
final long check=mDb.insert("highlight",null,contentValues);
//id get
//postion
//Toast.makeText(activity, ""+getItemId(position), Toast.LENGTH_SHORT).show();
ColorPicker colorPicker = new ColorPicker(context);
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
linearLayout.setBackgroundColor(Color.parseColor(colors.get(position)));
}
#Override
public void onCancel() {
}
}).show();
return false;
}
});
*/
return view;
}
public boolean Checkisfavourite(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public boolean colorcheck(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void singleverse(String text) {
DefaultSettings.speed(context);
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void stop(){
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
}
The main problem is that your TextToSpeech object belongs to your BaseAdapter when it should belong to the parent activity.
Instead of housing it in the adapter and calling speak on it every time the user clicks an item, I would instead house it in the parent activity and use an "interface callback" that sends a message to the parent when the user clicks an item, sending back the string to speak. This callback relationship works the exact same way as the TextToSpeech.OnInitListener callback that you're already using.
Once the TTS belongs to the parent activity, you can use the activity lifecycle functions to control the shutdown of the TTS like normal.
If you study and understand the following, you should be able to merge it into your code and get a working solution:
Make these changes to your custom BaseAdapter:
// Remove the TextToSpeech object from this class.
public class MyBaseAdapter {
// add this interface definition to your adapter
public interface SpeechClickSubscriber {
void stringNeedsToBeSpoken(String verse);
}
// add this property (the subscriber)
private SpeechClickSubscriber speechClickSubscriber;
// *add* this functionality to your adapter's existing constructor
MyBaseAdapter(SpeechClickSubscriber parent) {
speechClickSubscriber = parent;
}
//...
// change this section of code in your getView() method
speakverse.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
// change this...
// singleverse(verselist.get(position).toString());
// to this:
speechClickSubscriber.stringNeedsToBeSpoken(verselist.get(position).toString());
}
});
// ...
}
Make these changes to your MainActivity (or whatever your parent activity is):
// add the SpeechClickSubscriber implementation
public class MainActivity extends AppCompatActivity implements MyBaseAdapter.SpeechClickSubscriber, TextToSpeech.OnInitListener {
MyBaseAdapter adapter;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// using app context is better and less error prone.
textToSpeech = new TextToSpeech(getApplicationContext(), this);
}
// *add* this method to this activity (this is the answer to your question)
#Override
protected void onStop() {
super.onStop();
stopTTS();
}
// use this method as your "onStart()" method...
// this will help prevent any user input processing until the tts is initialized.
private void start_Activity_Because_TTS_Has_Initialized() {
adapter = new MyBaseAdapter(this);
}
// *MOVE* this method from your base adapter to this (parent) activity:
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
// *move* and *rename* this method from your adapter to the parent activity:
// from:
/*
private void singleverse(String text) {
DefaultSettings.speed(context);
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} */
// to:
#Override
public void stringNeedsToBeSpoken(String verse) {
Log.i("XXX","stringNeedsToBeSpoken() was called because the user clicked an item.");
Log.i("XXX","This method is being called because this activity subscribes to the callback we created and added to our base adapter.");
//DefaultSettings.speed(context); // <----------------- I don't know what this does.
// I'm assuming that DefaultSettings is a static class you have made.
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(verse, TextToSpeech.QUEUE_FLUSH, null);
}
public void stopTTS(){
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
}

How to auto refresh to list messages?

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.

Categories