I'm trying to send a gesture when I clicking on the button but nothing happens why?
I made the gesture position top the button to check if that works or no.
I enabled accessibility permissions.
Main Class
public class MainActivity extends AppCompatActivity {
MyService myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
if (myService == null)
myService = new MyService();
Log.w("ABC", String.valueOf(new Random().nextInt(1000)));
}
}
MyService Class
public class MyService extends AccessibilityService {
public MyService() {
clickOnPosition(540, 960);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
}
private void clickOnPosition(float x, float y) {
Path path = new Path();
path.moveTo(x, y);
GestureDescription.StrokeDescription strokeDescription = new GestureDescription.StrokeDescription(path, 4000, 1000);
GestureDescription.Builder builder = new GestureDescription.Builder();
builder.addStroke(strokeDescription);
dispatchGesture(builder.build(), new GestureResultCallback() {
#Override
public void onCompleted(GestureDescription gestureDescription) {
super.onCompleted(gestureDescription);
Log.w("ABC", "Completed");
}
#Override
public void onCancelled(GestureDescription gestureDescription) {
super.onCancelled(gestureDescription);
Log.w("ABC", "Canceled");
}
}, null);
}
}
Note: It works if I moved clickOnPosition(540, 960); to onServiceConnected()
Related
I am making a game on LibGdx that has video ads. I implemented interface and it's methods. Everything works, video is shown.
AndroidLauncher:
public class MainAndroidLauncherAuthorization extends AndroidApplication implements
AdsController, RewardedVideoAdListener, AdHandler {
private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
private RewardedVideoAd rewardedVideoAd;
private boolean isRewardLoaded;
private boolean completed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
setContentView(R.layout.activity);
initialize(new STARTGame(this, this), config);
MobileAds.initialize(this, "ca-app-pub-3940256099942544/5224354917");
rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
rewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
public void loadRewardedVideoAd() {
isRewardLoaded=false;
rewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new
AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
isRewardLoaded =true;
}
#Override
public void showRewardedVideo() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (rewardedVideoAd.isLoaded()) {
rewardedVideoAd.show();
} else {
loadRewardedVideoAd();
}
}
});
}
#Override
public boolean hasVideoReward(){
return isRewardLoaded;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem reward) {
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
completed = true;
}
#Override
public boolean addCoins() {
return completed;
}
#Override
protected void onResume() {
super.onResume();
rewardedVideoAd.resume(this);
}
#Override
public void onPause() {
super.onPause();
rewardedVideoAd.pause(this);
}
#Override
public void onDestroy() {
super.onDestroy();
rewardedVideoAd.destroy(this);
}
#Override
public void coin_10() {
Prefs prefs = new Prefs();
prefs.plus_Coins_bank(10);
}
}
Interface:
public interface AdsController {
void showRewardedVideo();
void loadRewardedVideoAd();
boolean addCoins();
boolean hasVideoReward();
Core:
public class Win_01_18 extends Window implements AdsController, AdHandler {
private Prefs prefs;
public Win_01_18(AdHandler sums, final AdsController adsController, final AssetMan assetMan) {
super("", assetMan.get_skin_dialogs(), "dialog_window_main");
*******
Button btn_buy_10 = new Button(assetMan.get_skin_buttons_coins_video(), "btn_video_long");
***
btn_buy_10.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
adsController.showRewardedVideo();
super.clicked(event, x, y);
}
});
#Override
public void showRewardedVideo() {
}
#Override
public void loadRewardedVideoAd() {
}
#Override
public boolean addCoins() {
return false;
}
#Override
public boolean hasVideoReward() {
return false;
}
#Override
public void coin_10() {
}
Everything works. There are 2 questions:
1 - How to check the onRewardedVideoCompleted() method from core-class?
2 - On what event should the coins be added for watching a video in the core-class?
I am currently trying this myself. But what about changing the
void showRewardedVideoAd()
to a boolean
boolean showRewardedVideoAd()
And then in the onRewardedVideoCompleted() you return true and if it fails you return false.
Then in the core where you call the ad you put
boolean adFinished = False;
adFinished = adsController.showRewardedVideo();
if(adFinished){
// give them the coins or whatever
} else {
// the ad failed or the clicked it away early or something. Don't give them coins and go on
}
I am trying to play youtube video, In Picture in Picture mode.
For this I am using youtube player api, when I press back button youtube player activity comes in picture in picture mode but video is stops playing, when i press play button then it again comes in full screen and start playing from start.
In full screen after rotating screen video is playing normally and start playing video where it before rotating.
I am not getting continues playing video in PIP.
Here is my code
public class YoutubePIPActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener
{
private static final String API_KEY = AppConstant.YUTUBE_PLAYER_API_KEY;
private static String mVIDEO_ID = "o7VVHhK9zf0";
private boolean isPIPModeEnabled = true;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube_pip);
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored)
{
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(mVIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult)
{
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(YouTubePlayer.ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
};
#Override
public void onBackPressed()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)
&& isPIPModeEnabled)
{
enterPIPMode();
}
else
{
super.onBackPressed();
}
}
private void enterPIPMode()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE))
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
Rational rational = new Rational(250, 150);
PictureInPictureParams.Builder params = new PictureInPictureParams.Builder();
params.setAspectRatio(rational);
this.enterPictureInPictureMode(params.build());
} else
{
this.enterPictureInPictureMode();
}
new Handler().postDelayed(() -> checkPIPPermission(), 30);
}
}
#RequiresApi(Build.VERSION_CODES.N)
void checkPIPPermission()
{
isPIPModeEnabled = isInPictureInPictureMode();
if(!isInPictureInPictureMode())
{
onBackPressed();
}
}
#Override
protected void onUserLeaveHint()
{
super.onUserLeaveHint();
enterPIPMode();
}
#Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig)
{
if(newConfig !=null){
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
}
}
}
Here is activity defined in manifest
<activity android:name=".ui.activity.youtube.YoutubePIPActivity"
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
android:exported="false"
android:resizeableActivity="true"
android:supportsPictureInPicture="true"
android:theme="#style/Theme.AppCompat.FullScreen"
tools:targetApi="n"/>
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void ListenForNewMessage()
{
final SpeechRecognizer newDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
newDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
if (newDeliverySpeech.isRecognitionAvailable(getApplicationContext()))
{
Log.d("SpeechListening","started listening hopefully");
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
The problem is, only the started listening hopefully is logged, the RecognitionListener never has onReadyForSpeech() or any of its methods called.
details
details
details
details
Can someone please tell me what I'm doing wrong here?
You are basically creating a new SpeechRecognizer object and register a new listener each time you click on the button. On top of that you create the SpeechRecognizer using the current Activity Context but you are actually using the Application context when calling: isRecognitionAvailable();
Try to create the SpeechRecognizer as a member object and register your listener when onCreate() is called. Also try to avoid using the Application context to avoid memory leaks.
Here is an example of how you should do it.
private SpeechRecognizer mDeliverySpeech;
private Intent mSpeechIntent;
private boolean mListening = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
SetupSpeechRecognizer();
mSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void SetupSpeechRecognizer()
{
mDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
mDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
}
private void ListenForNewMessage()
{
if (mDeliverySpeech.isRecognitionAvailable(this) && !mListening)
{
Log.d("SpeechListening","started listening hopefully");
mListening = true;
mDeliverySpeech.startListening(mSpeechIntent);
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
mDeliverySpeech.stopListening();
mListening = false;
}
}.start();
}
}
Do not forget to properly handle the activity life cycle when working with listener to avoid memory leak.
LibGdx Android App
I am trying to login to Google play from the libgdx screen using the actionResolver.loginGPGS() which is there in the Activity AndroidLauncher . The actual login process happens in the Activity-AndroidLauncher and onSignInSucceeded() is getting called after successful login.
Question:
I need to have some setup so that a new method in the Libgdx screen - StartScreen get triggered when the Google Play sign-in succeeds. Kindly advice.
StartScreen
public class StartScreen extends Screen implements InputProcessor,OnCompletionListener {
public StartScreen(ActionResolver actionResolver, String KEYSTATE) {
}
#Override
public void create() {
}
#Override
public void update() {
}
#Override
public void render(SpriteBatch sb) {
batch=sb;
sb.setProjectionMatrix(camera.combined);
sb.begin();
sb.draw(BACKGROUND,0,0,MainGame.SCREEN_WIDTH,MainGame.SCREEN_HEIGHT);
showButtons();
sb.end();
handleInput();
}
#Override
public void resize(int width, int height) {
camera.resize();
}
#Override
public void dispose() {
}
#Override
public void pause() {
gameMusic.pause();
System.out.println("StartScreen - pause");
}
#Override
public void resume() {
}
private void showButtons() {
}
private void handleInput() {
if(Gdx.input.isTouched()) {
Vector3 touchPosition = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPosition);
if(!exitButtonTouched){
// Exit Button
if(touchPosition.x >= xMargin && touchPosition.x <= xMargin + EXIT.getWidth() &&
touchPosition.y >= yMargin && touchPosition.y <= yMargin + EXIT.getHeight() ) {
actionResolver.loginGPGS();
}
}
}
}
AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements GameHelperListener,ActionResolver {
#Override
public void loginGPGS() {
try {
runOnUiThread(new Runnable(){
public void run() {
gameHelper.beginUserInitiatedSignIn();
}
});
} catch (final Exception ex) {
}
}
#Override
public void onSignInFailed() {
System.out.println("- - - AndroidLauncher - - - onSignInFailed");
}
#Override
public void onSignInSucceeded() {
System.out.println("- - - AndroidLauncher - - - onSignInSucceeded");
}
}
ActionResolver
public interface ActionResolver {
public void showOrLoadInterstital();
public boolean getSignedInGPGS();
public void loginGPGS();
public void submitScoreGPGS(int score);
public void unlockAchievementGPGS(String achievementId);
public void getLeaderboardGPGS();
public void getAchievementsGPGS();
public void setFinish();
}
Save a pointer to the Libgdx game when you create it:
game = new Game(this);
initialize(game, config);
Then just call any of Game's methods from onSignInSucceeded
#Override
public void onSignInSucceeded() {
System.out.println("- - - AndroidLauncher - - - onSignInSucceeded");
game.switchScreensOrWhatever();
}
}
Have that method trigger whatever you need done in LibGdx
This is my service class in that i increment the i value based on time...
public class BackService extends Service {
int i=0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
private void pollForUpdates() {
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("Service class called", "service class called "+i);
getRunningApps();
i++;
}
},0,1000);
}
private void getRunningApps()
{
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I want to append the i value to the TextView. i.e the TextView value is dynamically change based on i value...
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BackService.class));
TextView tx=(TextView)findViewById(R.id.textView1);
}}
how to append the i value to tx...
Thank you in advance..
You will need to register Broadcast receiver for Sending data back from Service to Activity.see these usefull example for communication between Activity to service :
http://androidexperinz.wordpress.com/2012/02/14/communication-between-service-and-activity-part-1/
http://androidexperinz.wordpress.com/2012/02/21/communication-between-service-and-activity-part-2/
http://blog.philippheckel.com/2012/06/10/android-example-communication-between-activity-and-service-using-messaging/
Use this
public class MainActivity extends Activity {
TextView tx;
RefreshBroadcastReciver mBroadCastReciver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BackService.class));
tx =(TextView)findViewById(R.id.textView1);
}
#Override
protected void onResume() {
super.onResume();
mBroadCastReciver = new RefreshBroadcastReciver();
registerReceiver(mBroadCastReciver, new IntentFilter("sendData"));
}
private class RefreshBroadcastReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
tx.setText(intent.getIntExtra("i", 0)+"");
}
}
#Override
protected void onStop() {
super.onStop();
if(mBroadCastReciver!=null)
unregisterReceiver(mBroadCastReciver);
}
}
and your service is here
public class BackService extends Service {
int i=0;
Intent intent1;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
intent1=new Intent("sendData");
}
private void pollForUpdates() {
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("Service class called", "service class called "+i);
getRunningApps();
i++;
Message msg=new Message();
msg.arg1=i;
handler.sendMessage(msg);
}
},0,1000);
}
private void getRunningApps()
{
}
#Override
public void onDestroy() {
super.onDestroy();
}
protected Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
intent1.putExtra("i", msg.arg1);
sendBroadcast(intent1);
}
};
}