How to connect wifi with NetworkSpecifier? - kotlin

Permission(AndroidManifest.xml)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
WifiConnector.kt
val builder = WifiNetworkSpecifier.Builder()
builder.setSsid("test1234")
builder.setWpa2Passphrase("12345678")
val wifiNetworkSpecifier = builder.build()
val networkRequestBuilder1 = NetworkRequest.Builder()
networkRequestBuilder1.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
networkRequestBuilder1.setNetworkSpecifier(wifiNetworkSpecifier)
val nr = networkRequestBuilder1.build()
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
cm.bindProcessToNetwork(network)
}
}
cm.requestNetwork(nr, networkCallback);
Test device android version
Android API 29
Hello
I used WifiNetworkSpecifier to connect to a specific Wifi.
https://developer.android.com/guide/topics/connectivity/wifi-bootstrap
I made it by referring to the document
The message appears.
"Something came up. The application has cancelled the request to choose a device"
I think the app is printing the message because it doesn't have the necessary permissions to connect to WiFi.
If you know why it's not working, please let me know

Related

Foreground Service Not Updating Sensors Data In Background

I am new in Android Development, I've created an application with API version 29 using Kotlin. My main activity is launching a Foreground Service which is doing the following tasks.
Getting Location using the FusedLocationProviderClient.
Getting Sensor Data (Accelerometer and Gyroscope)
Showing the above information in a Notification
The application is supposed to get the Location and Sensors information in the background and update the Notification.
The Application is currently updating the Sensors and Location data when the Main Activity application is running. Once the Main Activity is closed, the Location data gets updated in the Notification but the Sensor data is not being updated. I've read some QnA sessions (including this) but I'm unable to figure out the issue.
Code To Launch Service:
val serviceIntent = Intent(this, MyBackgroundService::class.java);
serviceIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
startForegroundService(serviceIntent);
Permissions & Features in Manifest:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<uses-feature android:name="android.hardware.sensor.gyroscope" android:required="true" />
Foreground Service in Manifest:
<service android:name=".MyBackgroundService"
android:enabled="true"
android:exported="true"
android:foregroundServiceType="location"
android:icon="#drawable/logo"
android:process=":MyBackgroundServiceProcess"/>
I am wondering if there is any foregroundServiceType to continuously get the Sensor values when the Main Activity is closed.

How Can I Use BroadcastReceiver on API 26 and Higher?

I'm developing an Android App. Users can chat each other. I fetch the messages on PushReceiver class. App opened or closed I mean foreground or background; the code block working from API 19 to API 26 but not working higher than API 26. I try to debug onReceive function but it's not call on Android O.
I want to say again. My code block working API 25 and lower versions.
I'm using pushy.me service.
My BroadcastReceiver Class:
public class PushReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String notificationTitle = "Title";
String notificationText = "Text";
Bundle bundle = intent.getExtras();
JSONObject jsonObject = new JSONObject();
for (String key : bundle.keySet()) {
try {
jsonObject.put(key, wrap(bundle.get(key)));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
notificationText = jsonObject.get("body").toString();
notificationTitle = jsonObject.get("title").toString();
} catch (Exception e) {}
// Prepare a notification with vibration, sound and lights
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setLights(Color.RED, 1000, 1000)
.setVibrate(new long[]{0, 400, 250, 400})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
// Automatically configure a Notification Channel for devices running Android O+
Pushy.setNotificationChannel(builder, context);
// Get an instance of the NotificationManager service
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Build the notification and display it
notificationManager.notify(1, builder.build());
}
}
My Manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
...
<receiver
android:name=".Notification.PushReceiver"
android:exported="false">
<intent-filter>
<!-- Do not modify this -->
<action android:name="pushy.me" />
</intent-filter>
</receiver> <!-- Pushy Update Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver
android:name="me.pushy.sdk.receivers.PushyUpdateReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver> <!-- Pushy Boot Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver
android:name="me.pushy.sdk.receivers.PushyBootReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver> <!-- Pushy Socket Service -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushySocketService" /> <!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service
android:name="me.pushy.sdk.services.PushyJobService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE" />
Edit: pushy.me Android Demo here
The latest Pushy Android SDK has added support for Android O power saving optimizations (App Standby / deprecation of Service), please update by following the instructions on this page:
https://pushy.me/docs/android/get-sdk
Also, make sure to add the following new JobService declaration to your AndroidManifest.xml, under the <application> tag:
<!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushyJobService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true" />

Android 7 open APK with ACTION_VIEW not working (Package installer has stopped)

My app has an auto update feature which download an APK and then uses a Intent.ACTION_VIEW to open the package installer.
Up to 7 it worked perfectly (by feeding the Intent with a normal file://)
With Android 7 I had to change to use a FileProvider. The only difference in the code is:
Intent installIntent = new Intent(Intent.ACTION_VIEW);
if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
installIntent.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
} else {
Uri apkUri = FileProvider.getUriForFile(AutoUpdate.this,
BuildConfig.APPLICATION_ID, file);
installIntent.setDataAndType(apkUri,manager.getMimeTypeForDownloadedFile(downloadId));
}
activity.startActivity(installIntent);
Once the startActivity is called I get this every single time
Is this a bug with Android 7 ? Or something/permission is missing my side ?
EDIT AndroidManifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_LOGS" />
<application ...>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myapp"
android:exported="false"
android:enabled="true"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
The path xmlfile
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="myfolder" path="."/>
</paths>
try like below, it helped me and its working in Android N7.0.
File toInstall = new File(appDirectory, appName + ".apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(intent);
} else {
Uri apkUri = Uri.fromFile(toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
Try to add read uri permission to your intent:
installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Check this answer
https://stackoverflow.com/a/40131196/1912947

Recieving Sms using a broadcast receiver-xamarin

My last question was not a great question.
so here my new one.
I want to write an app that has and activity which get some info(like a phone number) from the user and then It is destroyed and the app icon is also hidden from the user.but i want to continuously receive sms from that phone number and do some stuff.
until now i have learned that if i register my broadcast receiver in the manifest it can still receive even though my app is not running or hidden.
so here is my app which i'm using xamarin (mono android):
my simple activity (it is not complete yet):
my main XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:p1="http://schemas.android.com/apk/res/android"
p1:orientation="vertical"
p1:minWidth="25px"
p1:minHeight="25px"
p1:layout_width="match_parent"
p1:layout_height="match_parent"
p1:id="#+id/linearLayout1">
<EditText
p1:layout_width="match_parent"
p1:layout_height="wrap_content"
p1:id="#+id/txt_phone" />
<Button
p1:text="OK"
p1:layout_width="match_parent"
p1:layout_height="wrap_content"
p1:id="#+id/btn_ok" />
</LinearLayout>
and the activity class:
namespace SmsBroadcastReceiver
{
[Activity (Label = "SmsBroadcastReceiver", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
EditText txt_number = FindViewById<EditText> (Resource.Id.txt_phone);
Button btn_ok = FindViewById<Button> (Resource.Id.btn_ok);
btn_ok.Click += delegate {
//save the number in the sharedpreference and then...
Toast.MakeText (Context, "Your App Will be Closed now", ToastLength.Short).Show ();
};
}
}
}
now my broadcast receiver:
namespace SmsBroadcastReceiver
{
[BroadcastReceiver]
public class SmsReceiver : BroadcastReceiver
{
public override void OnReceive (Context context, Intent intent)
{
Toast.MakeText (context, "sms rec", ToastLength.Long).Show ();
//get the sharedpreference and then do stuff
}
}
}
and my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="SmsBroadcastReceiver.SmsBroadcastReceiver">
<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="18" />
<application android:label="SmsBroadcastReceiver">
</application>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
</manifest>
I know that the using a toast in a BR is not ideal but i just want to see that it is working which is not,everytime i send and sms to my phone it doesn't show anything.
where is my problem?
I think, you created BroadcastReceiver in the wrong way.
You should create it entirely with xamarin attributes.
Mono for Android translates each IntentFilterAttribute into an <intent-filter/> element.
[BroadcastReceiver]
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SmsReceiver : BroadcastReceiver
{
...
}
therefore there is no need to write receiver tags manually in your AndroidManifest file.
You can also use attribute's named parameters for Priority, Categories, etc.
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = Int32.MaxValue)]

MonoDroid device registeration for push notifications using PushSharp

In my monodroid application I have a problem registering some devices for push notifications using pushSharp. My general push notification setup works fine on newer devices such as SGS2, SGS3 and Nexus7, however on Legend and Hero running 2.2 and 2.2.1 the registration fails in release (works fine in debug).
I have narrowed down the problem to the StartService call:
var intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.SetPackage(GSF_PACKAGE);
intent.PutExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
PendingIntent.GetBroadcast(context, 0, new Intent(), 0));
intent.PutExtra(GCMConstants.EXTRA_SENDER, senders);
context.StartService(intent);
The manifest file looks fine:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
...
<!-- Google Cloud Messaging (GCM) for push messages -->
<permission android:name="my.package.name.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="my.package.name.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
The intent looks fine (act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gsf) and the senderId is correct, but the GCMIntentService OnReceive method is never triggered...
Sometimes the following error message can be seen using logcat (although not consistently):
E/C2DMRegistrar( 302): [C2DMReg] handleRequest caught java.io.IOException: SSL shutdown failed: I/O error during system call, Broken pipe.
I am not really sure how to solve this problem and would appreciate any help.
Thanks
Peter
You don't need these permissions as they should be set within your pushsharp code...
<permission android:name="my.package.name.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="my.package.name.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />