android wear message api start activity and methods - java

I have a problem with the android wear device I can turn on the camera with the message api by loading turnOn() onCreate on mobile device.
Problem One: I can't open an activity if the phone is locked.
Problem Two: I can start only one activity if the phone is unlocked but can't call methods of the phone. The only way I started the camera was starting the MainActivity on the Oncreate() method using the wearListener service.
I want something like this app: https://play.google.com/store/apps/details?id=com.jumpbyte.flashlight
Here is my code:
Oncreate method phone
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent() ;
int valor = intent.getIntExtra("parameter",0);
String value = "key" ;
if (valor == 0){
boolean isCameraFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!isCameraFlash) {
showCameraAlert();
} else {
camera = Camera.open();
params = camera.getParameters();
}
if(isFlashlightOn) {
setFlashlightOff();
} else {
setFlashlightOn();
}
}
else{
finish();
}
/* boolean isCameraFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!isCameraFlash) {
showCameraAlert();
} else {
camera = Camera.open();
params = camera.getParameters();
}
if(isFlashlightOn) {
setFlashlightOff();
} else {
setFlashlightOn();
}
*/
}
Listener phone:
private static final String HELLO_WORLD_WEAR_PATH = "/hello-world-wear" ;
public void onMessageReceived(MessageEvent messageEvent) {
if (messageEvent.getPath().equals(HELLO_WORLD_WEAR_PATH)) {
// AudioManager audiomanager ;
// audiomanager = (AudioManager)getSystemService(Context.AUDIO_SERVICE) ;
// audiomanager = (AudioManager)getSystemService(Context.AUDIO_SERVICE) ;
// audiomanager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI) ;
// Toast.makeText(getApplicationContext(), "Volume Up | Vibration Time Increased", Toast.LENGTH_SHORT).show() ;
//light lightOne = new light();
// MainActivity one = new MainActivity() ;
// one.messageone();
// lightOne.on();
// Toast.makeText(getApplicationContext(),
// "Button is clicked", Toast.LENGTH_LONG).show() ;
Intent startIntent = new Intent(this, MainActivity.class) ;
startIntent.putExtra("parameter", 0); //Optional parameters
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ;
startActivity(startIntent) ;
/* if(isFlashlightOn) {
setFlashlightOff();
} else {
setFlashlightOn();
}
*/
} else {
} } }
Wear main class:
private void sendMessage() {
if (mNode != null && mGoogleApiClient!=null && mGoogleApiClient.isConnected()) {
Wearable.MessageApi.sendMessage(
mGoogleApiClient, mNode.getId(), HELLO_WORLD_WEAR_PATH, null).setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.e("TAG", "Failed to send message with status code: "
+ sendMessageResult.getStatus().getStatusCode());
}
}
}
);
}else{ } }
protected void onStart() {
super.onStart() ;
if (!mResolvingError) {
mGoogleApiClient.connect() ;
} }
private void resolveNode() {
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) {
mNode = node ; } }
}) ; }
public void onConnected(Bundle bundle) {
resolveNode();
}
public void onConnectionSuspended(int i) {
//Improve your code
}
public void onConnectionFailed(ConnectionResult connectionResult) {
//Improve your code
}
Can someone help me out with this to problems please I can't find any way to pass those two problems. I want something like this app: https://play.google.com/store/apps/details?id=com.jumpbyte.flashlight

I'm somewhat of a noob myself but I'm having a similar problem so I'll try to give some input on what I've learned so far.
I don't think any of that code needs to be in onCreate(), since it'll only run once when the app is first opened.
First, I would take all the code you wrote inside of onCreate() and write a seperate method outside of onCreate(). The constants like intent,valor, and value should just be private and inside of the normal Main Activity.
After making a new method and some copy pasta I would run it inside of onMessageReceived().
Here is link to a MessageAPIDemo. Very helpful.
I'm personally having trouble getting my phone to receive a message when the app isn't opened on the phone, somewhat similar to your locked phone problem. I hope I've been of some help.

Related

Both local and remote video call display black screen but audio works fine in agora

I am trying out agora sdk sample on android using java. when I run the app on my phone and remote device the audio actually works well but the video shows black screen. How do I solve this issue.
I have tried what was stated on agora docs but non worked for me.
I have checked permissions they are working fine
My front camera is working fine
I enabled the video on my code.
My Code
public class VideoChatViewActivity extends AppCompatActivity {
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mRemoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
private LoggerRecyclerView mLogView;
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft();
}
});
}
};
private void setupRemoteVideo(int uid) {
int count = mRemoteContainer.getChildCount();
View view = null;
for (int i = 0; i < count; i++) {
View v = mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int) v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mRemoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mRemoteView);
// Initializes the video view of a remote user.
mRtcEngine.setupRemoteVideo(new VideoCanvas(mRemoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mRemoteView.setTag(uid);
}
private void onRemoteUserLeft() {
removeRemoteVideo();
}
private void removeRemoteVideo() {
if (mRemoteView != null) {
mRemoteContainer.removeView(mRemoteView);
}
// Destroys remote view
mRemoteView = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
mLogView = findViewById(R.id.log_recycler_view);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
mLogView.logI("Welcome to Agora 1v1 video call");
mLogView.logW("You will see custom logs here");
mLogView.logE("You can also use this to show errors");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
// This is our usual steps for joining
// a channel and starting a call.
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
// In simple use cases, we only need to enable video capturing
// and rendering once at the initialization step.
// Note: audio recording and playing is enabled by default.
mRtcEngine.enableVideo();
// Please go to this page for detailed explanation
// https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#af5f4de754e2c1f493096641c5c5c1d8f
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
mRtcEngine.setupLocalVideo(new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
}
private void joinChannel() {
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token) || TextUtils.equals(token, "#YOUR ACCESS TOKEN#")) {
token = null; // default, no token
}
mRtcEngine.joinChannel(token, "demoChannel1", "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!mCallEnd) {
leaveChannel();
}
/*
Destroys the RtcEngine instance and releases all resources used by the Agora SDK.
This method is useful for apps that occasionally make voice or video calls,
to free up resources for other operations when not making calls.
*/
RtcEngine.destroy();
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
// Stops/Resumes sending the local audio stream.
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
// Switches between front and rear cameras.
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
}
I dont really know what is the issue. Anyone have idea on how I can solve this issue?
I found the solution for this
you have to add delay of 10 seconds before running below code
mRtcEngine!!.setClientRole(Constants.CLIENT_ROLE_BROADCASTER)
mRtcEngine!!.joinChannel(
stringToken,
channelName,
"Extra Optional Data",
currentUid
)
so the surface view of current user is loaded properly first and then it tries to join the call.
Simply put, dont join channel before surface view and camera is ready.

How can I check if a telephone number exist programmatically?

I want to do an Android App that check if a number exist or not. In particular I was thinking of calling the number to check and if it ring it means that exist, otherwise it does not.
At the moment I can read the state "IDLE" and "OFFHOOK" but not the state "CALL_STATE_RINGING" that as far as I understood trigger only for received call.
How can I understand when it is ringing and when the number is not valid?
Note: The calling approach is just an idea but I could accept others solutions if they are effective.
My code at the moment:
Listener:
public class EndCallListener extends PhoneStateListener {
private String TAG = "CALL_AUTOMATICALLY_LISTENER";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
// TODO
Log.i(TAG, "RINGING, number: " + incomingNumber);
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
Log.i(TAG, "OFFHOOK");
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
Log.i(TAG, "IDLE");
}
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = "CALL_AUTOMATICALLY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
}
private void askPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},0);
}
public void startCall(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String number = "+39555555555"; // fake number
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
// Activate listener
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
else Log.d(TAG, "TelephonyManager null");
// start call
startActivity(intent);
} else {
askPermission();
}
}
}
public void startCallNotExisting(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String number = "+39456464564545555565656565";
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
// Activate listener
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
else Log.d(TAG, "TelephonyManager null");
// start call
startActivity(intent);
} else {
askPermission();
}
}
}
}
I suggest you check phone number regex instead of calling them.place this method in your helper or activity or fragment class
public static boolean validateMobile(String mobile) {
if (mobile.matches("^[+]?[0-9]{10,13}$")) {
return true;
} else {
return false;
}
}
And use it like
if(Helper.validateMobile(mobile){
//mobile is valid
}else{
//mobile is not valid}
also this regex can be different if you target one specific country.for example i use below regex for iran phone numbers
(\\+98|0)?9\\d{9}

App crashes after clicking scan button for the first time but the app works after i reopen it

I'm trying to create an indoor location services app in android studio.There is a scan button which start the discovery of BLE devices. When i click on the scan button,the app crashes. But when i reopen the app and click on the scan button again,it works.
i tried this taken from one of the projects from stackoverflow.
Class variable:
private BluetoothAdapter mBtAdapter = null;
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = btManager.getAdapter();
if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void onScanButton(){
if (mBtAdapter.isEnabled()){
scanLeDevice(true);
}
}
this is my code
BluetoothManager btManager; //field 'btManager' is never used
private BluetoothAdapter btAdapter = null;
BluetoothLeScanner btScanner;
Button startScanningButton;
Button stopScanningButton;
TextView peripheralTextView;
private final static int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
peripheralTextView = (TextView) findViewById(R.id.peripheralTextView);
peripheralTextView.setMovementMethod(new ScrollingMovementMethod());
startScanningButton = (Button) findViewById(R.id.StartScanButton);
startScanningButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startScanning();
}
});
stopScanningButton = (Button) findViewById(R.id.StopScanButton);
stopScanningButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopScanning();
}
});
stopScanningButton.setVisibility(View.INVISIBLE);
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
btScanner = btAdapter.getBluetoothLeScanner();
if (btAdapter != null && !btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}
// Make sure we have access coarse location enabled, if not, prompt the user to enable it
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect peripherals.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
// Device scan callback.
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
peripheralTextView.append("MAC address: " + result.getDevice().getAddress() + " rssi: " + result.getRssi() + "TxPower:" + result.getTxPower() + "\n");
// auto scroll for text view
final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
};
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
System.out.println("coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
}
}
}
public void startScanning() {
System.out.println("start scanning");
peripheralTextView.setText("");
startScanningButton.setVisibility(View.INVISIBLE);
stopScanningButton.setVisibility(View.VISIBLE);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
btScanner.startScan(leScanCallback);
}
});
}
public void stopScanning() {
System.out.println("stopping scanning");
peripheralTextView.append("Stopped Scanning");
startScanningButton.setVisibility(View.VISIBLE);
stopScanningButton.setVisibility(View.INVISIBLE);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
btScanner.stopScan(leScanCallback);
}
});
}
}
The logcat shows
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference
at com.example.myapplication.MainActivity$6.run(MainActivity.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Before i click the Scan button,a prompt will be display asking to turn
on the bluetooth.So bluetooth will be turned on
You are wrong about that part. You ask the user to enable it, but it might not have happened yet. At least you need to get the Scanner later on.
Currently you set the Scanner reference before the permission requesting has been initiated.
This also explains why it works after your App has crashed for the first time, because the 2nd time you come here the Permission has been enabled.
From the Javadoc of BluetoothAdapter#getBluetoothLeScanner():
Will return null if Bluetooth is turned off or if Bluetooth LE
Advertising is not supported on this device.
You can change your code to:
public void startScanning() {
btScanner = btAdapter.getBluetoothLeScanner();
if (btScanner == null) {
// not enabled yet or not supported
return;
}
System.out.println("start scanning");
peripheralTextView.setText("");
startScanningButton.setVisibility(View.INVISIBLE);
stopScanningButton.setVisibility(View.VISIBLE);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
btScanner.startScan(leScanCallback);
}
});
}

Android studio Call method

I am having a problem with my code.
I have an activity with an EditText , when the activity opens for the first time I would like to pass the value of the EditText to my server and receive an answer.
The problem is if I call the method in onCreate () it does not work.
If instead I call the method from the
click ()
event of the button it works.
Is there a way to call the method from the onCreate () and display the contents of the EditText?
This is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
First_Name = (EditText)findViewById(R.id.editText50);
parseContent = new ParseContentRistoratore(this);
preferenceHelper = new PreferenceHelperRistoratore(this);
CheckEditTextIsEmptyOrNot();
UserRegisterFunction(F_Name_Holder);
prova = (Button) findViewById(R.id.button10);
// If EditText is not empty and CheckEditText = True then this block will execute.
prova.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//REGISTRATION
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void UserRegisterFunction(final String fk_id_ristorante){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if(httpResponseMsg.equalsIgnoreCase("Prova gratuita terminata")){
// finish(); con finish(); l'attività finisce
Intent intent = new Intent(Main3Activity.this, Versione_scaduta.class);
startActivity(intent);
}
}
//REGISTRATION
#Override
protected String doInBackground(String... params) {
hashMap.put("fk_id_ristorante",params[0]);
finalResult = httpParse.postRequest(hashMap, HttpURLRegister);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(fk_id_ristorante);
}
//REGISTRAZIONE
public void CheckEditTextIsEmptyOrNot(){
F_Name_Holder = First_Name.getText().toString();
if(TextUtils.isEmpty(F_Name_Holder) )
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
#Override
protected void onResume() {
super.onResume();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
//editUserId = (EditText)findViewById(R.id.editUserEmail);
// editUserId.setText(String.format("Email Id %s",account.getEmail()));
First_Name.setText(String.format("r%s", account.getId()));
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
}
If you can not do it, I'd like to know something else instead.
Why in my PHP code if I remove the Else from the IF Cycle the code does not work when it is started on Android studio?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'config.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$fk_id_ristorante = $_POST['fk_id_ristorante'];
$CheckSQL = "SELECT * FROM R_Iscrizioni WHERE data_scadenza < CURDATE() AND fk_id_ristorante='$fk_id_ristorante' AND pagamento = 'No' ";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Prova gratuita terminata';
}
else {
echo 'Hello';
}
}
mysqli_close($con);
?>
What you need to do is just use CountDownTimer to let system load and be ready to let your code be execute right way.
Hope this helped you.

Chrome Custom Tabs pre-load webpages while browsing?

I'm testing the Chrome Custom Tabs. It is supposed to preload webpages a user is likely to click in the background. This happens through calling
session.mayLaunchUrl(uri, null, null);
While the MainActivity is active, the webpage is preloaded nicely and when launching the URL, the webpage loads quickly as expected.
However I would like to serve other webpages automatically to the user while he is already browsing (and the activity therefore is in background). Then, preloading the webpages does not seem to speed up the loading process anymore and even though the new served webpages are loading, this happens slowly.
I wrote a small app demonstrating this behavior. Preloading and launching an URL manually works nicely (as the activity is active, I suppose), serving new webpages in a loop automatically is slow (as the activity is not active and the mayLaunchUrl method does not work as expected then).
Is it possible to make use of the pre-loading mechanism while the user is browsing already? If yes, how?
I added the MainActivity code as example below:
public class MainActivity extends AppCompatActivity {
private CustomTabsSession mCustomTabsSession;
private CustomTabsClient mClient;
private CustomTabsServiceConnection mConnection;
private EditText urlET;
private String TAG = "MainActivity";
private ArrayList<String> urlList;
private Thread cycleThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("MainActivity", "onCreate");
urlList = new ArrayList<>();
urlList.add("http://www.google.com");
urlList.add("https://github.com");
urlList.add("http://stackoverflow.com");
urlList.add("http://www.heise.de");
// pre launch the chrome browser, bind services etc
warmup();
urlET = (EditText) findViewById(R.id.urlID);
// pre load a webpage manually
Button prepareBt = (Button) findViewById(R.id.prepareBt);
assert prepareBt != null;
prepareBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mayLaunch(null);
}
});
//launch webpage manually
Button launchBt = (Button) findViewById(R.id.launchBt);
assert launchBt != null;
launchBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launch(null);
}
});
//start a loop that serves webpages every 10 seconds
Button cycleBt = (Button) findViewById(R.id.cycleBt);
assert cycleBt != null;
cycleBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cycleThread !=null)
cycleThread.interrupt();
cycleThread = new Thread(cycle);
cycleThread.start();
}
});
}
private Runnable cycle = new Runnable() {
#Override
public void run() {
int i = 0;
mayLaunch(Uri.parse(urlList.get(i)));
try {
Thread.sleep(5000);
while (true){
try {
Log.d(TAG, "launch: "+urlList.get(i));
launch(Uri.parse(urlList.get(i)));
i++;
if(i>=urlList.size())
i=0;
Thread.sleep(5000);
Log.d(TAG, "prepare: "+urlList.get(i));
mayLaunch(Uri.parse(urlList.get(i)));
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private void mayLaunch(Uri uri){
if(uri ==null)
uri = Uri.parse(urlET.getText().toString());
CustomTabsSession session = getSession();
session.mayLaunchUrl(uri, null, null);
}
private void launch(Uri uri){
if(uri ==null)
uri = Uri.parse(urlET.getText().toString());
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(getSession())
.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))
.setShowTitle(true)
.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.build();
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
customTabsIntent.launchUrl(this,uri);
}
public CustomTabsSession getSession() {
if (mClient == null) {
mCustomTabsSession = null;
} else if (mCustomTabsSession == null) {
mCustomTabsSession = mClient.newSession(null);
Log.d(TAG, "getSession: created new session");
}
return mCustomTabsSession;
}
private void warmup(){
if (mClient != null) return;
String packageName = "com.android.chrome";
if (packageName == null) return;
mConnection = new CustomTabsServiceConnection() {
#Override
public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) {
mClient = customTabsClient;
mClient.warmup(0L);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mClient = null;
mCustomTabsSession = null;
}
};
CustomTabsClient.bindCustomTabsService(this, packageName, mConnection);
}
private void coolDown(){
if (mConnection == null) return;
unbindService(mConnection);
mClient = null;
mCustomTabsSession = null;
mConnection = null;
}
public void onDestroy() {
Log.v("MainActivity", "onDestroy");
super.onDestroy();
coolDown();
}
#Override
public void onBackPressed(){
}
}
Thanks!
CustomTabs ignores mayLaunchUrl() sent from the background. This is for 2 reasons:
Simple measure to avoid wasted bandwidth (it is easy to check that a custom tab from the same session is not the foreground, just did not do it yet)
Pages loaded through mayLaunchUrl() currently do not preserve Window.sessionStorage(), which is not a problem for App -> CustomTab transition, but for navigating within a single CustomTab this may break assumptions for users with navigation patterns like:
SiteA -> SiteB -> SiteA
(the second visit to SiteA does not see what is in the session). Teaching mayLaunchUrl() to choose the right sessionStorage() is complex, no plans for this yet.

Categories

Resources