Huawei Account Kit Automatic phone verification is not working - huawei-mobile-services

I have been trying to make the automatic phone verification work, but it does not fill the verification.
public class MySMSBroadcastReceiver extends BroadcastReceiver {
#Override public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null)
{ Status status = bundle.getParcelable(ReadSmsConstant.EXTRA_STATUS); if (status.getStatusCode() == CommonStatusCodes.TIMEOUT) { // Service has timed out and no SMS message that meets the requirement is read. Service ended. doSomethingWhenTimeOut(); }
else if (status.getStatusCode() == CommonStatusCodes.SUCCESS) {
if (bundle.containsKey(ReadSmsConstant.EXTRA_SMS_MESSAGE)) {
// An SMS message that meets the requirement is read. Service ended. doSomethingWhenGetMessage(bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE)); } } } } }

We need to also have a completion callback to catch the message to do action:
Task<Void> task = ReadSmsManager.start(MainActivity.this);
task.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// The service is enabled successfully. Continue with the process.
doSomethingWhenTaskSuccess();
}
}
});

Related

Why is there a delay between closing interstitial ad and opening the target activity?

I implemented this android code to load and show an interstitial ad and after closing the ad it will open the target activity, but my problem is there's a 3 seconds delay between closing and opening the target activity...here's my code:
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(HomeActivity.this, UNIT_ID, adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
admobInterstitialAd = interstitialAd;
admobInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
admobInterstitialAd = null;
/**********Here is the delay when starting the activity for about 3 seconds*******/
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
/********************************************************************************/
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
admobInterstitialAd = null;
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
admobInterstitialAd = null;
}
});
if (admobInterstitialAd != null) {
admobInterstitialAd.show(HomeActivity.this);
}
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
admobInterstitialAd = null;
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
Any suggestions to fix this issue....thanks in advance...
I faced the same problem. I still haven't been able to fix the problem and couldn't find a resource that does. While searching on Google, I realized that you are not alone and those who have the same problem on other platforms.
As a workaround, I will use a progress dialog. This makes users wait until the ad closes and the new event starts. I think 1-3 seconds.
if (mInterstitialAd != null) {
mInterstitialAd.show(MainAct.this);
startActivity(new Intent(MainAct.this, NewAct.class));
progressDialog.show();
} else {
startActivity(new Intent(MainAct.this, MafA.class));
}

Passing ExoPlayer instance from activity to binded service?

I'm trying to make a Video Player using ExoPlayer that can also work in the background and you can control it through the notification. I already created the ExoPlayer and the ForeGround Service for the notification and i binded them. At the moment it works as intended, the only problem is that i don't want the activity player to stop working when i close the notification. This happens because at the moment i'm creating the ExoPlayer instance in the service and then i pass the instance to the Activity, so when i close the notification the instance gets lost. Is there a way to initialize the player instance in the Activity and then pass that instance to the service so i can still control the video from the notification without risking to lose the instance once the notification is closed?
I'm pretty new to android and this is the first time that i'm binding a service to an activity so i don't really know how to do it. I tried searching on Google but that didn't help either.
This is the Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerView=findViewById(R.id.player_view);
intent=new Intent(this,AudioPlayerService.class);
//here i will add the url that needs to be loaded
//but at the moment this is just a draft
Util.startForegroundService(this,intent);
playerView.setUseController(true);
//playerView.showController();
playerView.setControllerAutoShow(true);
playerView.setControllerHideOnTouch(true);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
AudioPlayerService.LocalBinder binder = (AudioPlayerService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
initializePlayer();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
public void onStart() {
super.onStart();
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
initializePlayer();
}
#Override
protected void onStop() {
unbindService(mConnection);
mBound = false;
super.onStop();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
private void initializePlayer() {
if (mBound) {
SimpleExoPlayer player = mService.getplayerInstance();
playerView.setPlayer(player);
}
}
}
This is the Service
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public SimpleExoPlayer getplayerInstance() {
if (player == null) {
startPlayer();
}
return player;
}
public class LocalBinder extends Binder {
public AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
final Context context=this;
}
private void startPlayer() {
final Context context = this;
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(new DefaultHttpDataSourceFactory("NotificationSync", 10000, 10000, true))
.createMediaSource(Uri.parse("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(context, "1",
R.string.app_name,
2,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public String getCurrentContentTitle(Player player) {
return "title";
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Nullable
#Override
public String getCurrentContentText(Player player) {
return "text";
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}, new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
stopSelf();
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
mNotification = notification;
mNotificationId = notificationId;
if (ongoing) {
startForeground(notificationId, notification);
}
}
}
);
playerNotificationManager.setPlayer(player);
playerNotificationManager.setUseStopAction(true);
}
#Override
public void onDestroy() {
releasePlayer();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (player == null) {
//here i will get all the data from the intent that came from the
//activity (title,text,url...)
startPlayer();
}
return START_STICKY;
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
}
In the end all i want to achieve is a video player that you start in the activity and also works/can be controlled through a notification without interruption when i go from activity->background and background->activity. If there are other ways to achieve this i'm open to try.

Getting skipped frames with RxAndroid on a simple call

I'm implementing in a LauncherActivity (with just a loading indicator) an Observable (Single) from RxJava library to login with the previously recorded users credentials.
The activity is very very simple, and yet I get a skipped frames warning (40ish), both on my phone and on emulator, and I can't figure out why (though sometimes it doesn't show up).
Here is the code :
public class LauncherActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mProgressBar = findViewById(R.id.progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
if (UsersUtils.hasCredentialsRecorded(this)) {
getAccessToken();
} else {
login();
}
}
public void getAccessToken() {
Callable<Token> callable = new Callable<Token>() {
#Override
public Token call() throws Exception {
final Map<String, byte[]> credentials = UsersUtils.getCredentials(getApplicationContext());
Token token = OauthCalls.getToken(new String(credentials.get(UsersUtils.PREFERENCES_USER_KEY)),
new String(credentials.get(UsersUtils.PREFERENCES_PASS_KEY)));
return token;
}
};
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.subscribe(new DisposableSingleObserver<Token>() {
#Override
public void onSuccess(Token token) {
if (token == null) {
login();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onError(Throwable e) {
login();
}
});
}
public void login() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Thanks a lot for your help !

Stopping a Windows Service in the event of a critical error

I have a Windows Service which basically wraps a task:
public partial class Service : ServiceBase
{
private Task task;
private CancellationTokenSource cancelToken;
public Service()
{
InitializeComponent();
this.task = null;
this.cancelToken = null;
}
protected override void OnStart(string[] args)
{
var svc = new MyServiceTask();
this.cancelToken = new CancellationTokenSource();
this.task = svc.RunAsync(cancelToken.Token);
this.task.ContinueWith(t => this.OnUnhandledException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}
protected override void OnStop()
{
if (this.task != null)
{
this.cancelToken.Cancel();
this.task.Wait();
}
}
private void OnUnhandledException(Exception ex)
{
this.EventLog.WriteEntry(string.Format("Unhandled exception: {0}", ex), EventLogEntryType.Error);
this.task = null;
this.Stop();
}
}
As you can see, the service can catch unhandled exceptions. If this happens, the exception is logged and the service is stopped. This has the effect of writing two messages to the event log - one error stating there was an unhandled exception, and another stating that the service was successfully stopped.
This may sound minor, but I'm hoping to be able to suppress the 'successfully stopped' message. I find it misleading - it suggests that the service stopping was a normal occurrence. Is there another way I can force the service to stop itself without this message being logged?

XMPP: Smack client not receiving chat message

I've been struggling with XMPP chatting a lot through Smack and Openfire server.
My problem is as follows:
Whenever a user sends a message to another user, the message is received correctly at the other user. But any reply doesn't show up at the sender of the first message.
So User 1 sends to User 2 successfully. User 2 is then unable to send to User 1 any reply.
On the other hand, if I restart and let the users login again, User 2 can send to User 1 but not vice versa.
What I'm trying to say is that only the initiator of the chat can send a message, the receiver cannot reply back.
My code looks like this
package xmpp;
public class XMPPClient{
private static final int packetReplyTimeout = 500; // millis
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private ConnectionConfiguration config;
private MyTimer t = MyTimer.getInstance();
private ArrayList<String> threadPool = new ArrayList<String>();
public XMPPClient()
{
SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);
//define openfire server information
config = new ConnectionConfiguration("localhost",5222);
config.setSASLAuthenticationEnabled(false);
config.setSecurityMode(SecurityMode.disabled);
connection = new XMPPConnection(config);
//connect to server
t.start("Connecting to server...");
try {
connection.connect();
} catch (XMPPException e) {
System.err.println("Failed to connect to server! Connect to VPN!\t"+e.getMessage());
System.exit(0);
}
t.end("Connection took ");
//setup chat mechanism
chatManager = connection.getChatManager();
chatManager.addChatListener(
new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
chat.addMessageListener(new MyMessageListener());
}
});
}
public boolean login(String userName, String password, String resource) {
t.start("Logging in...");
try {
if (connection!=null && connection.isConnected())
connection.login(userName, password, resource);
//set available presence
setStatus(true);
}
catch (XMPPException e) {
if(e.getMessage().contains("auth")){
System.err.println("Invalid Login Information!\t"+e.getMessage());
}
else{
e.printStackTrace();
}
return false;
}
t.end("Logging in took ");
return true;
}
public void setStatus(boolean available) {
if(available)
connection.sendPacket(new Presence(Presence.Type.available));
else
connection.sendPacket(new Presence(Presence.Type.unavailable));
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
boolean chatExists = false;
Chat c = null;
for(String tid : threadPool)
{
if((c = chatManager.getThreadChat(tid)) != null)
{
if(c.getParticipant().equals(buddyJID))
{
if(checkAvailability(buddyJID))
{
chatExists = true;
break;
}
else
{
threadPool.remove(tid);
break;
}
}
}
}
if (chatExists)
{
Chat chat = c;
chat.sendMessage(message);
}
else
{
Chat chat = chatManager.createChat(buddyJID, messageListener);
threadPool.add(chat.getThreadID()); System.out.println(chat.getThreadID());
chat.sendMessage(message);
}
}
public void createEntry(String user, String name) throws Exception {
System.out.println(String.format("Creating entry for buddy '%1$s' with name %2$s", user, name));
Roster roster = connection.getRoster();
roster.createEntry(user, name, null);
}
public boolean checkAvailability(String jid)
{
System.out.print("Checking availability for: "+jid+"=");
System.out.println(connection.getRoster().getPresence(jid).isAvailable());
return connection.getRoster().getPresence(jid).isAvailable();
}
public void disconnect() {
if (connection!=null && connection.isConnected()) {
setStatus(false);
connection.disconnect();
}
}
}
import org.jivesoftware.smack.packet.Message;
public class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
}
}
I'm not sure what the problem is. Any suggestions? Sample code?
Thanks <3
I am not sure if this will help you but I can get reply with this code:
public void chat(String AddressedUser) throws NotConnectedException {
//Create username whom we want to send a message
String userToSend = AddressedUser + "#" + serverDomain;
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat(userToSend , new MessageListener() {
#Override
public void processMessage(Chat chat, Message message ) {
// TODO Auto-generated method stub
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Hey");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
}
I am sending "Hey" then what ever other user writes I will see in my logcat.
You haven't specified what the receiver is, for instance, if it is an existing client (like Spark for instance), or more custom code. This would be helpful, as would knowing what version of Smack you are using.
That particular code has several issues with it.
It keeps creating new Chat objects for every message sent, instead of
simply reusing the same chat.
There is no ChatManagerListener registered to handle new Chat messages that are not tied to an existing chat.
the is code is very complicated and it seems is meant only to send msgs.
Here is a sample code that works perfectly, both sending and receiving:
http://www.javaprogrammingforums.com/java-networking-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html