On Android 5.0 lollipop maybe due to depricated getRunningTask() method - android

Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.
public class StartupServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
if (AppLockerPreference.getInstance(context).isAutoStart()){
if (AppLockerPreference.getInstance(context).isServiceEnabled()){
context.startService(new Intent(context, DetectorService.class));
}else{
AppLockerPreference.getInstance(context).saveServiceEnabled(false);
}
}
return;
}else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, DetectorService.class));
}
}
}
DetectorService
public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";
#Override
public IBinder onBind(Intent intent) {
return null;
}
private static final Class<?>[] mStartForegroundSignature = new Class[] {
int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
boolean.class};
private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
try {
mStartForeground.invoke(this, mStartForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
//debug: log.w("Detector", "Unable to invoke startForeground", e);
} catch (IllegalAccessException e) {
// Should not happen.
//debug: log.w("Detector", "Unable to invoke startForeground", e);
}
return;
}
// Fall back on the old API.
stopForeground(true);
mNM.notify(id, notification);
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat(int id) {
// If we have the new stopForeground API, then use it.
if (mStopForeground != null) {
mStopForegroundArgs[0] = Boolean.TRUE;
try {
mStopForeground.invoke(this, mStopForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
//debug: log.w("Detector", "Unable to invoke stopForeground", e);
} catch (IllegalAccessException e) {
// Should not happen.
//debug: log.w("Detector", "Unable to invoke stopForeground", e);
}
return;
}
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
mNM.cancel(id);
stopForeground(false);
}
#Override
public void onCreate() {
//debug: log.i("Detector","Service.Oncreate");
initConstant();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
try {
mStartForeground = getClass().getMethod("startForeground",
mStartForegroundSignature);
mStopForeground = getClass().getMethod("stopForeground",
mStopForegroundSignature);
} catch (NoSuchMethodException e) {
// Running on an older platform.
mStartForeground = mStopForeground = null;
}
}
#Override
public void onDestroy() {
//debug: log.i("Detector","Service.Ondestroy");
mThread.interrupt();
// Make sure our notification is gone.
stopForegroundCompat(R.string.service_running);
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
#Override
public void onStart(Intent intent, int startId) {
//debug: log.i("Detector","Service.Onstart");
handleCommand(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//debug: log.i("Detector","Service.OnStartCommand");
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return Service.START_STICKY;
}
private void handleCommand(Intent intent){
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.service_running);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.statusbar_icon, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AppLockerActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, text,
text, contentIntent);
startForegroundCompat(R.string.service_running, notification);
startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}
private void startMonitorThread(final ActivityManager am){
if (mThread!=null)
mThread.interrupt();
mThread = new MonitorlogThread(new ActivityStartingHandler(this));
mThread.start();
}
private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;
private void initConstant() {
//debug: log.i("Detector","Service.OninitConstant");
if (constantInited) return;
String pattern = getResources().getString(R.string.activity_name_pattern);
//debug: log.d("Detector", "pattern: " + pattern);
ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
logCatCommand = getResources().getString(R.string.logcat_command);
ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}
MonitorlogThread
private class MonitorlogThread extends Thread{
ActivityStartingListener mListener;
public MonitorlogThread(ActivityStartingListener listener){
//debug: log.i("Detector","Monitor//debug: logThread");
mListener = listener;
}
BufferedReader br;
private Context context;
#Override
public void run() {
//debug: log.i("Detector","RUN!");
while(!this.isInterrupted() ){
try {
Thread.sleep(100);
////debug: log.i("Detector","try!");
//This is the code I use in my service to identify the current foreground application, its really easy:
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground task.
//Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
Log.d("Android", "App------>7----"+am);
//RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
Log.d("Android", "App------>8----"+foregroundTaskInfo);
//Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();
//Thats it, then you can easily access details of the foreground app/activity:
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
PackageManager pm = getBaseContext().getPackageManager();
PackageInfo foregroundAppPackageInfo = null;
String foregroundTaskAppName = null;
String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
try {
foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
//debug: log.i("Detector",foregroundTaskAppName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mListener!=null){
//mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
}
} catch (InterruptedException e) {
// good practice
Thread.currentThread().interrupt();
return;
}
}
}
}

Use this code for above 5.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
long milliSecs = 60 * 1000;
Date date = new Date();
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
if (queryUsageStats.size() > 0) {
Log.i(TAG, "UsageStats size: " + queryUsageStats.size());
}
long recentTime = 0;
String recentPkg = "";
for (int i = 0; i < queryUsageStats.size(); i++) {
UsageStats stats = queryUsageStats.get(i);
if (i == 0 && !getPackageName().equals(stats.getPackageName())) {
Log.i(TAG, "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
}
if (stats.getLastTimeStamp() > recentTime) {
String recentTime = stats.getLastTimeStamp();
String recentPkg = stats.getPackageName();
}
};
} catch (Exception e) {
e.printStackTrace();
}
}

Can you try this.
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
ActivityManager.RunningAppProcessInfo runningAppProcessInfo = (ActivityManager.RunningAppProcessInfo) am.getRunningAppProcesses();
String foregroundTaskPackageName = runningAppProcessInfo.pkgList.getClass().getPackage().getName();
PackageManager pm = getBaseContext().getPackageManager();
PackageInfo foregroundAppPackageInfo = null;
String foregroundTaskAppName = null;
String foregroundTaskActivityName = runningAppProcessInfo.pkgList.getClass().getName();
try {
foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
//debug: log.i("Detector",foregroundTaskAppName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else {
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
PackageManager pm = getBaseContext().getPackageManager();
PackageInfo foregroundAppPackageInfo = null;
String foregroundTaskAppName = null;
String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
try {
foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
//debug: log.i("Detector",foregroundTaskAppName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}

Use RunningAppProcessInfo instead of getRunningTasks for SDK versions greater than KitKat.
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
...
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
...
}

Related

Camera receiver can't detect image when taken for second time by Camera in Nougat

i have created an Application for Nougat device where my application is detecting all the images taking by camera and i am sending this images in the server. My application is successfully sending the first photo taken by the camera but the receiver neither detecting the second image i am taking nor sending it to the server. I have a ConfigurationBuilder class which will trigger each and every 30 minutes to detect the new pictures by the camera and a cameraReceiver and a service class where i have registered the receiver.
ConfigurationBuilder.java
public class ConfigurationBuilder extends JobService {
JobParameters mRunningParams;
static final int PROJECTION_ID = 0;
static final int PROJECTION_DATA = 1;
static final String DCIM_DIR = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).getPath();
static final String[] PROJECTION = new String[] {
MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA
};
static final List<String> EXTERNAL_PATH_SEGMENTS
= MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPathSegments();
String TAG = "JobService";
private Context mContext;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public boolean onStartJob(JobParameters jobParameters) {
mContext = getApplicationContext();
getSettingResponse(true);
jobFinished(jobParameters, false);
Log.d(TAG, "onStartJob: ");
return true;
}
private void getSettingResponse(boolean fromJobScheduler) {
try {
if (fromJobScheduler)
new DataClear();
OkHttpClient client = new SSLManager().getClientKeyNonDeprecated(mContext);
// code request code here
HttpUrl.Builder urlBuilder =
HttpUrl.parse(mContext.getSharedPreferences(NetworkAPI.PREFNAME,Context.MODE_PRIVATE ).getString("configuration_url", "")).newBuilder();
//urlBuilder.addQueryParameter("device", CommonMethods.getBluetoothName());
urlBuilder.addQueryParameter("device", "FranksS7");
urlBuilder.addQueryParameter("membership", "Phone Network");
urlBuilder.addQueryParameter("membershipType", "Domain");
Request request = new Request.Builder().addHeader("Accept", "application/json")
.url(urlBuilder.build()).get()
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
getConfigure(null);
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
Log.d(TAG, "onResponse:Unexpected code" + response.body().string());
} else {
getConfigure(response.body().string());
}
}
});
} catch (Exception e) {
Log.d(TAG, "getSettingResponse: " + e.getMessage());
}
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
private void getConfigure(String response) {
try {
if (response != null) {
JSONArray policies = new JSONObject(response).getJSONArray("Policies");
for (int i = 0; i < policies.length(); i++) {
JSONObject obj = policies.getJSONObject(i);
Iterator iterator = obj.keys();
String key = (String) iterator.next();
JSONObject issue = obj.getJSONObject(key);
String value = issue.optString("Value");
RecorderPolicies policiesField = new Select()
.from(RecorderPolicies.class)
.where("Policy = ?", key).executeSingle();
if (policiesField != null) {
policiesField.Value = value;
long res = policiesField.save();
// new Update(RecorderPolicies.class).set("Value = ?",value).where("Policy = ?", key).execute();
} else {
RecorderPolicies recorderPolicies = new RecorderPolicies();
recorderPolicies.Policy = key;
recorderPolicies.Value = value;
long res = recorderPolicies.save();
}
}
}
if (isMyServiceRunning(ApplicationService.class)) {
// stopService(new Intent(mContext, ApplicationService.class));
Log.d(TAG, "Service Terminated");
}
if (new RecorderPolicies().getActivateCode("CanRecordDetailedData"))
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
mContext.startService(new Intent(mContext, ApplicationService.class));
Log.d(TAG, "Service Restarted");
}
}, 10000);
else
Log.d(TAG, "----------------------problem starting service---------------------");
} catch (Exception e) {
Log.d(TAG, "getConfigure: " + e.getMessage());
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void startConfigurationScheduler(int JobID, Context activityContext) {
mContext = activityContext;
ComponentName jobService =
new ComponentName(activityContext, ConfigurationBuilder.class.getName());
JobInfo jobInfo =
new JobInfo.Builder(JobID, jobService)
.setPersisted(true).setRequiresDeviceIdle(true)
//updated code for nougat...............................................................on 12/11/2017
//.setPeriodic(32*60000, (long) (1.6*60000)).build();
.setPeriodic(32 * 60000).build();
JobScheduler jobScheduler = (JobScheduler) activityContext.getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfo);
getSettingResponse(false);
}
public void stopConfigurationScheduler(int JobID, Context activityContext) {
JobScheduler jobScheduler = (JobScheduler) activityContext.getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.cancel(JobID);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Process.killProcess(service.pid); // kill service
return true;
}
}
return false;
}
}
CameraReceiver .java
public class CameraReceiver extends BroadcastReceiver {
private String pathSplit;
private String type;
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext=context;
Cursor cursor = context.getContentResolver().query(intent.getData(),
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
String MediaType = intent.getAction().equals("android.hardware.action.NEW_VIDEO") ? "VIDEO" : "IMAGE";
FilesObservers.postDataCreateEvent("CREATE", image_path, true,MediaType);
cursor.close();
}
}
public IntentFilter getVideoFilters() {
IntentFilter lsIntentFilter = new IntentFilter();
try {
lsIntentFilter.addDataType("video/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
lsIntentFilter.addAction("android.hardware.action.NEW_VIDEO");
lsIntentFilter.addCategory("android.intent.category.DEFAULT");
return lsIntentFilter;
}
public IntentFilter getCameraFilters() {
IntentFilter lsIntentFilter = new IntentFilter();
try {
lsIntentFilter.addDataType("image/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
} //lsIntentFilter.addAction("JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri)");
lsIntentFilter.addAction("android.provider.MediaStore.ACTION_IMAGE_CAPTURE)");
lsIntentFilter.addCategory("android.intent.category.DEFAULT");
return lsIntentFilter;
}
}
In Nougat ACTION_NEW_VIDEO and ACTION_NEW_PICTURE broadcasts were removed.
Instead this they recommend to use JobInfo.Builder.JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri)
It is funny because In Android O this broadcast has been brought back - for registered receivers only.

Understanding Android Memory Consumption

I am new to Android development and I would like to understand why my application is using this much memory when it starts. Right now, it starts off with 18MB of memory (using the memory monitor in Android Studio). I have added Firebase Analytics and Admob to it. I am worried that these are culprits of using this large amount of memory.
By doing some digging in, I found out that SharedPreferenceImpl and its children objects (FastXmlSerializer and ByteBuffer) were taking up 50% of the memory! I am pretty shocked. Next, I try to see which thread is generating these objects. I found out that the thread name is "thread-1-pool-1".
Here is the stacktrace responsible for creating this large amount of memory:
at java.nio.ByteBuffer.allocate(ByteBuffer.java:56)
at com.android.internal.util.FastXmlSerializer.<init>(FastXmlSerializer.java:62)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:188)
at android.app.SharedPreferencesImpl.writeToFile(SharedPreferencesImpl.java:600)
at android.app.SharedPreferencesImpl.-wrap2(SharedPreferencesImpl.java)
at android.app.SharedPreferencesImpl$2.run(SharedPreferencesImpl.java:515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
I have a LoopThread that calls a method in a service. I am wondering if this could cause the large consumption of memory. My service class and loop thread contains no references to SharedPreferences though. So, I am very confuse why this happens. Any pointers would be appreciated.
The code may not be very clean and it is long. But here it is. The idea of this app is to bring up a screen saver when the power button is pressed.
This is the service class.
//SaverService.java
#Override
public void onCreate() {
Log.d("SaverService","Created saver service...");
super.onCreate();
loopThread = new LoopThread();
loopThread.createHandler(this);
loopThread.start();
startSaverMethod();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, StartSaver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.pokeball)
.setContentTitle("Go-Saver's running")
.setContentText("Tap here to cancel")
.setContentIntent(pendingIntent);
Notification notification = mBuilder.build();
startForeground(1001, notification);
return START_STICKY;
}
//SharedPreference should be a singleton
private void startSaverMethod() {
//sharedPreferences = getSharedPreferences("GoSaverPrefs", Context.MODE_PRIVATE);
try {
//SharedPreferences.Editor editor = sharedPreferences.edit();
screenBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
previousScreenBrightness = screenBrightness;
//editor.putInt("screenBrightness", screenBrightness);
//editor.commit();
screenBrightnessMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
previousScreenBrightnessMode = screenBrightnessMode;
//editor.putInt("screenBrightnessMode",screenBrightnessMode);
//editor.commit();
screenOffTimeout = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT);
previousScreenOffTimeout = screenOffTimeout;
//editor.putInt("screenOffTimeout",screenOffTimeout);
//editor.commit();
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
//Registerting receiver
screenOffReceiver = new ScreenOffReceiver();
screenOffReceiver.setSaverService(this);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(screenOffReceiver, filter);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 3600000);
pressedMillisec = getPressedMillisec();
}
#Override
public void onDestroy() {
Log.d("SaverService","Destroying saver service...");
disableSaverSettings();
//screenOffTimeout = sharedPreferences.getInt("screenOffTimeout", 30000);
screenOffTimeout = previousScreenOffTimeout;
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, screenOffTimeout);
unregisterReceiver(screenOffReceiver);
removeScreenSaver();
//sharedPreferences = null;
windowManager = null;
screenOffReceiver = null;
Message killMessage = loopThread.handler.obtainMessage(LoopThread.KILL);
loopThread.handler.sendMessage(killMessage);
loopThread.handler.getLooper().quit();
super.onDestroy();
System.gc();
}
public boolean isScreenSaver() {
if(screenSaver != null) {
return screenSaver.isShown();
} else {
return false;
}
}
private boolean isSaverBrightness() {
try {
int brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
int brightnessMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
return brightness == 1 && brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
} catch (Exception e) {
Log.e("SaverService", "Cannot get brightness");
return false;
}
}
public void startScreenSaverAsync() {
Message onMessage = loopThread.handler.obtainMessage(LoopThread.ON);
loopThread.handler.sendMessage(onMessage);
}
public void startScreenSaver() {
Log.d("SaverService","######################################");
boolean isRightState = !isScreenSaver() && !isSaverBrightness();
if (!isRightState) {
Log.e("SaverService","Invalid state. Stopping service");
stopSelf();
}
long currentMillisec = getPressedMillisec();
if (currentMillisec - pressedMillisec < 2000) {
Log.d("SaverService","Pressed too fast. Ignoring the second press.");
return;
}
//Creating screenSaver
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
screenSaver = li.inflate(R.layout.screen_saver, null);
long startTime = System.currentTimeMillis();
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE,
PixelFormat.TRANSLUCENT);
long totalTime = System.currentTimeMillis() - startTime;
Log.d("SaverService","params Time: " + totalTime);
startTime = System.currentTimeMillis();
enableSaverSettings();
totalTime = System.currentTimeMillis() - startTime;
Log.d("SaverService","enableSaverSettings Time: " + totalTime);
startTime = System.currentTimeMillis();
removeScreenSaver();
totalTime = System.currentTimeMillis() - startTime;
Log.d("SaverService","removeScreenSaver Time: " + totalTime);
Log.d("SaverService", "Adding Screen Saver");
startTime = System.currentTimeMillis();
windowManager.addView(screenSaver, params);
totalTime = System.currentTimeMillis() - startTime;
Log.d("SaverService","addView Time: " + totalTime);
Log.d("SaverService", "Turning On Screen");
startTime = System.currentTimeMillis();
turnOnScreen(this);
totalTime = System.currentTimeMillis() -startTime;
Log.d("SaverService","turnOnScreen Time: " + totalTime);
pressedMillisec = getPressedMillisec();
Log.d("SaverService", "Current time - " + pressedMillisec);
Log.d("SaverService","######################################");
}
public void stopScreenSaverAsync() {
Message offMessage = loopThread.handler.obtainMessage(LoopThread.OFF);
loopThread.handler.sendMessage(offMessage);
}
public void stopScreenSaver() {
Log.d("SaverService","######################################");
long currentMillisec = getPressedMillisec();
if (currentMillisec - pressedMillisec < 2000) {
Log.d("SaverService","Pressed too fast. Ignoring the second press.");
return;
}
disableSaverSettings();
removeScreenSaver();
turnOnScreen(this);
pressedMillisec = getPressedMillisec();
Log.d("SaverService", "Current time - " + pressedMillisec);
Log.d("SaverService","######################################");
}
private long getPressedMillisec() {
return Calendar.getInstance().getTimeInMillis();
}
private void removeScreenSaver() {
try {
windowManager.removeViewImmediate(screenSaver);
screenSaver = null;
} catch (Exception e) {
Log.w("SaverService", "Could not remove screen saver...");
}
}
private void enableSaverSettings() {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 1);
}
private void disableSaverSettings() {
screenBrightness = previousScreenBrightness;
screenBrightnessMode = previousScreenBrightnessMode;
//screenBrightness = sharedPreferences.getInt("screenBrightness", 50);
//screenBrightnessMode = sharedPreferences.getInt("screenBrightnessMode", Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, screenBrightnessMode);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, screenBrightness);
}
private void turnOnScreen(Context context) {
//Wait for screen is off
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
while (isScreenOn) {
try {
Thread.sleep(2);
isScreenOn = pm.isScreenOn();
} catch (Exception e) {
Log.i("Issue", "Could not sleep...");
}
}
Intent intentNew = new Intent(context.getApplicationContext(), Transparent.class);
intentNew.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intentNew);
}
This is the class that listens for a Power button press:
public class ScreenOffReceiver extends BroadcastReceiver {
private SaverService saverService = null;
private static boolean anyThreadRunning = false;
void setSaverService(SaverService saverService){
this.saverService = saverService;
}
#Override
public void onReceive(Context context, Intent intent) {
runMethod2(context, intent);
}
private void runMethod2(Context context, Intent intent) {
String action = intent.getAction();
Log.d("SaverService", action);
if(anyThreadRunning) {
Log.d("SaverService","Another thread is using ScreenOffReceiver. Skipping... ");
return;
}
if(action.equals(Intent.ACTION_SCREEN_OFF) && !saverService.isScreenSaver()){
anyThreadRunning = true;
Log.d("SaverService","Turning on screen saver.");
saverService.startScreenSaverAsync();
}
else if(action.equals(Intent.ACTION_SCREEN_OFF) && saverService.isScreenSaver()){
anyThreadRunning = true;
Log.d("SaverService","Turning off screen saver." );
saverService.stopScreenSaverAsync();
}
anyThreadRunning = false;
}
}
This the loop thread class:
public class LoopThread extends Thread {
public Handler handler = null;
public static final int ON = ScreenOffHandler.ON;
public static final int OFF = ScreenOffHandler.OFF;
public static final int KILL = ScreenOffHandler.KILL;
private SaverService saverService;
public void run(){
Looper.prepare();
handler = new ScreenOffHandler(saverService);
Looper.loop();
}
public void createHandler(SaverService saverService){
this.saverService = saverService;
}
private static class ScreenOffHandler extends Handler {
private SaverService saverService;
public static final int ON = 1;
public static final int OFF = 0;
public static final int KILL = -100;
public ScreenOffHandler(SaverService saverService) {
this.saverService = saverService;
}
public void handleMessage(Message msg) {
// ...Run in background
int what = msg.what;
switch (what){
case ON:
saverService.startScreenSaver();
break;
case OFF:
saverService.stopScreenSaver();
break;
case KILL:
saverService = null;
break;
}
}
}
}

Asynctask within fragments doesn't work when service is running

I have a drawerlayout and he call many fragments and they have asynctask within, also i have created a notification service, it's work very fine in api level < 11 but when the level is > 10 the asynctask of fragment only work when the service is not running, why?
My code of service is here
public class NotificationService extends Service {
MyTask myTask;
private final String url_notificaciones = "http://www.domain.com/domain/getNotificaciones.php";
private static final String TAG_TIPO_NOTIFICACION = "tipo_notificacion";
private static final String TAG_TITULO_NOTIFICACION= "titulo_notificacion";
private static final String TAG_DESCRIPCION_NOTIFICACION= "descripcion_notificacion";
private String jsonResult;
SessionManagement session;
boolean InitializeNotificationManager = true;
private HashMap<String, String> user;
private String id_datos_usuarios_session;
private JsonReadTask task;
private Handler handler = new Handler();
private TaskCanceler taskCanceler;
#Override
public void onCreate() {
super.onCreate();
try {
session = new SessionManagement(getApplication());
user = session.getUserDetails();
id_datos_usuarios_session = user.get(SessionManagement.KEY_ID_DATOS_USUARIOS).toString();
}catch (Exception e){
InitializeNotificationManager = false;
}
myTask = new MyTask();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
myTask.execute();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
myTask.cancel(true);
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
private class MyTask extends AsyncTask<String, String, String> {
private String date;
private boolean cent;
#Override
protected void onPreExecute() {
super.onPreExecute();
cent = true;
}
#Override
protected String doInBackground(String... params) {
while (cent) {
try {
if(isNetworkStatusAvialable (getApplication())) {
accessWebService();
}
// Stop 20s
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
//Toast.makeText(getApplicationContext(), "Hora actual: ", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCancelled() {
super.onCancelled();
cent = false;
}
}
public void accessWebService(){
task = new JsonReadTask();
taskCanceler = new TaskCanceler(task);
handler.postDelayed(taskCanceler, 15*1000);
task.execute(new String[]{url_notificaciones});
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("get_app_id_datos_usuarios", id_datos_usuarios_session));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("notification");
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
String tipo_notificacion = jsonChildNode.getString(TAG_TIPO_NOTIFICACION);
String titulo_notificacion = jsonChildNode.getString(TAG_TITULO_NOTIFICACION);
String descripcion_notificacion = jsonChildNode.getString(TAG_DESCRIPCION_NOTIFICACION);
if(tipo_notificacion.equals("1")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("MenuNotificationFragment", "MyFriendsRequired");
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// Creamos la notificación. Las acciones son de "mentirijilla"
Notification noti = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle(titulo_notificacion)
.setContentText(descripcion_notificacion).setSmallIcon(R.mipmap.icon_app)
.setContentIntent(pIntent)
.setLights(0xffff00, 4000, 100)
/*.addAction(R.drawable.ic_arrow, "Llamada", pIntent)
.addAction(R.drawable.ic_arrow, "Más", pIntent)
.addAction(R.drawable.ic_arrow, "Mucho Más", pIntent)*/.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Ocultamos la notificación si ha sido ya seleccionada
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
//Sound notification
try {
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
ringtone.play();
} catch (Exception e) {
}
//Vibrate notification
try {
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 2000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, -1);
} catch (Exception e) {
}
}else if(tipo_notificacion.equals("2")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("MenuNotificationFragment", "MyBussinesRequired");
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// Creamos la notificación. Las acciones son de "mentirijilla"
Notification noti = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle(titulo_notificacion)
.setContentText(descripcion_notificacion).setSmallIcon(R.mipmap.icon_app)
.setContentIntent(pIntent)
.setLights(0xffff00, 4000, 100)
/*.addAction(R.drawable.ic_arrow, "Llamada", pIntent)
.addAction(R.drawable.ic_arrow, "Más", pIntent)
.addAction(R.drawable.ic_arrow, "Mucho Más", pIntent)*/.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Ocultamos la notificación si ha sido ya seleccionada
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
//Sound notification
try {
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
ringtone.play();
} catch (Exception e) {
}
//Vibrate notification
try {
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 2000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, -1);
} catch (Exception e) {
}
}
} catch (JSONException e) {
}
}
}// end async task
//If the internet connection is ok
public static boolean isNetworkStatusAvialable (Context context) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if (netInfos != null)
if (netInfos.isConnected())
return true;
}
}catch (Exception e){
return false;
}
return false;
}
public class TaskCanceler implements Runnable{
private AsyncTask taskR;
public TaskCanceler(AsyncTask task) {
this.taskR = task;
}
#Override
public void run() {
if (task.getStatus() == AsyncTask.Status.RUNNING ) {
task.cancel(true);
}
}
}
}
Starting on Android 11 AsyncTask objects shares a single thread. So your service is blocking that thread, and the fragments can't run. The easiest solution is pretty obvious here, don't use AsyncTask for the service. It doesn't even make sense to use it there because AsyncTask is meant to deliver results back on the UI thread, something your service doesn't need to do. Here is a possible solution:
public class MyService extends Service implements Runnable {
private HandlerThread = ht;
private Handler handler;
#Override
public void onCreate() {
super.onCreate();
try {
session = new SessionManagement(getApplication());
user = session.getUserDetails();
id_datos_usuarios_session = user.get(SessionManagement.KEY_ID_DATOS_USUARIOS).toString();
}catch (Exception e){
InitializeNotificationManager = false;
}
ht = new HandlerThread("MyService");
ht.start();
handler = new Handler(ht.getLooper());
handler.post(this);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(this);
ht.quit();
ht = null;
handler = null;
}
#Override
public void run(){
if(isNetworkStatusAvialable (getApplication())) {
accessWebService();
}
handler.postDelayed(20000, this);
}
}

Android background service and wake lock

I have android background service to connect with my RabbitMQ server. My background service listen incoming rabbitmq message. Everything is working well but the problem is appear while screen goes off. My android client disconnect when phone screen goes off. What should I do to always connected with my android rabbitmq client and rabbitmq server ?
My code are below :
public class RabbitmqPushService extends Service{
private Thread subscribeThread;
private ConnectionFactory factory;
private Connection connectionSubscribe;
private Channel channelSubscribe;
private NotificationManager mNotificationManager;
public static int NOTIFICATION_ID = 0;
private static final String HOST_NAME = Constant.HOST_NAME; //Rabbitmq Host Name
private static final int PORT_ADDRESS = 5672;
private static final String EXCHANGE_NAME = "fanout_msg";
private static String QUEUE_NAME = Constant.phone_number+"_queue"; //Queue Name
private static String[] ROUTE_KEY = {"all", Constant.phone_number};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
NOTIFICATION_ID = 0;
setupConnectionFactory();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(connectionSubscribe != null)
{
if(!connectionSubscribe.isOpen())
{
connect();
}
}
else
{
connect();
}
return Service.START_STICKY;
}
#Override
public void onDestroy() {
if(connectionSubscribe != null)
{
disconnectSubscribe();
}
NOTIFICATION_ID = 0;
}
private void setupConnectionFactory() {
factory = new ConnectionFactory();
factory.setHost(HOST_NAME);
factory.setPort(PORT_ADDRESS);
factory.setUsername(Constant.USERNAME);
factory.setPassword(Constant.PASSWORD);
factory.setRequestedHeartbeat(60);
}
private void connect()
{
final Handler incomingMessageHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String message = msg.getData().getString("msg");
try {
JSONObject jsonObject = new JSONObject(message);
BeepHelper.msgBeep(getApplicationContext());
sendNotification("From : " + jsonObject.getString("from"), jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
};
subscribe(incomingMessageHandler);
publishToAMQP();
}
private void disconnectSubscribe()
{
subscribeThread.interrupt();
try {
channelSubscribe.close();
connectionSubscribe.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (TimeoutException e) {
e.printStackTrace();
}
}
void subscribe(final Handler handler)
{
subscribeThread = new Thread()
{
#Override
public void run() {
while(true) {
try {
connectionSubscribe = factory.newConnection();
channelSubscribe = connectionSubscribe.createChannel();
channelSubscribe.exchangeDeclare(EXCHANGE_NAME, "fanout");
channelSubscribe.queueDeclare(QUEUE_NAME, true, false, false, null);
for(int i = 0; i<ROUTE_KEY.length; i++)
{
channelSubscribe.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTE_KEY[i]);
}
QueueingConsumer consumer = new QueueingConsumer(channelSubscribe);
channelSubscribe.basicConsume(QUEUE_NAME, false, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("msg", message);
msg.setData(bundle);
handler.sendMessage(msg);
channelSubscribe.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
} catch (InterruptedException e) {
break;
} catch (Exception e1) {
try {
Thread.sleep(4000); //sleep and then try again
} catch (InterruptedException e) {
break;
}
}
}
}
};
subscribeThread.start();
}
#Override
public void publishMessage(String message) {
try {
queue.putLast(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void sendNotification(String title, String msg) {
mNotificationManager = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID++, mBuilder.build());
}
}
You need a Wake Lock to keep the phone running when screen is off. Wake locks allow your application to control the power state of the host device.
Add the WAKE_LOCK permission to your application's manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Then add the following in onCreate():
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
wakelock.acquire();
If your app includes a broadcast receiver that uses a service to do some work, you can manage your wake lock through a WakefulBroadcastReceiver. This is the preferred approach. If your app doesn't follow that pattern, you set a wake lock directly.

App widget fetch data from server

I have developed a widget which will fetch the data from a server and do some modifications and display in widget.
I have a ALARM manager which starts a service in every 10 sec and service fetches data with async task and display.
It consumes a lot of CPU usage.
Kindly help if I can change the code design and make the widget more effective.
I use Jsoup to connect and fetch data.
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.d("Widget : " , "Inside onUpdate widget");
// To prevent any ANR timeouts, we perform the update in a service
final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Calendar TIME = Calendar.getInstance();
TIME.set(Calendar.MINUTE, 0);
TIME.set(Calendar.SECOND, 0);
TIME.set(Calendar.MILLISECOND, 0);
final Intent i = new Intent(context, UpdateService.class);
if (service == null)
{
service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
m.setRepeating(AlarmManager.RTC, TIME.getTime().getTime(), 100 * 60, service);
}
public static class UpdateService extends Service {
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// System.out.println("Inside config change ");
enableControls(this);
}
#Override
public void onStart(Intent intent, int startId) {
// Build the widget update for today
mContext = this;
Log.d("Widget : " , "Service started");
enableControls(this);
}
public static void enableControls(Context context){
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_status);
Intent active = new Intent(context, MyWidgetProvider.class);
active.setAction(ACTION_WIDGET_REFRESH);
active.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
pushWidgetUpdate(context, remoteViews);
fetchStatus();
}
public static void fetchStatus(){
new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... urls) {
try {
if(getWiFiStatus(mContext) == true ){
boolean getRedirectedURL = false;
String url,finalURL;
finalURL = "http://mobile.server.status";
Document doc = Jsoup.connect(finalURL).get();
while(getRedirectedURL == false){
Log.d(LOG_TAG,"inside while loop ---- : " + getRedirectedURL);
doc = Jsoup.connect(finalURL).get();
Log.d(LOG_TAG,"Complete doc: " + doc);
// System.out.println("Found the doc : " +doc.toString().contains("status"));
// Log.d(LOG_TAG,"Whole data third :"+doc);
// System.out.println("Printing redirected URL " + (docHead.select("meta")));
if(doc.toString().contains("status")){
getRedirectedURL = true;
break;
}
else
getRedirectedURL = false;
Elements docHead = doc.select("meta");
for(Element emt :docHead) {
url =null;
//Log.d(LOG_TAG,"Value boolean :"+emt.getElementsByAttribute("http-equiv").toString().toLowerCase().contains("url"));
if(emt.getElementsByAttribute("http-equiv").toString().toLowerCase().contains("url") ){
//getRedirectedURL = true;
url = emt.getElementsByAttribute("http-equiv").toString().toLowerCase().split("url=")[1].toString();
if (emt.getElementsByAttribute("http-equiv").toString().toLowerCase().contains("http://")){
finalURL = null;
finalURL = url.split("\"")[0].toString();
}
else
finalURL = finalURL + url.split("\"")[0].toString();
//Log.d(LOG_TAG,"Final URL :"+finalURL);
}
// else
// getRedirectedURL = false;
}
}
Log.d(LOG_TAG,"Final URL :"+finalURL);
doc = Jsoup.connect(finalURL).get();
Document noFramesDoc = Jsoup.parseBodyFragment(doc.toString());
}
else{
refreshStatus(mContext);
}
} catch (UnknownHostException exception){
System.out.println("Inside unknown host : ");
}
catch (Exception e) {
Log.d(LOG_TAG,"other Exception found :"+e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(mContext != null)
}
#Override
protected void onCancelled() {
}
}.execute();
}

Categories

Resources