how to override permission manager in android - java

i m creating app that has permission to autostart with boot. and it is working fine on those mobile that does not contains Permission manager.
i want to start my app like Whats App and Wechat and other app does. But permission manager stop my app to auto start - MI Redme Note 4g mobile and Samsung mobile. Basically, i want to override the permission manager setting so that my app will start
currently i m using these code
<receiver
android:name=".BootComplete"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".AutoStartUp" >
</service>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Please Advice me to get my app auto start like Whats App, Wechat, Youtube and Other app does
thanks in Advance

What your code does here is that: When the device is booted it will tell the broadcast receiver, now the broadcast receiver needs to start the Service or App or whatever you want to start:
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent0) {
if(! isMyServiceRunning(MyFirstService.class, context)){//test
Intent startServiceIntent = new Intent(context, MyFirstService.class);
context.startService(startServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass,Context context) {
ActivityManager manager = (ActivityManager)context. getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
This code also checks if the Service is already running (for some reason) and you can remove that part if you want.

Related

USB broadcast receiver (ACTION_POWER) not working

I am trying to implement a basic receiver for USB connection. Found a reference here.
I searched a lot, but can't make it to work...
package com.example.usbtethering;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "USB connected.", Toast.LENGTH_SHORT).show();
Log.v("AAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAA");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.usbtethering">
<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.USBTethering">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/Theme.USBTethering.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
</manifest>
On emulator, I am changing the following setting:
I see the status is changing on the phone bar, but my code is not executed.
Any idea what I am missing?
TL;DR (XY)
My goal is to enable USB tethering automatically when connected to USB, only if hour is between 8:00-22:00. The idea is to block internet usage outside of the specified hours.
On the phone - settings, app-store, browsers, Youtube and hotspot are password locked. So the internet can only be used for Whatsapp, waze, and USB tethering. However this currently requires the "administrator" to manually enable/disable USB tethering in settings each time.
So I intend to create this app which I think should be simple, give it permission to change settings:
Enable tethering on each USB connection between 8:00 and 22:00.
Disable tethering (if enabled) on 22:00.
I have moderate C++/python programming experience, and some Java, but this is my first attempt to Android.
As part of the Android 8.0 (API level 26) Background Execution Limits,
apps that target the API level 26 or higher can no longer register
broadcast receivers for implicit broadcasts in their manifest.
However, several broadcasts are currently exempted from these
limitations. Apps can continue to register listeners for the following
broadcasts, no matter what API level the apps target.
So from the API > 28 Version you must register the reciver for that you can use this piece of code in your Activity or if you want to listen to the Power Connection changes in the background use a Service
IntentFilter ACTION_POWER_CONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
IntentFilter ACTION_POWER_DISCONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(new MyReceiver(), ACTION_POWER_CONNECTED);
registerReceiver(new MyReceiver(), ACTION_POWER_DISCONNECTED);
I believe you want to use a Service this is an example :
First you need to Create a Service (PowerSerivce) in the manifest file :
<service
android:name=".PowerService"
android:stopWithTask="false" />
<!-- If set to true,
this service with be automatically stopped when the user remove a task rooted in an activity owned by the application-->
And this is the PowerService.java :
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class PowerService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter ACTION_POWER_CONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
IntentFilter ACTION_POWER_DISCONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(new MyReceiver(), ACTION_POWER_CONNECTED);
registerReceiver(new MyReceiver(), ACTION_POWER_DISCONNECTED);
Log.d("Service", "onStartCommand: " );
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service", "onDestroy: " );
}
}
And this is MyReciver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.ACTION_POWER_CONNECTED")){
Toast.makeText(context, "CONNECTED", Toast.LENGTH_LONG).show();
}else if(intent.getAction().equals("android.intent.action.ACTION_POWER_DISCONNECTED")){
Toast.makeText(context, "DISCONNECTED", Toast.LENGTH_LONG).show();
}
}
}
And finaly you need to start this Service in my case i started it only for API>=26
normally in APIs below 26 you don't need this Service (you can check it by yourself). in this code I started the PowerService only for version above API 26
// add this code in your first activity or where you want
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startService(new Intent(this, PowerService.class)):
}
References :
Service
Implicit Broadcast
Exceptions

why restarting a device that has an application that restricts the use of UserManager.DISALLOW_USB_FILE_TRANSFER renders the device unusable?

I'm have created a kiosk application by following this guide in android developers - Lock Task Mode. The application can start itself automatically whenever the device finish booting up but the problem is whenever I restart/shutdown and start my device that has this restriction the device will not be able to boot it will stuck in the brand logo screen of the device and have to factory reset it to work again.
dpm.addUserRestriction(componentName, UserManager.DISALLOW_USB_FILE_TRANSFER);
This restriction is working fine if I don't restart the device but at some point the device needs to be shutdown. How can I set this restriction properly during start without breaking the deivce?
I found a workaround to solve the problem. I have created a BroadcastReceiver for device shutdown and remove the restriction and re-enable the restriction when the device restarts.
public class ShutDownReceiver extends BroadcastReceiver {
private static final String TAG = "ShutDownReceiver";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SHUTDOWN.equals(action)){
DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName cn = AdminReceiver.getComponentName(context);
if (dpm != null && dpm.isDeviceOwnerApp(context.getPackageName())) {
//This is a custom method
setUserRestriction(dpm, cn, UserManager.DISALLOW_USB_FILE_TRANSFER, false);
}
Toast.makeText(context, "Shutting Down", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onReceive: ACTION_SHUTDOWN");
}
}
}
Add code in manifest
<receiver android:name=".receiver.ShutDownReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.QUICKBOOT_POWEROFF" />
</intent-filter>
</receiver>

How to start activity or service (Either) on bootup completed?

I'm trying to find out how to run a service (Any service, may be foreground or background) when device boots. I've tried implementing broadcast receiver but it seems not to work.
Below is my full code.
1.AndroidManifext.xml - I made sure I included the service and broadcast receiver here. Are there any permissions I may be lacking?
<?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.testboot">
<!-- Example need below permission. -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name="com.example.testboot.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.example.testboot.BootDeviceReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name="com.example.testboot.RunAfterBootService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
2.MainActivity.java - This is the launch class, I made it call the broadcast receiver class. Asides from that, it doesn't have anything else.
package com.example.testboot;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("com.example.testboot.BootDeviceReceiver");
sendBroadcast(intent);
}
}
3.BootDeviceReceiver.java -This is the class responsible for knowing when device has booted up (Extends Broadcast receiver)
package com.example.testboot;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class BootDeviceReceiver extends BroadcastReceiver {
private static final String TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message = "BootDeviceReceiver onReceive, action is " + action;
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);
if(Intent.ACTION_BOOT_COMPLETED.equals(action))
{
//startServiceDirectly(context);
startServiceByAlarm(context);
}
}
/* Start RunAfterBootService service directly and invoke the service every 10 seconds. */
private void startServiceDirectly(Context context)
{
try {
while (true) {
String message = "BootDeviceReceiver onReceive start service directly.";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// This intent is used to start background service. The same service will be invoked for each invoke in the loop.
Intent startServiceIntent = new Intent(context, RunAfterBootService.class);
context.startService(startServiceIntent);
// Current thread will sleep one second.
Thread.sleep(10000);
}
}catch(InterruptedException ex)
{
Log.e(TAG_BOOT_BROADCAST_RECEIVER, ex.getMessage(), ex);
}
}
/* Create an repeat Alarm that will invoke the background service for each execution time.
* The interval time can be specified by your self. */
private void startServiceByAlarm(Context context)
{
// Get alarm manager.
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Create intent to invoke the background service.
Intent intent = new Intent(context, RunAfterBootService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
long intervalTime = 60*1000;
String message = "Start service use repeat alarm. ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// Create repeat alarm.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
}
}
3.RunAfterBootService.java - This is the service class, should be displayed after device completes booting up.
package com.example.testboot;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
public class RunAfterBootService extends Service {
private static final String TAG_BOOT_EXECUTE_SERVICE = "BOOT_BROADCAST_SERVICE";
public RunAfterBootService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onCreate() method.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String message = "RunAfterBootService onStartCommand() method.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onStartCommand() method.");
Intent i = new Intent();
i.setClass(RunAfterBootService.this,MainActivity.class);
startActivity(i);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
So far, when I restart my device nothing happens at all.
Has your app an icon ? you must open your app one time then you can receive the boot_complete broadcast.

Android WebView geolocation

I know this question has been asked a lot of time but i could not find any help.
I am trying to built an app that loads a website that uses geolocation.
When the app loads, it should open up a google map with my location on it. On a web browser it works fine.
link i am trying to access is https://pas.irsglobal.net/test/
My code is as follows.
//MainActivity.java
package za.co.opexsolutions.www.panicapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
/**
* WebViewClient subclass loads all hyperlinks in the existing WebView
*/
public class GeoWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
}
/**
* WebChromeClient subclass handles UI-related calls
* Note: think chrome as in decoration, not the Chrome browser
*/
public class GeoWebChromeClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
}
WebView wv;
String mypage = "https://pas.irsglobal.net/test/";
String mypage_error = "file:///android_asset/mypage_error/index.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.wv);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.setWebViewClient(new GeoWebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setGeolocationEnabled(true);
wv.setWebChromeClient(new GeoWebChromeClient());
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
// callback.invoke(String origin, boolean allow, boolean remember);
callback.invoke(origin, true, false);
}
});
wv.loadUrl(mypage);
wv.setWebViewClient(new WebViewClient(){
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
wv.loadUrl(mypage_error);
}
});
}
}
//Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.LOCATION_HARDWARE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/shipping"
android:label="#string/app_name"
android:roundIcon="#mipmap/shipping"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".HomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"></activity>
</application>
OK, After a some time of searching what could be the problem, I hope this will help others too.
The problem in this case it is not my code, but the Android version i was running on the emulator. (I was using Android 7 Nougat).
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
For full assistance Please Click Here

Intercept opening android setting of apps with BroadcastReceiver

I declared in AndroidManifest permission and receiver
<uses-permission android:name="android.permission.REAL_GET_TASKS"/>
<receiver android:name=".UninstallIntentReceiver">
<intent-filter android:priority="0">
<action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
<data android:scheme="package" />
</intent-filter>
</receiver>
And here is my java class receiver
public class UninstallIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String[] packageNames = intent.getStringArrayExtra("android.intent.extra.PACKAGES");
if(packageNames!=null){
for(String packageName: packageNames){
Log.d("User selected: ",packageName);
}
}
}
When I open settings of other apps it works well - I get notification
(I can see in logs package name of chosen application), but
when I open settings my own application, I don't receive anything

Categories