Issue in making UPI payment request from android - java

UPI payment failed in PhonePe while testing my android application.
The error it is showing is - For security reasons, you are not allowed to send money from your bank account for this payment. You don't have to enter UPI PIN to receive money/cashback.
MainActivity.java contains -
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button pay_btn;
final int UPI_PAYMENT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pay_btn = (Button) findViewById(R.id.pay_btn);
pay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
payUsingUpi("1","Test Payment","Ratnadeep Parya","parya.ratnadeep125#okaxis");
}
});
}
private void payUsingUpi(String amounttxt, String notetxt, String nametxt, String upitxt) {
Uri uri = Uri.parse("upi://pay").buildUpon()
.appendQueryParameter("pa",upitxt)
.appendQueryParameter("pn",nametxt)
.appendQueryParameter("tn",notetxt)
.appendQueryParameter("am",amounttxt)
.appendQueryParameter("cu","INR")
.build();
Intent upi_payment = new Intent(Intent.ACTION_VIEW);
upi_payment.setData(uri);
Intent chooser = Intent.createChooser(upi_payment,"Pay with");
if (null!=chooser.resolveActivity(getPackageManager())){
startActivityForResult(chooser,UPI_PAYMENT);
}
else {
Toast.makeText(this, "No UPI app found!", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case UPI_PAYMENT:
if ((RESULT_OK==resultCode|| (resultCode==11))){
if (data!=null){
String txt = data.getStringExtra("response");
Log.d("UPI", "onActivityResult: "+ txt);
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
else {
Log.d("UPI", "onActivityResult: "+ "Return data is null!");
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
}
else {
Log.d("UPI", "onActivityResult: "+ "Return data is null!");
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
break;
}
}
private void upipaymentdataoperation(ArrayList<String> data) {
if (isConnectionAvailable(MainActivity.this)){
String str = data.get(0);
Log.d("UPIPAY", "upipaymentdataoperation: "+str);
String paymentCancel="";
if (str==null)str="discard";
String status = "";
String approvalref = "";
String response[]=str.split("&");
for (int i=0;i<response.length;i++){
String equalStr[]=response[i].split("=");
if (equalStr.length>=2){
if (equalStr[0].toLowerCase().equals("Status".toLowerCase())){
status=equalStr[1].toLowerCase();
}
else if(equalStr[0].toLowerCase().equals("approval Ref".toLowerCase())||
equalStr[0].toLowerCase().equals("txnRef".toLowerCase()))
{
approvalref=equalStr[1];
}
}
else {
paymentCancel="Payment cancelled by user";
if (status.equals("success")){
Toast.makeText(this, "Transaction success", Toast.LENGTH_SHORT).show();
Log.d("UPI", "responsestr: "+approvalref);
}
else if ("Payment cancelled by user".equals(paymentCancel)){
Toast.makeText(this, "Payment cancelled by user", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Transaction failed", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText(this, "No internet", Toast.LENGTH_SHORT).show();
}
}
private boolean isConnectionAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager!=null){
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null && networkInfo.isConnected() && networkInfo.isConnectedOrConnecting() && networkInfo.isAvailable()){
return true;
}
}
return false;
}
}
AndroidManifest.xml contains -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.UpiTesting"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml contains -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context=".MainActivity">
<Button
android:id="#+id/pay_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pay_with_upi"
android:backgroundTint="#android:color/holo_green_dark"
android:layout_centerInParent="true"
android:textSize="20sp"/>
</RelativeLayout>
Please assist me to get rid of this issue.
I was trying to test UPI payment by sending request in UPI application.
In PhonePe it is showing that - For security reasons, you are not allowed to send money from your bank account for this payment. You don't have to enter UPI PIN to receive money/cashback.

Related

Why my Android App is not scanning Bluetooth device?

In my Bluetooth App I have created two buttons one for getting paired devices and the other to scan the Bluetooth device. When I click the scan button Toast message shows no device found, the code always goes to else part in my broadcast receiver. Can someone explain to me what's happening*
** MainActivity.java **
package com.example.broadcast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_ENABLE_BT = 2;
private Button scanButton;
private Button discoverButton;
private MyBroadcast broadcast;
private MyBroadcastdiscover broadcastdiscover;
public BluetoothAdapter bluetoothAdapter;
public Set<BluetoothDevice> pairedDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcast=new MyBroadcast();
broadcastdiscover=new MyBroadcastdiscover();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
scanButton=(Button) findViewById(R.id.scan_btn);
discoverButton=(Button) findViewById(R.id.discover_btn);
scanButton.setOnClickListener(this);
discoverButton.setOnClickListener(this);
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Device doesn't support bluetooth", Toast.LENGTH_LONG).show();
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(broadcast, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcast);
unregisterReceiver(broadcastdiscover);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcast);
unregisterReceiver(broadcastdiscover);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.scan_btn:
{
pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
ArrayList list = new ArrayList();
list.add(device.getName());
Toast.makeText(getApplicationContext(),deviceName,Toast.LENGTH_LONG).show();
}
break;
}
}
case R.id.discover_btn:
{
Toast.makeText(getApplicationContext(),"SCAN",Toast.LENGTH_LONG).show();
/* Intent discoverableIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
startActivity(discoverableIntent);*/
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
checkBTPermission();
bluetoothAdapter.startDiscovery();
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
if(!bluetoothAdapter.isDiscovering())
{
bluetoothAdapter.startDiscovery();
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
break;
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermission() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d("TAG", "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
}
** MyBroadcastdiscover.java**
package com.example.broadcast;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
public class MyBroadcastdiscover extends BroadcastReceiver {
public ArrayList<BluetoothDevice> mBTDevices=new ArrayList<>();
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Toast.makeText(context,action,Toast.LENGTH_LONG).show();
if(action.equals(BluetoothDevice.ACTION_FOUND))
{
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Toast.makeText(context,deviceName,Toast.LENGTH_LONG).show();
Log.d("TAG",deviceHardwareAddress);
}
else {
Toast.makeText(context,"NO DEVICE YET FOuND",Toast.LENGTH_LONG).show();
Log.d("TAG","DEVICE NOT FOUND");
}
}
}
** AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- If your app targets Android 9 or lower, you can declare
ACCESS_COARSE_LOCATION instead. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Broadcast">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
** activitymain.xml**
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.119" />
<Button
android:id="#+id/scan_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="108dp"
android:text="#string/scanDevice"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<Button
android:id="#+id/discover_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="92dp"
android:text="#string/scanningdevice"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/scan_btn" />
</androidx.constraintlayout.widget.ConstraintLayout>
You must declare the service inside aplication in Manifest.xml like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Broadcast">
...
<receiver android:name="com.example.broadcast.MyBroadcastdiscover" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACTION_FOUND" />
</intent-filter>
</receiver>
</application>

No reaction for reciving SMS, BroadcastReceiver

I'm new in Android and I tried to receive SMS by my application. Sending SMS is working, so permission should work. First I wanted to show received SMS text in Toast, but I read it would be better to use Log. I'm using it and I not have any sign from BroadcastReciver.
I've tried to add receiver in manifest and Log for view is it working, but I not have anything in logs
MainActivity:
package pl.edu.pwr.student.a235420_ks_a5;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button importSimData;
private Button sendMessage;
private EditText smsMessagePhoneNumber;
private EditText smsMessageText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
importSimData = findViewById(R.id.button1);
sendMessage = findViewById(R.id.button2);
smsMessagePhoneNumber = findViewById(R.id.editText1);
smsMessageText = findViewById(R.id.editText2);
SmsReceiver myReciver = new SmsReceiver();
Log.i("MAIN_ACTIV", "On create");
importSimData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
Toast.makeText(MainActivity.this, "NO permission!",
Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, "Add permissions in settings",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "you have permission!",
Toast.LENGTH_LONG).show();
TelephonyManager tm = (TelephonyManager) MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
int phoneType = tm.getPhoneType();
int phoneCallState = tm.getCallState();
int phoneNetworkType = tm.getDataNetworkType();
String phoneSubscriberId = tm.getSubscriberId();
Toast.makeText(MainActivity.this, String.valueOf(phoneType),
Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, String.valueOf(phoneCallState ),
Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, String.valueOf( phoneNetworkType),
Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, phoneSubscriberId,
Toast.LENGTH_LONG).show();
}
}
});
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
//NO permission
Toast.makeText(MainActivity.this, "NO permission!",
Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, "Add permissions in settings",
Toast.LENGTH_LONG).show();}
else {
//you have
String phoneNumber = smsMessagePhoneNumber.getText().toString();
String smsText = smsMessageText.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, smsText, null, null);
}
}
});
}
}
SMSReceiver:
package pl.edu.pwr.student.a235420_ks_a5;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_REC_ACTION =
"android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("SMS_RECIVER", "Recived Broadcast");
if (intent.getAction().
equals(SmsReceiver.SMS_REC_ACTION)) {
Log.i("SMS_RECIVER", "Recived SMS");
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])
bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage smsMessage =
SmsMessage.createFromPdu
((byte[]) pdu);
sb.append("body - " + smsMessage.
getDisplayMessageBody());
}
}
Toast.makeText(context, "SMS RECEIVED - "
+ sb.toString(), Toast.LENGTH_LONG).show();
}
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pl.edu.pwr.student.a235420_ks_a5">
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SmsReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="PACKAGE_NAME.android.action.broadcast"/>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
I would like to get text from incomming SMS in my app and show it in Log or better in Toast

How to fix this Java code to upload file with webview element android studio

Developing very basic app for my site to upload files to server using a webview to emulate the desktop process, failing to get it to work.
I have copied code from GitHub to form this app, however when I press the input button on the HTML form I am prompted to select a file from my phone's storage, after doing so the selected file doesn't show up in the HTML form, and pressing the button again results in no action. I've no idea why and I really don't know Java, can anyone help? (YouTube video of original GitHub poster - https://www.youtube.com/watch?v=oFGQbXdWv-g) (Github page - https://github.com/tarikul1988/WebViewFileUploadWorking)
The entire project code is as follows;
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.xyz.imagedrop.MainActivity">
<WebView
android:id="#+id/webview_sample"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
MainActivity.java:
package com.xyz.imagedrop;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview_sample);
if (Build.VERSION.SDK_INT >= 23 &&(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
//webView.loadUrl("https://infeeds.com/");
webView.loadUrl("http://imagedrop.xyz");
webView.setWebChromeClient(new WebChromeClient() {
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
// Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent contentSelectionIntent = new
Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
// Intent[] intentArray;
//
// if (takePictureIntent != null) {
// intentArray = new Intent[]{takePictureIntent};
// } else {
// intentArray = new Intent[0];
// }
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT,
contentSelectionIntent);
// chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image
Chooser");
// chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
});
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String
description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!",
Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xyz.imagedrop">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
</uses-permission>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

unable to start android service from activity that is in the different package

I am new to android stack. I am trying to start android service from the launcher activity. Service and Activity are defined in separate packages but it is not being started. In the logcat there is no exception or error. I have checked many questions on stackoverflow regarding this issue but that didn't worked. Below are the source code of my app. I have spent almost 8 hours on this issue. Any help would be great appreciation.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.test.app">
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".messaging.AlertService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
AlertService.java:
package nl.test.app.messaging;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class AlertService extends Service {
public AlertService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "on create called\n", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
LoginActivity.java
package nl.test.app.ui;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import nl.test.app.R;
public class LoginActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
// function for service testing
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent();
String pkg = "nl.test.app.messaging";
String cls = "nl.test.app.messaging.AlertService";
myIntentToStartAlertListActivity.setComponent(new ComponentName(pkg, cls));
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
}
}
Try this
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent(LoginActivity.this, AlertService.class);
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
// function for service testing
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent(LoginActivity.this,AlertService.class);
String pkg = "nl.test.app.messaging";
String cls = "nl.test.app.messaging.AlertService";
myIntentToStartAlertListActivity.setComponent(new ComponentName(pkg, cls));
//startService(myIntentToStartAlertListActivity)
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}

Unable to create facebook login in android application cannot find symbol method getAccessToken()

I am creating a facebook login for my android application. I am getting following below errors which i tried to solve but i can not because i am unable to find solution.
1) Error:(46, 46) error: cannot find symbol method getAccessToken()
2) Error:(41, 55) error: incompatible types: > cannot be converted to FacebookCallback
My activity_main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5b9bd5"
tools:context="com.example.ratingapp.ratingapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/info"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="18sp"
/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</android.support.constraint.ConstraintLayout>
My MainActivity.java is:
package com.example.ratingapp.ratingapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.accountkit.LoginResult;
import com.facebook.login.LoginManager;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
import java.util.List;
import static android.R.attr.data;
public class MainActivity extends AppCompatActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
info.setText(
"User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken()
);
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException exception) {
info.setText("Login attempt failed.");
}
});
}
}
Please help me solve these errors what i am doing wrong in this code.
Please alsoc check my AndroidManifest.xml incase i put a wrong facebook library.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ratingapp.ratingapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
/manifest>
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess (final LoginResult loginResult)
{
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted (JSONObject object, GraphResponse response)
{
try
{
String id = response.getJSONObject().getString("id");
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordEditText.getWindowToken(), 0);
if (connect())
{
/*ENTER*/
}
else
{
Toast.makeText(getApplicationContext(), textProblemConnecting(), Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("YOUR FIELDS");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel ()
{
}
#Override
public void onError (FacebookException e)
{
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, email, id, last_name, birthday, locale");
request.setParameters(parameters);
request.executeAsync();

Categories

Resources