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

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();

Related

Issue in making UPI payment request from android

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.

Image not showing(Blank space) while using glide library in android

Image is showing nothing not even the image I chose as default no error nothing just the image cannot be loaded I granted internet permission still this is happening plz help
No error is there in logcat.
App launches everything is fine but the image wont load i tried waiting still and the API is working fine......i dunno if its my code or the permission which is causing this...
Java Code
package com.example.meme_share;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
ImageView i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView i = findViewById(R.id.imageView);
}
public void loadmeme() {
RequestQueue a = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest b = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String u = null;
try {
u = response.getString("url");
System.out.println("Raunak"+u);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Raunak"+u);
Glide.with(MainActivity.this).load(u).into(i);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
});
}
}
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">
<Button
android:id="#+id/button2"
android:layout_width="182dp"
android:layout_height="71dp"
android:layout_marginTop="134dp"
android:text="Next"
app:backgroundTint="#android:color/tertiary_text_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.93"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/imageView"
android:layout_width="415dp"
android:layout_height="538dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06"
tools:srcCompat="#drawable/ic_launcher_background" />
<Button
android:id="#+id/button"
android:layout_width="182dp"
android:layout_height="71dp"
android:layout_marginTop="134dp"
android:text="Share"
app:backgroundTint="#android:color/tertiary_text_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.956" />
</androidx.constraintlayout.widget.ConstraintLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.meme_share">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<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.Meme_Share">
<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>
You have created two ImageView i; variables: first in onCreate methon and second in class scope.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = findViewById(R.id.imageView); // < here
}
Besides this problem here are some others:
You don't call loadmeme method anywhere
You don't make network request
ImageView imageView; // 1. Use class scoped imageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
// 2. Run loadmeme method
loadmeme();
}
public void loadmeme() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String u = null;
try {
u = response.getString("url");
System.out.println("Raunak" + u);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Raunak" + u);
Glide.with(MainActivity.this).load(u).into(imageView);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
});
// 3. Add request to queue
requestQueue.add(jsonObjectRequest);
}

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>

Android - Service does not start

I am making app for me and my class mates, that checks for new homeworks and exams. It has service that may not be killed beacuse of checking school server (like every 5 minutes) for changed size of file with list of exams and stuff like this. I tried following code:
MayinActivity.java
package com.test.simpleservice;
import android.app.ActivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//checking runings services - remove later
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
String message = null;
for (int i=0; i<rs.size(); i++) {
ActivityManager.RunningServiceInfo
rsi = rs.get(i);
System.out.println("!!!!!!!!!!Service" + "Process " + rsi.process + " with component " + rsi.service.getClassName());
message = message + rsi.process;
}
Button btnStart = (Button) findViewById(R.id.startBtn);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ServiceManager.startService(getApplicationContext());
}
});
}
}
MyServices.java
package com.test.simpleservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyServices extends Service {
private static final String LOGTAG = "MyServices";
#Override
public void onStart(Intent intent, int startId) {
System.out.println("start...");
//some code of your service starting,such as establish a connection,create a TimerTask or something else
Toast.makeText(this, "service start", Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//this will start service
System.out.println("startcommand...");
Toast.makeText(this, "service startcomand", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
//this will NOT kill service
//super.onDestroy();
Toast.makeText(this, "task destroyed", Toast.LENGTH_LONG).show();
Intent in = new Intent();
in.setAction("PreventKilling");
sendBroadcast(in);
}
#Override
public void onTaskRemoved(Intent intent){
Toast.makeText(this, "task removed", Toast.LENGTH_LONG).show();
intent = new Intent(this, this.getClass());
startService(intent);
}
}
Reciever.java
package com.test.simpleservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class Receiver extends BroadcastReceiver {
private static final String LOGTAG = "Receiver";
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyServices.class);
context.startService(serviceIntent);
}
Log.d(LOGTAG, "ServiceDestroy onReceive...");
Log.d(LOGTAG, "action:" + intent.getAction());
Log.d(LOGTAG, "ServiceDestroy auto start service...");
ServiceManager.startService(context);
}
}
ServiceManager
package com.test.simpleservice;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceManager {
private static final String LOGTAG = "ServiceManager";
public static void startService(Context context) {
Log.i(LOGTAG, "ServiceManager.startSerivce()...");
Intent intent = new Intent(MyServices.class.getName());
intent.setPackage("com.test.simpleservice");
context.startService(intent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.simpleservice">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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>
<service android:name=".MyServices" />
<receiver android:name=".Receiver" >
<intent-filter>
<action android:name="PreventKilling" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.RECIEVE_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.test.simpleservice.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_btn"
android:id="#+id/startBtn"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
When I run the app and click button "start", the service wont start - no toasts, no logs, nothing in setting->apps->services. Why? Any better way to make unkillable process without anoying notification?
logcat
last few lines becouse that before are just listed services:
01-16 14:10:15.567 13753-13772/com.test.simpleservice I/OpenGLRenderer: Initialized EGL, version 1.4
01-16 14:10:15.567 13753-13772/com.test.simpleservice W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
01-16 14:10:15.587 13753-13772/com.test.simpleservice D/OpenGLRenderer: Enabling debug mode 0
01-16 14:10:17.597 13753-13753/com.test.simpleservice I/ServiceManager: ServiceManager.startSerivce()...
And one more question: will this app start after boot? If not, what did I do wrong?
im sorry for my poor english
Intent intent = new Intent(context, MyServices.class);
intent.setPackage("com.test.simpleservice");
context.startService(intent);
Because your context is:
public static void startService(Context context)
And here :
public void onReceive(Context context, Intent intent)
For above Intent name -> intent

Splash screen in Android glitch

I have developed a splash screen in Android which comes for 2 seconds and go to the main activity. The problem is that when I start the application the main activity comes for few milliseconds and then goes to the splash screen activity. Can I know the solution for this?
splashscreen.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
public class splashscreen extends Activity {
private static int splashInterval = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
etWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(splashscreen.this, MainActivity.class);
startActivity(i);
this.finish();
}
private void finish() {
// TODO Auto-generated method stub
}
},
splashInterval);
};
}
splashscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<ImageView android:src="#drawable/splash" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitXY"/>
<ProgressBar android:id="#+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="58dp" />
</RelativeLayout>
Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="asdf.splashtest1" >
<application android:allowBackup="true" android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity android:name=".splashscreen" android:label="#string/app_name" android:screenOrientation="portrait" android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Main activity -->
<activity android:name=".MainActivity" android:label="#string/app_name" ></activity>
</application>
</manifest>
//MainActivity.java
package asdf.splashtest1;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This is my Splash Code Maybe This will helps,
Thread Background = new Thread() {
public void run() {
try {
sleep(2000);
Intent intent = new Intent(splashscreen.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
}
};
Background.start();
}
At sleep(2000), enter your desired time in milliseconds.
Edit
private class SplashTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
finish();
Intent intent = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(intent);
}
}
Call This Async with in onCreate Method new SplashTask().execute();

Categories

Resources