WearOS onGenericMotionListener not called - java

I am trying to catch the action when I rotate my bezel on my Samsung Galaxy Watch 4, but it never "runs".
Here is my code:
findViewById(R.id.Badtunna).setOnGenericMotionListener(new View.OnGenericMotionListener() {
#Override
public boolean onGenericMotion(View view, MotionEvent motionEvent) {
System.out.println("GUM");
if(motionEvent.getAction() == MotionEvent.ACTION_SCROLL &&
motionEvent.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)) {
System.out.println("BUBBEL");
return true;
}
return false;
}
});
My view is a normal TextView:
<TextView
android:id="#+id/Badtunna"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Badtunna" />
Here is my onCreate() in MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Add all the domoticz devices
domoticz_devices.put(766, "idx_766");
domoticz_devices.put(17, "idx_17");
findViewById(R.id.Skymningssensor).requestFocus();
findViewById(R.id.Skymningssensor).setOnGenericMotionListener(new View.OnGenericMotionListener() {
#Override
public boolean onGenericMotion(View view, MotionEvent motionEvent) {
System.out.println("GUM");
if(motionEvent.getAction() == MotionEvent.ACTION_SCROLL &&
motionEvent.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)) {
System.out.println("BUBBEL");
return true;
}
return false;
}
});
TextView idx_17_button = findViewById(R.id.idx_17);
idx_17_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
toggleDomoticzDevice(17, "idx_17");
} catch (IOException e) {
e.printStackTrace();
}
}
});
TextView idx_657_button = findViewById(R.id.idx_657);
idx_657_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
toggleDomoticzDevice(657, "idx_657");
} catch (IOException e) {
e.printStackTrace();
}
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
for (Integer i : domoticz_devices.keySet()) {
getDomoticzDeviceAndSetTextview(i, domoticz_devices.get(i));
}
handler.postDelayed(this, delay);
}
}, delay);
}
When focus is "working" should the keyboard pop up?
I have also updated my TextView and added focusable:true and focusableintouchmode:true
Thanks in advance!
Best regards Max

Docs here
https://developer.android.com/training/wearables/user-input/rotary-input#custom-scrolling
Likely issue is focus
Remember to make sure your view gains focus, otherwise the events will not come through.
https://developer.android.com/training/wearables/user-input/rotary-input#custom-scrolling
By default, launching an activity or even tapping on a view does not give it focus, even if it is focusable. To give your view focus, the view must use the tag or manually call View.requestFocus().

Related

How to automatically Click a Button in Android Every Second

How to automatically Click a Button in Android after a 5 second delay
I tried with the codes that are entered in the link but my application has crashed
My codes;
public class MainActivity extends AppCompatActivity {
Button button;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
Thread timer = new Thread() {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
button.performClick();
}
}
};
timer.start();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
button.performClick();
}
}, 1000);
}
public void buttonClick() {
button=(Button) findViewById(R.id.button);
text=(TextView) findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random s=new Random();
int number=s.nextInt(3);
switch (number)
{case 1:text.setText("1");
break;
case 2: text.setText("2");
break;
}
}
});
}
}
Logcat Error
You need to use
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
to avoid this error.
Please check Android "Only the original thread that created a view hierarchy can touch its views."
Also you can just use the Handler to perform the button click after a specified amount of time, no need to use the timer.
This is more simpler method to run every second. you dont need to trigger the button. just call the method you want to execute
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
Runnable runnable = new Runnable(){
#Override
public void run() {
buttonClick();
if(handler!=null)
handler.postDelayed(runnable, 1000);
}
}
handler.postDelayed(runnable, 1000);
}

onBackPressed() finishes my Activity

In my project I have just one Activity that have View.
I think that it has two View that switch the View. The first View is my home that has one Button named "play" . when You click play Button in goes to the second View. Second View is my game.
And now my problem is that when I want to use onBackPressed() method in the second View, it closes the Activity. and onBackPressed() method do the same in both View.
How to handle onBackPressed() method in second View that return to the first View.
How to switch the View in onBackPressed()?
I am new with Android and now I really confused.
any suggestion? or any key word to search to solve my problem.
here is my code:
public class PTPlayer extends Cocos2dxActivity {
static Splash splash;
public static AppList appList;
static Noti_Queue noti_queue;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("----------", "onActivityResult: request: " + requestCode + " result: " + resultCode);
if (requestCode == PTServicesBridge.RC_SIGN_IN) {
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (appList == null) {
appList = new AppList(this);
appList.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
}
#Override
public void onNativeInit() {
initBridges();
}
private void initBridges() {
PTStoreBridge.initBridge(this);
PTServicesBridge.initBridge(this, getString(R.string.app_id));
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kRevMob")) {
PTAdRevMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAdMob") || PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdAdMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAppLovin")) {
PTAdAppLovinBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kLeadBolt")) {
PTAdLeadBoltBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kVungle")) {
PTAdVungleBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kPlayhaven")) {
PTAdUpsightBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kMoPub")) {
PTAdMoPubBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdFacebookBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kHeyzap")) {
PTAdHeyzapBridge.initBridge(this);
}
}
#Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
glSurfaceView.setEGLConfigChooser(8, 8, 8, 0, 0, 0);
return glSurfaceView;
}
static {
System.loadLibrary("player");
}
#Override
protected void onResume() {
super.onResume();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onResume(this);
}
}
#Override
protected void onStart() {
super.onStart();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStart(this);
}
}
#Override
protected void onStop() {
super.onStop();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStop(this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
}
here i think that in my second view:
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxActivity.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private Cocos2dxGLSurfaceView mGLSurfaceView;
private Cocos2dxHandler mHandler;
private static Context sContext = null;
public static Context getContext() {
return sContext;
}
// ===========================================================
// Constructors
// ===========================================================
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sContext = this;
this.mHandler = new Cocos2dxHandler(this);
this.init();
Cocos2dxHelper.init(this, this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
protected void onResume() {
super.onResume();
Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume();
}
#Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
this.mGLSurfaceView.onPause();
}
#Override
public void showDialog(final String pTitle, final String pMessage) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
this.mHandler.sendMessage(msg);
}
#Override
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
this.mHandler.sendMessage(msg);
}
#Override
public void runOnGLThread(final Runnable pRunnable) {
this.mGLSurfaceView.queueEvent(pRunnable);
}
// ===========================================================
// Methods
// ===========================================================
public void init() {
// FrameLayout
ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
FrameLayout framelayout = new FrameLayout(this);
framelayout.setLayoutParams(framelayout_params);
// Cocos2dxEditText layout
ViewGroup.LayoutParams edittext_layout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
this.mGLSurfaceView = this.onCreateView();
// Switch to supported OpenGL (ARGB888) mode on emulator
if (isAndroidEmulator())
this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);
this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
RelativeLayout relativeLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
relativeLayout.setLayoutParams(params);
//AdView adad = new AdView(this);
ClickBanner_CLickYab_Holder adad = new ClickBanner_CLickYab_Holder(this);
RelativeLayout.LayoutParams adad_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
adad_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// adad.setToken(getString(R.string.adad_token));
adad.setLayoutParams(adad_params);
Button myButton = new Button(this);
myButton.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton.setLayoutParams(adad_params1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
Button myButton1 = new Button(this);
myButton1.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton1.setLayoutParams(adad_params2);
myButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
relativeLayout.addView(this.mGLSurfaceView);
relativeLayout.addView(adad);
relativeLayout.addView(myButton);
relativeLayout.addView(myButton1);
ClickBanner_CLickYab_Holder.setTestMode();
setContentView(relativeLayout);
}
public Cocos2dxGLSurfaceView onCreateView() {
return new Cocos2dxGLSurfaceView(this);
}
private final static boolean isAndroidEmulator() {
String model = Build.MODEL;
Log.d(TAG, "model=" + model);
String product = Build.PRODUCT;
Log.d(TAG, "product=" + product);
boolean isEmulator = false;
if (product != null) {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
Log.d(TAG, "isEmulator=" + isEmulator);
return isEmulator;
}
}
you must use of Override Method for when back button pressed
if you want to stay on currnt activity use like this
#Override
public void onBackPressed() {
return;
}
if you want to use double click to exit and one click to stay you can use like this
first define a variable for double click
boolean doubleBackToExit = false;
and the Override backbutton method
#Override
public void onBackPressed() {
if (doubleBackToExit) {
//on double back button pressed
return;
}
this.doubleBackToExit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit=false;
}
}, 2000);
}
Then do this.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(MainActivityPhase2.this, GlobalSearch.class);
startActivity(intent);
finish();
}
Just don't call the super.onBackPressed() everytime.
#Override
public void onBackPressed() {
if (isFirstView()) {
super.onBackPressed();
} else {
switchToFirstView();
}
Call in only when there isn't any last view available. Or where you want to close the App. The code will finish your activity when you are on the first activity. And switch to first activity if you are on second activity.
Just replace my methods as per your code.
Overriding onBackPressed() of the activity and provide your screen where you want to go.
onBackpressed() check which is the current view you are showing and according to move to the first view.
in your second class Cocos2dxActivity, place this code.
#Override
public void onBackPressed() {
this.finish();
}
If you have just one activity with two View you can use Fragments.
Using Fragments, Activity.OnBackPressed() will remove last fragment in the stack and you can resolve your problem.
So, in the activity you have to put a container in xml layout file:
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:clickable="true" android:layout_height="match_parent"/>
In the Activity java file:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourHomeFragment())
.commit();
So to add second Fragment you can use this code:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
Pay attention: you can call this code or in YourHomeFragment class (into button clickListener) or in your Activity (using a callback system). For example:
In YourHomeFragment -->
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
}
});
In this way, you have to declare two layout xml file for fragments and one for Activity.
List of java and relative xml files:
MainActivity.java
activity_main.xml
YourHomeFragment.java
fragment_your_home.xml <-- insert here your first View
YourPlayFragment.java
fragment_your_play.xml <-- play view

onTouchEvent works on one page but it doesn't work on another page

I am new to Android, i tried to use an ontouchevent() to detect screen touch, i worked on one of the sample page but when i copy pasted the same code in another page it doesn't seem to be working.
I think it has something to do with the View.
Can someone please help me on this.
Code
public class HelpDesk extends Activity{
#Override
public void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
ImageButton home = (ImageButton)findViewById(R.id.home);
ImageButton exit = (ImageButton)findViewById(R.id.exit);
final Intent homeIntent = new Intent(this,MobNavSys4VisuallyImpaired.class);
home.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
startActivity(homeIntent);
}
});
exit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
startActivity(homeIntent);
}
});
}
public boolean onTouchEvent(MotionEvent event)
{
System.out.print("touch");
Toast.makeText(this, "hiiiiii", Toast.LENGTH_SHORT).show ();
return true;
}}
`
check it
change return true;
to return super.onTouchEvent(event);

VideoView onTouch events: pause/resume video, and show/hide MediaController and ActionBar

Question summary:
1) How to first display the video as paused, and not play it immediately?
2) How to pause/un-pause the video on touch, and also hide/show the ActionBar and MediaController.
I'd appreciate any advice. Thanks! (Relevant Code is attached)
Update 1
Found somewhat of a solution to question 2 (needed to return false), but I still don't know how to answer question 1.
When the user presses a button in my app, it takes them to watch their video. When they first open that screen, I'd like the video to be paused and not play immediately. I'd also like to be able to pause playback of the video by tapping the screen. When the video is paused, I'd like to show the ActionBar and the MediaController. When the video is resumed, I'd like to hide the ActionBar and MediaController (possibly after a slight delay?)
I've tried a few things, but I end up with problems, like the video will pause but not resume, or the ActionBar and MediaController will not show or hide properly.
Update 2
I have found a partial solution to question 1 and have updated the code to display the video as paused the first time it is opened. However, when it is opened for the first time, it only shows a black screen until I touch the videoview to play it. After watching the video once, it will reset to the beginning and pause, waiting to be played again, and will show the correct image from the beginning of the video. But I don't know how to get around the black screen at the beginning.
Relevant code:
public class ViewImageVideoFragment extends Fragment
{
private int position = 0;
private MediaController mMediaController;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mMediaController = new MediaController(getActivity());
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
if (savedInstanceState != null)
{
position = savedInstanceState.getInt("position");
}
View v = inflater.inflate(R.layout.fragment_video_view, parent, false);
mVideoView = (VideoView) v.findViewById(R.id.fragmentVideoView);
mVideoView.setVideoPath(videoPath);
mVideoView.setMediaController(mMediaController);
mVideoView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent motionEvent)
{
if (mVideoView.isPlaying())
{
mVideoView.pause();
if (!getActivity().getActionBar().isShowing())
{
getActivity().getActionBar().show();
mMediaController.show(0);
}
position = mVideoView.getCurrentPosition();
return false;
}
else
{
if (getActivity().getActionBar().isShowing())
{
getActivity().getActionBar().hide();
mMediaController.hide();
}
mVideoView.seekTo(position);
mVideoView.start();
return false;
}
}
});
mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mediaPlayer)
{
mVideoView.seekTo(0);
}
});
if (position != 0)
{
mVideoView.seekTo(position);
mVideoView.start();
}
else
{
mVideoView.seekTo(0);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
if (mVideoView != null)
{
savedInstanceState.putInt("position", mVideoView.getCurrentPosition());
}
mVideoView.pause();
}
}
To first show the video as paused, simply change seekTo(0) to seekTo(1) in your code. This will move the video to the time at 1 millisecond and you can take it from there.
//edited here
private int position = 1;
private MediaController mMediaController;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mMediaController = new MediaController(getActivity());
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
if (savedInstanceState != null)
{
position = savedInstanceState.getInt("position");
}
View v = inflater.inflate(R.layout.fragment_video_view, parent, false);
mVideoView = (VideoView) v.findViewById(R.id.fragmentVideoView);
mVideoView.setVideoPath(videoPath);
mVideoView.setMediaController(mMediaController);
mVideoView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent motionEvent)
{
if (mVideoView.isPlaying())
{
mVideoView.pause();
if (!getActivity().getActionBar().isShowing())
{
getActivity().getActionBar().show();
mMediaController.show(0);
}
position = mVideoView.getCurrentPosition();
return false;
}
else
{
if (getActivity().getActionBar().isShowing())
{
getActivity().getActionBar().hide();
mMediaController.hide();
}
mVideoView.seekTo(position);
mVideoView.start();
return false;
}
}
});
mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mediaPlayer)
{
//here
mVideoView.seekTo(1);
}
});
//here
if (position != 1)
{
mVideoView.seekTo(position);
mVideoView.start();
}
else
{
//here
mVideoView.seekTo(1);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
if (mVideoView != null)
{
savedInstanceState.putInt("position", mVideoView.getCurrentPosition());
}
mVideoView.pause();
}
}
If I understand correctly, you want to display a frame from the video as a placeholder until you are ready to start the video. There's two ways I know to accomplish this:
seekTo
You can use MediaPlayer.seekTo to move the video some frames ahead, for example using the value 150 to display the frame at the 150th millisecond in the video file. The video does not need to be started in order to seek.
MediaMetadataRetriever
MediaMetadataRetriever met = new MediaMetadataRetriever();
try {
met.setDataSource(data[0], new HashMap<String, String>()); //use this constructor, other one has a bug...
Bitmap b = met.getFrameAtTime();
if (b == null)
b = met.getFrameAtTime(150, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
met.release();
return b;
} catch (Exception e) {
Log.d(TAG, "MediaMetadata failed", e);
}
This will give you a Bitmap which you can then throw in an ImageView and set in place of the video. However, this API has always been buggy for me depending on the types of video codecs you are dealing with.
My sources --
show()
show(int timeout)
hide()
isShowing()
onTouchEvent()
All notes are in the code
public class ViewImageVideoFragment extends Fragment
{
private int position = 0;
private MediaController mMediaController;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mMediaController = new MediaController(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
if (savedInstanceState != null)
{
position = savedInstanceState.getInt("position");
}
v = inflater.inflate(R.layout.fragment_video_view, parent, false);
mVideoView = (VideoView) v.findViewById(R.id.fragmentVideoView);
mVideoView.setVideoPath(videoPath);
mVideoView.setMediaController(mMediaController);
mVideoView.setOnTouchListener(
new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent motionEvent)
{
if (mVideoView.isPlaying())
{
mVideoView.pause();
/*
Ok, so now you want to use that show(), preferrably without the int timeout
I didn't add it in myself but you should be able to handle it yourself
*/
return true;
}
else /* I changed it to else, change it to if else if you have something specific you want to deal with */
{
/*
I would use that hide method I linked here, then start the
video, I assume you know how to play the video yourself
*/
}
return false;
}
});
mVideoView.seekTo(position);
mVideoView.start();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
if (mVideoView != null)
{
savedInstanceState.putInt("position", mVideoView.getCurrentPosition());
}
mVideoView.pause();
}
}
I provided the other methods because, depending on how you may continue, they may or may not prevent future questions.

Android button having two functions

I need to have a button that is suppose to have two functions.
If I tap on it once, it will go to the next page.
If I hold down on the button, it will allow me to edit the text on the button.
The button is able to go to the next page upon tapping on it, but how do I implement the second function which allows me to change the text If I hold down the button?
Does anybody know?
java code
public class MainActivity extends Activity {
Button button1;
Button button2;
Button button3;
Handler h;
private Socket socket;
private boolean mInSettingsMode;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "192.168.43.83";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
// living button click start
button1 = (Button) findViewById(R.id.btnliving);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun, 0);
}
});
button2 = (Button) findViewById(R.id.btnbed);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun2, 0);
}
});
button3 = (Button) findViewById(R.id.btndin);
button3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun3, 0);
}
});
}
Runnable irun = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, living.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
Runnable irun2 = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, bed.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
Runnable irun3 = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, din.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present.
* getMenuInflater().inflate(R.menu.main, menu); return true; }
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
// new Thread(new ClientThread()).start();
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
xml code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:background="#drawable/back1"
tools:context=".MainActivity" >
<Button
android:id="#+id/btnliving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light Control"
/>
<Button
android:id="#+id/btnbed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fan Control"
/>
<Button
android:id="#+id/btndin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thermostat Control"
/>
</LinearLayout>
You can set second function as a setOnLongClickListener as:
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
//change text here
return true;
}
});
and first function is same setOnclickListener as:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
check this Documentation
button.setOnTouchListener(new View.OnTouchListener() {
private static final long MAX_CLICK_TIME = 400;
long time = 0;
#Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
time = System.currentTimeMillis();
} else if (MotionEvent.ACTION_UP == event.getAction()) {
long pressingTime = System.currentTimeMillis() - time;
if (pressingTime > MAX_CLICK_TIME) {
// do change text logic
} else {
// show new page logic
}
}
return true;
}
});
If you want to change the text of a button without having to wait until the user removes his finger from the button, you can use TimerTask.Code with TimerTask:
button.setOnTouchListener(new View.OnTouchListener() {
private static final long MAX_CLICK_TIME = 400;
long time = 0;
Timer timer = new Timer();
#Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
time = System.currentTimeMillis();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
// do change text logic
}
};
timer.schedule(timerTask, MAX_CLICK_TIME);
} else if (MotionEvent.ACTION_UP == event.getAction()) {
long pressingTime = System.currentTimeMillis() - time;
if (pressingTime <= MAX_CLICK_TIME) {
timer.cancel();
// show new page logic
}
}
return true;
}
});
I have not tested, but should work. In any case, the idea should be clear.

Categories