i am unable to use GetPackageManager in my BroadcastReceiver, i am getting the error "The method getPackageManager() is undefined for the type ReceiverSchedulerDaily". below is my code
public class ReceiverSchedulerDaily extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// clean all app caches
PackageManager pm = getPackageManager();
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorageAndNotify")) {
try {
long desiredFreeStorage = Long.MAX_VALUE;
m.invoke(pm, desiredFreeStorage, null);
} catch (Exception e) {
}
break;
}
}
//
}
}
Instead of the line:
PackageManager pm = getPackageManager();
Use this:
PackageManager pm = context.getPackageManager();
The code you are using was probably used in an Activity before, which is a subclass of Context. But you are using it in a BroadCastReceiver now, which does not extend Context. So you have to use a Context reference instead, to get the reference to the Package Manager system service.
Related
I want to write Firebase's InstanceId service like service in my project. The project is an SDK where the developer who integrates it has the provision to override this service. In this case, I should be able to read the name of the new service specified by the developer with a particular action in their AndroidManifest.xml file.
So the real question here is, how can I read the name of the service declared in the AndroidManifest.xml file with a specific action?
Use below utility method
public static void startService(Context context, String lookupAction) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(lookupAction);
serviceIntent.setPackage("package.of.your.application");
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(serviceIntent, 0);
if (resInfo != null && !resInfo.isEmpty()) {
ServiceInfo service = resInfo.get(0).serviceInfo;
ComponentName cmpService = new ComponentName(service.applicationInfo.packageName, service.name);
Intent serviceToStart = new Intent(lookupAction);
serviceToStart.setComponent(cmpService);
context.startService(serviceToStart);
} else {
// Handle error
}
}
I will add documentation soon
Get Exception :
Caused by: android.database.sqlite.SQLiteException: no such table:
TABLE_USER_RITUALS (code 1): , while compiling: Select * from
TABLE_USER_RITUALS where USER_NAME = 'vxfbb' and RITUAL_NAME =
'Morning Routine'
But the database is exists as the code works fine if the app is opened in background, it got crashed when app is removed from the background
Broadcast Receiver Class:
public class AlarmReceiver extends BroadcastReceiver
{
String h_id, habit, habit_desc, habit_time;
//public static Ringtone ringtone;
#Override
public void onReceive(Context mContext, Intent arg1)
{
String selectedRitual = arg1.getExtras().getString(AppsConstant.SELECTED_RITUAL);
String userName = arg1.getExtras().getString(AppsConstant.user_name);
// Enable {#code SampleBootReceiver} to automatically restart the alarm when the
// device is rebooted.
ComponentName receiver = new ComponentName(mContext, SampleBootReceiver.class);
PackageManager pm = mContext.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
//get data from database
GetData getData = new GetData();
UserRitualModel userReminderSetting = getData.getRitualsDetails(userName, selectedRitual);
int isfullScreen = userReminderSetting.getNotificationStyle();
int ringInSilent = userReminderSetting.getRingInSilent();
if(ringInSilent ==TableAttributes.ON)
{
final AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume,AudioManager.FLAG_ALLOW_RINGER_MODES);
}
Intent i;
if(isfullScreen==TableAttributes.ON)
{
i = new Intent(mContext, ReminderFullScreen.class);
}
else
{
i = new Intent(mContext, Reminder.class);
}
// i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(AppsConstant.SELECTED_RITUAL, selectedRitual);
i.putExtra(AppsConstant.user_name, userName);
mContext.getApplicationContext().startActivity(i);
}
}
I have got the answer :
You will need the context,for calling the database which you have as part of the BroadcastReceiver onReceive method signature and that's it.
for refrence :
how can i access database from broadcast receiver in android?
Im new to services, so i have a little problem here. Im trying to get foreground app name and i want to print it out with toast, bu i always get an runtimeException and i dont know why... Here+s the code:
public class ForegroundAppService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Foreground service started", Toast.LENGTH_SHORT).show();
try {
ActivityManager activityManager = (ActivityManager)
ForegroundAppService.this.getSystemService(ACTIVITY_SERVICE);
RunningTaskInfo runningTaskInfo = activityManager.getRunningTasks(1).get(0);
String foregroundTaskPackageName =
runningTaskInfo.topActivity.getPackageName().toString();
PackageManager pm = ForegroundAppService.this.getPackageManager();
PackageInfo foregroundAppPackageInfo;
foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
String foregroundTaskAppName =
foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
Toast.makeText(this, foregroundTaskAppName, Toast.LENGTH_SHORT).show();
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return Service.START_STICKY;
}
}
Thanks in advance!
An Android Service lives on its own, without an Activity. You can bind an Activity to a service or start a Service from an Activity. In any case, as the Service has no Foreground Activity, the ActivityManager is not available and you get an exception.
What you can do is, have a look into the parameter Intent that you got in the onStartCommand. You find there some limited information about the sender of the intent. If you like to know more, you can add extra information to the Intent by the calling Activity with Intent.putExtra().
If you want to closely bind an Activity with your Service use the bindService method for Activity. You can than send messages between them.
Is there a way to check which BroadcastReceivers are declared in the manifest, in runtime?
With PackageManager, you can queryBroadcastReceivers() to find who will all respond to a specific Intent, and with getInstalledPackages(), you can find out the receivers installed per package.
The code would be similar like this, from within an Activity:
// Query all packages that have the BroadcastReceivers...
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager pm = getPackageManager();
final List<ResolveInfo> listPkgs = pm.queryBroadcast(mainIntent, 0);
if (listPkgs != null && listPkgs.size() > 0){
for(ResolveInfo resInfo : listPkgs){
// Now resInfo will contain the list of packages that has receivers...
}
}
Thanks, but was not my intention... I wanted to get know if a specific receiver is declared in the running application in runtime, and achieved it like this:
private <Receiver extends CyborgReceiver<?>> boolean checkIfBroadcastReceiverIsRegisteredInManifest(Class<Receiver> receiverType) {
PackageManager pm = application.getPackageManager();
try {
ActivityInfo info = pm.getReceiverInfo(new ComponentName(application, receiverType), PackageManager.GET_RECEIVERS);
return info.enabled;
} catch (NameNotFoundException e) {
return false;
}
}
Pass in the application object as the first argument, you can do this with (Application)context.GetApplicationContext() if you have to, then pass in your class which implements the broadcast receiver class as the second argument e.g. broadcastReceiver.class
public static boolean validateReceiverInManifest(Application application, Class receiverClass) throws PackageManager.NameNotFoundException {
PackageManager pm = application.getPackageManager();
String packageName = application.getPackageName();
PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_RECEIVERS);
ActivityInfo[] receivers = packageInfo.receivers;
String receiverClassName = receiverClass.getName();
for (ActivityInfo activityInfo : receivers) {
if (activityInfo.name.equals(receiverClassName)) {
return true;
}
}
return false;
}
i'm using this snippet to check if an app/activity is installed:
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
public static boolean isScanAvailable(Context context) {
return isIntentAvailable(context, "com.google.zxing.client.android.SCAN");
}
In the above example it checks if the Barcode Scanner App is installed, which works just fine.
However, if i try to check for the Adobe Flashplayer using com.adobe.flashplayer it doesn't work and always returns false.
Is there a better / more reliable method to check for Flash?
Uhm yeah. My code posted above does Intent checking which isn't working for the flashplayer (no public intents i guess).
The more obvious way would be to just use getPackageInfo() which works just fine:
public static boolean isFlashAvailable(Context context) {
String mVersion;
try {
mVersion = context.getPackageManager().getPackageInfo(
"com.adobe.flashplayer", 0).versionName;
Log.d("Flash", "Installed: " + mVersion);
return true;
} catch (NameNotFoundException e) {
Log.d("Flash", "Not installed");
return false;
}
}
(As an added bonus we get the exact version number too)