Why my Android App is not scanning Bluetooth device? - java

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>

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.

Android Widget freezes after some time

I have made a counter widget. There are two buttons, one to increase and one to decrease the number. The number is displayed on a TextView. At first everything works just fine, but after some time (usually around an hour) the Textview freezes i.e. I click the buttons but the number doesen't change.
When I click the buttons, the "clicking animation" is still played, so the buttons might still work.
When I remove the widget and replace it again, the widget starts to work again but the same problem occurs after around the same time.
The code is here:
WidgetProvider
package com.example.myapplication;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class WidgetProvider1 extends AppWidgetProvider {
String widgettextviewtext;
final String INCREASE= "sdfjkldjldkf";
final String DECREASE = "skdhbcvouweoaior";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
MainActivity.zahl = 15;
remoteViews.setTextViewText(R.id.textView, ""+MainActivity.zahl);
remoteViews.setOnClickPendingIntent(R.id.button3,onClickPendingIntent(context,ZAHLGROESSER) );
remoteViews.setOnClickPendingIntent(R.id.button2,onClickPendingIntent(context,ZAHLKLEINER) );
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
updateWidgetNow(context,remoteViews);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
//if increase button is clicked
if(intent.getAction().equals(INCREASE)){
if(MainActivity.zahl == 15) {
Toast.makeText(context, "STOOOP!!!", Toast.LENGTH_SHORT).show();
}else{
MainActivity.number = MainActivity.number+1;
String text=""+ MainActivity.number;
remoteViews.setTextViewText(R.id.textView, text);
updateWidgetNow(context, remoteViews);
}
}
//if decrease button is clicked
if(intent.getAction().equals(DECREASE)) {
if (MainActivity.number == 0) {
Toast.makeText(context, "Hurray!", Toast.LENGTH_SHORT).show();
}else{
MainActivity.number = MainActivity.number - 1;
String text = "" + MainActivity.number;
remoteViews.setTextViewText(R.id.textView, text);
updateWidgetNow(context, remoteViews);
}
}
super.onReceive(context, intent);
}
public void updateWidgetNow (Context context, RemoteViews remoteViews){
ComponentName widgetComponent = new ComponentName(context, WidgetProvider1.class);
AppWidgetManager.getInstance(context).updateAppWidget(widgetComponent, remoteViews);
}
public PendingIntent onClickPendingIntent (Context context, String stringAction){
Intent onClickIntent = new Intent(context, WidgetProvider1.class);
onClickIntent.setAction(stringAction);
return PendingIntent.getBroadcast(context,0,onClickIntent,PendingIntent.FLAG_UPDATE_CURRENT);
}
}
MainActivity:
package com.example.myapplication;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public static int number = 15;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission android:name="android.permission.VIBRATE"/>
<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:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="#string/app_name"
android:theme="#style/Theme.MyApplication">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.myapplication.WidgetProvider1"
android:label="Tutorial Widget"
android:exported="true"
>
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info"
/>
</receiver>
</application>
</manifest>
WidgetInfo:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="180dp"
android:minWidth="180dp"
android:initialLayout="#layout/widget_layout"
android:previewImage="#drawable/widget_preview"
android:widgetCategory="home_screen"
android:resizeMode="horizontal|vertical"
>
</appwidget-provider>
WidgeLayout:
<?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"
android:theme="#style/Theme.AppCompat.Light"
android:id="#+id/widget_layout"
>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="220dp"
android:layout_centerInParent="true"
android:text="1"
android:textAlignment="center"
android:textSize="150dp"
android:textColor="#color/white"
/>
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/textView"
android:layout_marginBottom="1dp"
android:text="increase"
android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"
android:textSize="30dp"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView"
android:layout_marginTop="1dp"
android:text="decrease"
android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"
android:textSize="30dp"
/>
</RelativeLayout>

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>

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

Bluetooth adapter is remaining null in android

I have a problem while writing code of bluetooth adapter in android. Bluetooth adapter is always remains null. I have written code for that but I could not turn on the bluetooth.
My Code is as below
package com.example.bluetoothdemo;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class MainActivity extends Activity {
String msg="Hello";/* Default message to be sent. */
BluetoothAdapter adpt=null;// Default it is set to null value.
public static String MacAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.button_send);
final TextView tv=(TextView)findViewById(R.id.disp_msg);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adpt=BluetoothAdapter.getDefaultAdapter();
if(adpt==null){
// Always this portion is generating errors.
tv.append("Bluetooth Not Available in device");
Toast.makeText(getApplicationContext(), "Bluetooth is off",Toast.LENGTH_LONG).show();
}
else{
if(!adpt.isEnabled()){
//adpt.enable();
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivity(i);
startActivityForResult(i, 0);
tv.append("Bluetooth is turned on.");
}
}
byte[] toSend=msg.getBytes();
try{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=adpt.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
socket.connect();
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
Toast.makeText(getBaseContext(), MacAddress, Toast.LENGTH_SHORT).show();
}catch(IOException e){
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
My activity_main.xml file is as below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
<TextView android:id="#+id/disp_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/display"
/>
</LinearLayout>
My AndroidMenifest.xml file is as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.bluetoothdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>-
I have created the .apk file also and run on my Micromax A89 Ninja phone but the error says that "BluetoothDemo has been stopped unexpectedly."
Please write the below line
adpt=BluetoothAdapter.getDefaultAdapter();
in OnCreate() method after this line,
setContentView(R.layout.activity_main);

Categories

Resources