I am collecting GPS location data in Splash Screen and store it in session, and use it later in MainActivity. If the GPS is turn off or used for the first time it will ask for permission in my splash screen. The problem is that I am using the timer to move splash screen Activity to another activity. Due to the timer, SplashScreen is moving to next the activity without the permission. I want my Splash screen to wait till permission dialog is allowed or denied. Below is my code
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.location.LocationTrack;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class SplashActivity extends AppCompatActivity {
TextView welcomeText;
ImageView mLogo;
ImageView zbgimg;
Typeface tf1;
private Session session;
private ArrayList<String> permissionsToRequest;
private ArrayList<String> permissionsRejected = new ArrayList<>();
private ArrayList<String> permissions = new ArrayList<>();
private final static int ALL_PERMISSIONS_RESULT = 101;
LocationTrack locationTrack;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new Session(SplashActivity.this);
//GPS Tracker
permissions.add(ACCESS_FINE_LOCATION);
permissions.add(ACCESS_COARSE_LOCATION);
permissionsToRequest = findUnAskedPermissions(permissions);
//get the permissions we have asked for before but are not granted..
//we will store this in a global list to access later.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0)
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
}
locationTrack = new LocationTrack(SplashActivity.this);
if (locationTrack.canGetLocation()) {
double longitude = locationTrack.getLongitude();
double latitude = locationTrack.getLatitude();
Geocoder gcd = new Geocoder(SplashActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
String subLocality = addresses.get(0).getSubLocality();
String address = addresses.get(0).getAddressLine(0);
String state = addresses.get(0).getAdminArea();
String countryn = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
session.setLocation(latitude,longitude,locality,subLocality);
//Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
}
} else {
locationTrack.showSettingsAlert();
}
welcomeText = (TextView) findViewById(R.id.welcome);
tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
welcomeText.setTypeface(tf1);
mLogo = (ImageView) findViewById(R.id.applogo);
zbgimg = (ImageView) findViewById(R.id.zbgimg);
zbgimg.setImageResource(R.drawable.splash_screen_option_three);
animation2();
animation3();
new Handler().postDelayed(new Runnable() {
#SuppressLint("PrivateResource")
#Override
public void run() {
if (session.FbLoggedIn()) {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
} else {
Intent i = new Intent(SplashActivity.this,
LoginActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
}
}
}, 3000);
}
private void animation2() {
mLogo.setAlpha(1.0F);
Animation anim = AnimationUtils.loadAnimation(SplashActivity.this, R.anim.translate_top_to_center);
mLogo.startAnimation(anim);
}
private void animation3() {
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(welcomeText, "alpha", 0.0F, 1.0F);
alphaAnimation.setStartDelay(1700);
alphaAnimation.setDuration(500);
alphaAnimation.start();
}
///GPS Tracker
private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
ArrayList<String> result = new ArrayList<String>();
for (String perm : wanted) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (canMakeSmores()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
}
return true;
}
private boolean canMakeSmores() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ALL_PERMISSIONS_RESULT:
for (String perms : permissionsToRequest) {
if (!hasPermission(perms)) {
permissionsRejected.add(perms);
}
}
if (permissionsRejected.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
}
}
});
return;
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(SplashActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
locationTrack.stopListener();
}
If you do not understand please comment.
Try this solution.
First of all, make your onCreate() method this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new Session(SplashActivity.this);
//GPS Tracker
permissions.add(ACCESS_FINE_LOCATION);
permissions.add(ACCESS_COARSE_LOCATION);
permissionsToRequest = findUnAskedPermissions(permissions);
//get the permissions we have asked for before but are not granted..
//we will store this in a global list to access later.
welcomeText = (TextView) findViewById(R.id.welcome);
tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
welcomeText.setTypeface(tf1);
mLogo = (ImageView) findViewById(R.id.applogo);
zbgimg = (ImageView) findViewById(R.id.zbgimg);
zbgimg.setImageResource(R.drawable.splash_screen_option_three);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0)
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
}
else {
animation2();
animation3();
setUserLocation(); //After that start app
}
}
Then make separate setUserLocation() function outside of onCreate() as follow:-
public void setUserLocation() {
locationTrack = new LocationTrack(SplashActivity.this);
if (locationTrack.canGetLocation()) {
double longitude = locationTrack.getLongitude();
double latitude = locationTrack.getLatitude();
Geocoder gcd = new Geocoder(SplashActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
String subLocality = addresses.get(0).getSubLocality();
String address = addresses.get(0).getAddressLine(0);
String state = addresses.get(0).getAdminArea();
String countryn = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
session.setLocation(latitude,longitude,locality,subLocality);
//Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
}
startApp();
} else {
locationTrack.showSettingsAlert();
}
}
One more separate function startApp() outside onCreate() like below:-
public void startApp() {
new Handler().postDelayed(new Runnable() {
#SuppressLint("PrivateResource")
#Override
public void run() {
if (session.FbLoggedIn()) {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
} else {
Intent i = new Intent(SplashActivity.this,
LoginActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
}
}
}, 3000);
}
And last thing, change onRequestPermissionsResult() method like below:-
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ALL_PERMISSIONS_RESULT:
for (String perms : permissionsToRequest) {
if (!hasPermission(perms)) {
permissionsRejected.add(perms);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsRejected.size() > 0) {
if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
}
}
});
return;
}
}
else {
animation2();
animation3();
setUserLocation(); //After that start app
}
}
else {
animation2();
animation3();
setUserLocation(); //After that start app
}
break;
}
}
So, this solution follow permission first, then user-Location and then startApp.
If I understand correctly you want to access location before going jumping from splash screen. If so just remove timer open and as splash screen opens make it check for location service on/off and get location and then jump to another activity.
if (!canGetLocation()) {
showSettingsAlert();
} else {
fetch location
if (session.FbLoggedIn()) {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
} else {
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
}
}
Related
I'm creating a location based app which gets the current location of the user every 'x' minutes in the background, for that I'm planning to use PeriodicWorkRequest using WorkManager API.
But the thing is the minimum time for repeat interval is 15 minutes, so I thought I could use this Codelab (which uses Broadcast receiver in the pending intent) to get user's location updates, Which of the methods should I be using?
I'm planning to get Latitude and longitude coordinates from an API and create a Geofence with that latitude and longitude using Periodic Work Request Every 15 minutes in the Background, But the thing is I have Android Oreo and my Geofence does not seem to be triggered or I do not get any notification when my App is killed, I only get when app is in background or in the foreground even after I'm using Broadcast receiver for the pending intent in creating Geofence.
Also my periodic work does not seem to run as expected, because I Have put a test notification in the work and it gets executed only when I open the app for the first time and does not work after 15 minutes as it is expected to work, My Main Goal is to Create a periodic work request which runs every 15 minutes in the background, downloads location data from API and creates a geofence with that location, but since my work manager and geofence is not working properly I'm not able to achieve desired results. Any help would be appreciated. Here is the Code I'm using.
MainActivity:
package com.example.rohit.geofencefundo;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int LOC_PERM_REQ_CODE = 1;
//meters
private static final int GEOFENCE_RADIUS = 150;
//in milli seconds
private static final int GEOFENCE_EXPIRATION = 600000;
LocationManager locationManager;
android.location.LocationListener locationListener;
LatLng userLocation;
Data data;
private GoogleMap mMap;
private GeofencingClient geofencingClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* geofencingClient = LocationServices.getGeofencingClient(this);
showCurrentLocationOnMap();*/
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.g_map);
mapFragment.getMapAsync(this);
geofencingClient = LocationServices.getGeofencingClient(this);
//addresses = geocoder.getFromLocation(lat, lng, 1);
data = new Data.Builder()
.putString(BackgroundWork.EXTRA_TITLE, "Message from Activity!")
.putString(BackgroundWork.EXTRA_TEXT, "Hi! I have come from activity.")
.build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMinZoomPreference(15);
showCurrentLocationOnMap();
//locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(BackgroundWork.class, 15,
TimeUnit.MINUTES)
.addTag("notifWorker");
// ...if you want, you can apply constraints to the builder here...
// Create the actual work object:
PeriodicWorkRequest photoCheckWork = photoCheckBuilder.setInputData(data).build();
// Then enqueue the recurring task:
WorkManager.getInstance().enqueue(photoCheckWork);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
addLocationAlert(latLng.latitude, latLng.longitude);
}
});
}
#SuppressLint("MissingPermission")
private void showCurrentLocationOnMap() {
if (isLocationAccessPermitted()) {
requestLocationAccessPermission();
} else if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
/*public void addFence(View view){
addLocationAlert(28.360596,75.5863917); //28.360596 75.5863917 budh bhavan
addLocationAlert( 28.3603219,75.5868534); //ram marg
}*/
/*#SuppressLint("MissingPermission")
private void showCurrentLocationOnMap() {
if (isLocationAccessPermitted()) {
requestLocationAccessPermission();
}
}*/
private boolean isLocationAccessPermitted() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestLocationAccessPermission() {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
LOC_PERM_REQ_CODE);
}
#SuppressLint("MissingPermission")
private void addLocationAlert(double lat, double lng) {
if (isLocationAccessPermitted()) {
requestLocationAccessPermission();
} else {
String key = "" + lat + "-" + lng;
Geofence geofence = getGeofence(lat, lng, key);
/* geofencingClient.addGeofences(getGeofencingRequest(geofence),
getGeofencePendingIntent())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this,
"Location alter has been added",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,
"Location alter could not be added",
Toast.LENGTH_SHORT).show();
}
}
});*/
geofencingClient.addGeofences(getGeofencingRequest(geofence),
getGeofencePendingIntent())
.addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "added", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
}
private void removeLocationAlert() {
if (isLocationAccessPermitted()) {
requestLocationAccessPermission();
} else {
geofencingClient.removeGeofences(getGeofencePendingIntent())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this,
"Location alters have been removed",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,
"Location alters could not be removed",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case LOC_PERM_REQ_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showCurrentLocationOnMap();
Toast.makeText(MainActivity.this,
"Location access permission granted, you try " +
"add or remove location allerts",
Toast.LENGTH_SHORT).show();
}
return;
}
}
}
private PendingIntent getGeofencePendingIntent() {
Intent intent = new Intent(this, LocationAlertBroadcastReceiver.class);
return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private GeofencingRequest getGeofencingRequest(Geofence geofence) {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL);
builder.addGeofence(geofence);
return builder.build();
}
private Geofence getGeofence(double lat, double lang, String key) {
return new Geofence.Builder()
.setRequestId(key)
.setCircularRegion(lat, lang, GEOFENCE_RADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_DWELL)
.setLoiteringDelay(10000)
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.remove_loc_alert:
removeLocationAlert();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
GeofenceTransitionsJobIntentService:
package com.example.rohit.geofencefundo;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.support.v4.app.JobIntentService;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
public class GeofenceTransitionsJobIntentService extends JobIntentService {
private static final int JOB_ID = 573;
private static final String TAG = "GeofenceTransitionsIS";
private static final String CHANNEL_ID = "channel_01";
/**
* Convenience method for enqueuing work in to this service.
*/
public static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, GeofenceTransitionsJobIntentService.class, JOB_ID, intent);
}
/**
* Handles incoming intents.
* #param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
#Override
protected void onHandleWork(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionInfo(
triggeringGeofences);
String transitionType = getTransitionString(geofenceTransition);
sendNotification(transitionType, geofenceTransitionDetails);
sendNotification2(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
}
}
private String getGeofenceTransitionInfo(List<Geofence> triggeringGeofences) {
ArrayList<String> locationNames = new ArrayList<>();
for (Geofence geofence : triggeringGeofences) {
locationNames.add(getLocationName(geofence.getRequestId()));
}
String triggeringLocationsString = TextUtils.join(", ", locationNames);
return triggeringLocationsString;
}
private String getLocationNameGeocoder(double lat, double lng) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat,lng, 1);
} catch (Exception ioException) {
Log.e("", "Error in getting location name for the location");
}
if (addresses == null || addresses.size() == 0) {
Log.d("", "no location name");
return null;
} else {
Address address = addresses.get(0);
ArrayList<String> addressInfo = new ArrayList<>();
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
addressInfo.add(address.getAddressLine(i));
}
return TextUtils.join(System.getProperty("line.separator"), addressInfo);
}
}
private String getLocationName(String key) {
String[] strs = key.split("-");
String locationName = null;
if (strs != null && strs.length == 2) {
double lat = Double.parseDouble(strs[0]);
double lng = Double.parseDouble(strs[1]);
locationName = getLocationNameGeocoder(lat, lng);
}
if (locationName != null) {
return locationName;
} else {
return key;
}
}
private String getGeofenceTransitionDetails(
int geofenceTransition,
List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList<String> triggeringGeofencesIdsList = new ArrayList<>();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
private void sendNotification(String locTransitionType, String locationDetails) {
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "rohit901";
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
#SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,"My Notification",NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("rohit901 channel for app test FCM");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.support.compat.R.drawable.notification_icon_background)
.setTicker("Hearty365")
.setContentTitle(locTransitionType)
.setContentText(locationDetails)
.setContentInfo("info");
Random random = new Random();
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
m += random.nextInt(100) + 1;
notificationManager.notify(m,notificationBuilder.build());
}
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return getString(R.string.geofence_transition_entered);
case Geofence.GEOFENCE_TRANSITION_DWELL:
return "dwell at location";
case Geofence.GEOFENCE_TRANSITION_EXIT:
return getString(R.string.geofence_transition_exited);
default:
return getString(R.string.unknown_geofence_transition);
}
}
}
Background Work (Worker Class):
package com.example.rohit.geofencefundo;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Random;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
public class BackgroundWork extends Worker {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_TEXT = "text";
public static final String EXTRA_OUTPUT_MESSAGE = "output_message";
JSONObject jsonPart;
String result;
private Context mContext;
public BackgroundWork(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
mContext = context;
}
#NonNull
#Override
public Worker.Result doWork() {
//do work and shit
Log.d("work901","work and shit");
String title = getInputData().getString(EXTRA_TITLE);
String text = getInputData().getString(EXTRA_TEXT);
Log.d("work901tit","title from main is "+title);
Data output = new Data.Builder()
.putString(EXTRA_OUTPUT_MESSAGE, "I have come from MyWorker!")
.build();
sendNotification(title,text);
new JsonTask().execute("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2018-10-20&endtime=2018-10-21&latitude=33.9370804&longitude=135.8284085&maxradiuskm=5000");
setOutputData(output);
return Result.SUCCESS;
}
private void sendNotification(String title, String text) {
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "rohit901";
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
#SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,"My Notification",NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("rohit901 channel for app test FCM");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.support.compat.R.drawable.notification_icon_background)
.setTicker("Hearty365")
.setContentTitle(title)
.setContentText(text)
.setContentInfo("info");
Random random = new Random();
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
m += random.nextInt(100) + 1;
notificationManager.notify(m,notificationBuilder.build());
}
public class JsonTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
//pd.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Toast.makeText(FeedBackActivity.this, "DOne", Toast.LENGTH_SHORT).show();
Log.d("rohit901",s);
result = s;
try {
JSONObject jsonObject = new JSONObject(result);
String features = jsonObject.getString("features"); //array of features
//JSONObject jsonObject2 = new JSONObject(features);
//String geometry = jsonObject2.getString("geometry"); //array of geometry
//JSONObject jsonObject3 = new JSONObject(geometry);
//String coordinates = jsonObject3.getString("coordinates");
JSONArray arr = new JSONArray(features);
JSONArray locArr;
Log.d("work901Array",arr.toString());
for(int i =0;i<arr.length();i++) {
jsonPart = arr.getJSONObject(i);
//jsonPart2 =
locArr = new JSONArray(jsonPart.getJSONObject("geometry").getString("coordinates"));
Log.d("geo901","Longitude: "+locArr.getString(0)+", Latitude: "+locArr.getString(1));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
}
Rest of my code is here: GitHub
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,ActivityExpenseDetails.class);
intent.putExtra("employee_name",expenseArrayList.get(position).getEmployee_name());
intent.putExtra("expense_type",expenseArrayList.get(position).getExpense_type());
intent.putExtra("amount",expenseArrayList.get(position).getAmount());
intent.putExtra("description",expenseArrayList.get(position).getDescription());
context.startActivity(intent);
}
});
I have written an android app which basically allows me to keep track of times and address of GPS coordinates.
I have 3 Lists each corresponding to Lyft, Uber and Other.
But I believe my app starts slowing down my Smart Phone (Samsung Galaxy S7 Edge, with Android O)
can someone look at my code and tell me why is it slowing my smart phone.
My assumption is that, possibly thread synchronization issue.
Attached is my code
1) MainActivity.java
package com.milind.myapp.gpstrackingservice;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.PowerManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AddressListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private PowerManager.WakeLock wakeLock;
private TextView labelAddress;
private TextView multiTextLyft;
private TextView multiTextUber;
private TextView multiTextOther;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
labelAddress = findViewById(R.id.label_address);
multiTextLyft = findViewById(R.id.multi_text_lyft);
multiTextUber = findViewById(R.id.multi_text_uber);
multiTextOther = findViewById(R.id.multi_text_other);
if (MyService.isServiceStarted())
{
MyService.getInstance().load(getSharedPrefs());
refreshAllViews();
}
PowerManager powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "myapp:My Lock");
}
#Override
protected void onStart()
{
super.onStart();
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WAKE_LOCK}, 1);
if (!MyService.isServiceStarted())
{
Intent intent = new Intent(this, MyService.class);
intent.setAction(MyService.ACTION_START_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
startForegroundService(intent);
}
else
{
startService(intent);
}
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
{
if (MyService.isServiceStarted())
{
MyService.getInstance().registerAddressListener(this);
}
wakeLock.acquire();
}
else
{
if (MyService.isServiceStarted())
{
MyService.getInstance().unregisterAddressListener(this);
}
wakeLock.release();
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults)
{
switch (requestCode)
{
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location loc)
{
final String address = MyService.getAddress(this, loc);
final CharSequence text = labelAddress.getText();
if (text.toString().equals(address))
{
return;
}
MyService.getInstance().load(getSharedPrefs());
labelAddress.setText(address);
refreshAllViews();
new Tone().play(880);
}
private void refreshAllViews()
{
runOnUiThread(new Runnable()
{
public void run()
{
refereshEditTextLyft();
refereshEditTextUber();
refereshEditTextOther();
}
});
}
private void refereshEditTextLyft()
{
multiTextLyft.setText(MyService.getInstance().getLyftAddresses());
}
private void refereshEditTextUber()
{
multiTextUber.setText(MyService.getInstance().getUberAddresses());
}
private void refereshEditTextOther()
{
multiTextOther.setText(MyService.getInstance().getOtherAddresses());
}
private SharedPreferences getSharedPrefs()
{
return getSharedPreferences("name", MODE_PRIVATE);
}
public void onLyftButtonClicked(View view)
{
MyService.getInstance().addLyftAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextLyft();
MyService.getInstance().save(getSharedPrefs());
}
public void onUberButtonClicked(View view)
{
MyService.getInstance().addUberAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextUber();
MyService.getInstance().save(getSharedPrefs());
}
public void onOtherButtonClicked(View view)
{
MyService.getInstance().addOtherAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextOther();
MyService.getInstance().save(getSharedPrefs());
}
public void onClearButtonClicked(View view)
{
if (MyService.isServiceStarted())
{
SharedPreferences sharedPreferences = getSharedPrefs();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
MyService.getInstance().clear();
refereshEditTextLyft();
refereshEditTextUber();
refereshEditTextOther();
}
}
public void onDelLyftButtonClicked(View view)
{
MyService.getInstance().delLyftEntry();
new Tone().play(440);
refereshEditTextLyft();
MyService.getInstance().save(getSharedPrefs());
}
public void onDelUberButtonClicked(View view)
{
MyService.getInstance().delUberEntry();
new Tone().play(440);
refereshEditTextUber();
MyService.getInstance().save(getSharedPrefs());
}
public void onDelOtherButtonClicked(View view)
{
MyService.getInstance().delOtherEntry();
new Tone().play(440);
refereshEditTextOther();
MyService.getInstance().save(getSharedPrefs());
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
public void onActionModeFinished(ActionMode mode)
{
super.onActionModeFinished(mode);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
}
2) The MyService.java
package com.milind.myapp.gpstrackingservice;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MyService extends Service implements LocationListener
{
private static final String TAG = MyService.class.getSimpleName();
public static final String ACTION_START_SERVICE = "ACTION_START_SERVICE";
public static final String ACTION_STOP_SERVICE = "ACTION_STOP_SERVICE";
public static final String ACTION_UBER = "ACTION_UBER";
public static final String ACTION_LYFT = "ACTION_UBER";
public static final String ACTION_END = "ACTION_END";
public static final String LYFT_PREFIX = "Lyft";
public static final String OTHER_PREFIX = "Other";
public static final String UBER_PREFIX = "Uber";
private static MyService mInstance = null;
private List<AddressListener> listeners = new ArrayList<>();
private List<AddressPoint> lyftAddresses = new ArrayList<>();
private List<AddressPoint> uberAddresses = new ArrayList<>();
private List<AddressPoint> otherAddresses = new ArrayList<>();
private Location mLastLocation;
public MyService()
{
super();
Log.d(TAG, "MyService(): constructor called");
}
public static boolean isServiceStarted()
{
Log.d(TAG, "isServiceStarted()");
return mInstance != null;
}
public static final MyService getInstance()
{
return mInstance;
}
#Override
public IBinder onBind(Intent intent)
{
Log.d(TAG, "onBind(Intent intent)");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand(Intent, flags, startId) : " + hashCode());
Log.d(TAG, "onStartCommand(...) intent=" + intent + "=" + ", flags=" + flags + ", startId=" + startId);
Log.d(TAG, "onStartCommand(...) isServiceStarted=" + isServiceStarted());
String action = null;
if (intent != null)
{
Log.d(TAG, intent.toString());
action = intent.getAction();
}
else
{
Log.d(TAG, "onStartCommand(...): early return");
return super.onStartCommand(intent, flags, startId);
}
if (isServiceStarted() == false && action == ACTION_START_SERVICE)
{
Log.d(TAG, "onStartCommand(...): Service starting=" + startId);
//startForegroundServivceNotification()
startRunningInForeground();
requestLocationUpdates();
mInstance = this;
Log.d(TAG, "onStartCommand(...): Service started=" + startId);
}
else if (isServiceStarted() == true && action == ACTION_STOP_SERVICE)
{
Log.d(TAG, "onStartCommand(...): Service stopping=" + startId);
stopLocationUpdates();
stopSelf();
Log.d(TAG, "onStartCommand(...): Service stop requested" + startId);
mInstance = null;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
Log.d(TAG, "onDestroy(): Service destroyed");
super.onDestroy();
mInstance = null;
}
private void stopLocationUpdates()
{
Log.d(TAG, "stopLocationUpdates()");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
private void requestLocationUpdates()
{
Log.d(TAG, "requestLocationUpdates()");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1500, 0, this);
Log.w(TAG, "requestLocationUpdates(): ended gracefully");
}
catch (SecurityException ex)
{
Log.w(TAG, "requestLocationUpdates(): Exception");
ex.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location)
{
Log.v(TAG, "onLocationChanged(Location location): started, location=" + location.toString());
dispatchLocationChange(location);
mLastLocation = location;
Log.v(TAG, "onLocationChanged: completed");
}
private void dispatchLocationChange(Location loc)
{
Log.v(TAG, "dispatchLocationChange(Location)");
for (AddressListener listener : listeners)
{
listener.onLocationChanged(loc);
}
}
public static String getAddress(Context context, Location loc)
{
Log.v(TAG, "getAddress(Location loc) started");
List<Address> addresses;
Geocoder gcd = new Geocoder(context, Locale.getDefault());
try
{
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
String strReturnAddress = "";
if (addresses != null && addresses.size() > 0)
{
final Address address = addresses.get(0);
Log.d(TAG, address.toString());
String addressLines = "";
Log.v(TAG, "Locale: " + address.getLocale());
for (int i = 0; i <= address.getMaxAddressLineIndex(); ++i)
{
Log.v(TAG, "AddressLine " + i + ": " + address.getAddressLine(i));
addressLines += address.getAddressLine(i) + ", ";
Log.v(TAG, "addressLines:" + addressLines);
}
String strAddress =
addressLines
;
Log.v(TAG, "strAddress:" + strAddress);
strReturnAddress = strAddress.substring(0, strAddress.length() - 2);
Log.v(TAG, "strReturnAddress:" + strReturnAddress);
}
Log.d(TAG, "getAddress(Location loc) completed with return=" + strReturnAddress);
return strReturnAddress;
}
catch (IOException e)
{
e.printStackTrace();
Log.d(TAG, "Exception", e);
}
Log.d(TAG, "getAddress(Location loc) completed with return=null");
return "";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.d(TAG, "onStatusChanged(provider, status, extras): status=" + status + ", extras=" + extras);
}
#Override
public void onProviderEnabled(String provider)
{
Log.d(TAG, "onProviderEnabled(provider) ");
}
#Override
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled(provider) ");
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private static void logGetProperties(final String tag, final Object obj)
{
Log.v(tag, "logGetProperties(...)");
Class cls = obj.getClass();
Method[] methods = cls.getMethods();
Log.v(tag, "methods.length = " + methods.length);
for (Method method : methods)
{
String methodName = method.getName();
Log.v(tag, "methodName = " + methodName);
if (methodName.startsWith("get")
&& (method.getParameters() == null || method.getParameters().length == 0)
&& method.getReturnType() != Void.class)
{
try
{
Log.v(tag, methodName + " = " + method.invoke(obj, new Object[0]));
}
catch (Exception ex)
{
Log.e(tag, methodName + " Failed (exception)");
}
}
}
}
public AddressListener registerAddressListener(AddressListener listener)
{
Log.d(TAG, "registerAddressListener(AddressListener)");
if (!listeners.contains(listener))
{
listeners.add(listener);
}
return listener;
}
public AddressListener unregisterAddressListener(AddressListener listener)
{
Log.d(TAG, "unregisterAddressListener(AddressListener)");
if (listeners.contains(listener))
{
listeners.remove(listener);
Log.d(TAG, "unregisterAddressListener(AddressListener): Listener removed");
return listener;
}
Log.d(TAG, "unregisterAddressListener(AddressListener): Listener not found");
return null;
}
public void addLyftAddress(CharSequence text)
{
Log.d(TAG, "addLyftAddress(CharSequence text): text: " + text);
lyftAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
public void addUberAddress(CharSequence text)
{
Log.d(TAG, "addUberAddress(CharSequence text): text: " + text);
uberAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
public void addOtherAddress(CharSequence text)
{
Log.d(TAG, "addOtherAddress(CharSequence text): text: " + text);
otherAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
String getLyftAddresses()
{
return getAddresses(lyftAddresses);
}
String getUberAddresses()
{
return getAddresses(uberAddresses);
}
String getOtherAddresses()
{
return getAddresses(otherAddresses);
}
private String getAddresses(List<AddressPoint> addresses)
{
Log.d(TAG, "getAddresses(List<AddressPoint>)");
String strAddresses = "" + addresses.size() + "\n--------\n";
for (int i = 0; i < addresses.size(); ++i)
{
AddressPoint addresspoint = addresses.get(i);
strAddresses += addresspoint + "\n--------\n";
if ((i % 2) != 0)
{
strAddresses += "\n\n";
}
}
return strAddresses;
}
private void startRunningInForeground()
{
//if more than or equal to 26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
//if more than 26
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
{
String CHANNEL_ONE_ID = "Package.Service";
String CHANNEL_ONE_NAME = "Screen service";
NotificationChannel notificationChannel = null;
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null)
{
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle("Recording data")
.setContentText("App is running background operations")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(101, notification);
}
//if version 26
else
{
startForeground(101, updateNotification());
}
}
//if less than version 26
else
{
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("App")
.setContentText("App is running background operations")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setOngoing(true).build();
startForeground(101, notification);
}
}
private Notification updateNotification()
{
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
return new NotificationCompat.Builder(this)
.setContentTitle("Activity log")
.setTicker("Ticker")
.setContentText("app is running background operations")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setOngoing(true).build();
}
public void load(final SharedPreferences lSharedPrefs)
{
Log.w(TAG, "load(SharedPreferences): started");
load(lSharedPrefs, lyftAddresses, LYFT_PREFIX);
load(lSharedPrefs, uberAddresses, UBER_PREFIX);
load(lSharedPrefs, otherAddresses, OTHER_PREFIX);
Log.w(TAG, "load(SharedPreferences): completed");
}
private void load(final SharedPreferences lSharedPrefs, final List<AddressPoint> lAddrPoints, final String lPrefix)
{
Log.w(TAG, "load(SharedPreferences, lAddrPoints, lPrefix)");
lAddrPoints.clear();
final int count = lSharedPrefs.getInt(lPrefix + "Count", lAddrPoints.size());
for (int i = 0; i < count; ++i)
{
String address = lSharedPrefs.getString(lPrefix + "Address" + i, null);
final long time = lSharedPrefs.getLong(lPrefix + "Time" + i, 0);
//if address or time is invalid skip to the next entry
if (address == null || time == 0)
{
continue;
}
final AddressPoint addressPoint = new AddressPoint(time, address);
lAddrPoints.add(addressPoint);
}
}
private void save(final SharedPreferences lSharedPrefs, final List<AddressPoint> lAddrPoints, final String lPrefix)
{
Log.w(TAG, "save(SharedPreferences, lAddrPoints, lPrefix)");
SharedPreferences.Editor editor = lSharedPrefs.edit();
final int count = lAddrPoints.size();
//Save the count
editor.putInt(lPrefix + "Count", count);
for (int i = 0; i < count; ++i)
{
//Save the entry
AddressPoint lAddrPoint = lAddrPoints.get(i);
editor.putLong(lPrefix + "Time" + i, lAddrPoint.getTime());
editor.putString(lPrefix + "Address" + i, (String) lAddrPoint.getAddress());
}
Log.w(TAG, "save(sharedFrefs, List, String): commit");
editor.commit();
}
public void save(final SharedPreferences sharedPreferences)
{
Log.w(TAG, "save(SharedPreferences): started");
Log.w(TAG, "save: lyftAddresses");
save(sharedPreferences, lyftAddresses, LYFT_PREFIX);
Log.w(TAG, "save: uberAddresses");
save(sharedPreferences, uberAddresses, UBER_PREFIX);
Log.w(TAG, "save: otherAddresses");
save(sharedPreferences, otherAddresses, OTHER_PREFIX);
Log.w(TAG, "save(SharedPreferences) completed");
}
public void clear()
{
lyftAddresses.clear();
uberAddresses.clear();
otherAddresses.clear();
}
public void delLyftEntry()
{
if (lyftAddresses.size() > 0)
{
lyftAddresses.remove(lyftAddresses.size() - 1);
}
}
public void delUberEntry()
{
if (uberAddresses.size() > 0)
{
uberAddresses.remove(uberAddresses.size() - 1);
}
}
public void delOtherEntry()
{
if (otherAddresses.size() > 0)
{
otherAddresses.remove(otherAddresses.size() - 1);
}
}
}
3) activity_main.xml
4) AndroidManifest.xml
This (likely) isn't a threading issue, in the normal sense of the word. What's happening is you've got a GeoCoder.getFromLocation() call executing on the main thread. Per the documentation:
The returned values may be obtained by means of a network lookup. ...It may be useful to call this method from a thread separate from your primary UI thread.
That means the method could block for several seconds each time it is called. That's more likely if you're driving through an area of spotty cell coverage. Since the method is called with each location update (roughly every 2 seconds), it's understandable that the UI is hanging.
SUGGESTED FIX
Replace your getAddress() function with an AsyncTask, which moves the getFromLocation() call to a background thread (now your app will truly be multithreaded). Something like this should work:
private class GetFromLocationTask extends AsyncTask<Location, Void, List<Address>> {
protected List<Address> doInBackground(Location... locs) {
return gcd.getFromLocation(locs[ 0 ].getLatitude(), locs[ 0 ].getLongitude(), 1);
}
protected void onProgressUpdate(Void... progress) {}
protected void onPostExecute(List<Address> result) {
//execute the remainder of your getAddress() logic here
}
}
Then, execute it using new GetFromLocationTask().execute(location). Call this instead of getAddress(). You don't need to pass a Context to getAddress(), since Service.this will work just as well (it is a Context).
Bonus hint: Note that onLocationChanged() runs on the UI thread, and so does refreshAllViews(). That means your call to runOnUiThread() is superfluous, and it will just execute the given Runnable synchronously.
So here I want to have click event on pressing which i will have particular Category of location rather than search box for searching places. On pressing OnClickGPS it will open PlacePickerFragment of Facebook with search box at the top. But i want to search places category wise like Restaurent, Theatre, etc. on button click. Any assistance in this will be highly appreciable.
package com.priyank.checkin;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.model.GraphLocation;
import com.facebook.model.GraphPlace;
import com.facebook.widget.PlacePickerFragment;
import com.facebook.Session;
public class PlacePickerSampleActivity extends FragmentActivity implements LocationListener {
private static final int PLACE_ACTIVITY = 1;
private static final Location SEATTLE_LOCATION = new Location("") {
{
setLatitude(47.6097);
setLongitude(-122.3331);
}
};
private static final Location SAN_FRANCISCO_LOCATION = new Location("") {
{
setLatitude(37.7750);
setLongitude(-122.4183);
}
};
private static final Location PARIS_LOCATION = new Location("") {
{
setLatitude(48.857875);
setLongitude(2.294635);
}
};
private TextView resultsTextView;
private LocationManager locationManager;
private Location lastKnownLocation;
private String NameEditTextValue;
private EditText NameEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main7);
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
NameEditTextValue = NameEditText.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Alert Message");
i.putExtra(Intent.EXTRA_TEXT, NameEditTextValue +"- via Security Android App");
startActivity(Intent.createChooser(i, "Alert Status"));
}
});
NameEditText = (EditText) findViewById(R.id.editText1);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
Button button = (Button) findViewById(R.id.seattleButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickSeattle();
}
});
button = (Button) findViewById(R.id.sanFranciscoButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickSanFrancisco();
}
});
button = (Button) findViewById(R.id.gpsButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickGPS();
}
});
if (Session.getActiveSession() == null ||
Session.getActiveSession().isClosed()) {
Session.openActiveSession(this, true, null);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onStart() {
super.onStart();
// Update the display every time we are started (this will be "no place selected" on first
// run, or possibly details of a place if the activity is being re-created).
displaySelectedPlace(RESULT_OK);
}
private void onError(Exception exception) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error").setMessage(exception.getMessage()).setPositiveButton("OK", null);
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PLACE_ACTIVITY:
displaySelectedPlace(resultCode);
break;
default:
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
break;
}
}
private void displaySelectedPlace(int resultCode) {
String results = "";
PlacePickerApplication application = (PlacePickerApplication) getApplication();
GraphPlace selection = application.getSelectedPlace();
if (selection != null) {
GraphLocation location = selection.getLocation();
results = String.format("Name: %s\nCategory: %s\nLocation: (%f,%f)\nStreet: %s, %s, %s, %s, %s",
selection.getName(), selection.getCategory(),
location.getLatitude(), location.getLongitude(),
location.getStreet(), location.getCity(), location.getState(), location.getZip(),
location.getCountry());
} else {
results = "<No place selected>";
}
resultsTextView.setText(results);
NameEditText.setText(results);
}
public void onLocationChanged(Location location) {
lastKnownLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void startPickPlaceActivity(Location location) {
PlacePickerApplication application = (PlacePickerApplication) getApplication();
application.setSelectedPlace(null);
Intent intent = new Intent(this, PickPlaceActivity.class);
PickPlaceActivity.populateParameters(intent, location, null);
startActivityForResult(intent, PLACE_ACTIVITY);
}
private void onClickSeattle() {
try {
startPickPlaceActivity(SEATTLE_LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onClickSanFrancisco() {
try {
startPickPlaceActivity(SAN_FRANCISCO_LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onClickGPS() {
try {
if (lastKnownLocation == null) {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (bestProvider != null) {
lastKnownLocation = locationManager.getLastKnownLocation(bestProvider);
}
}
if (lastKnownLocation == null) {
String model = android.os.Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// Looks like they are on an emulator, pretend we're in Paris if we don't have a
// location set.
lastKnownLocation = PARIS_LOCATION;
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.error_dialog_title)
.setMessage(R.string.no_location)
.setPositiveButton(R.string.ok_button, null)
.show();
return;
}
}
startPickPlaceActivity(lastKnownLocation);
} catch (Exception ex) {
onError(ex);
}
}
}
The best way to do this is to use the PlacePickerFragment, and call setSearchText("restaurant"). While it doesn't necessarily restrict it to a category, it will search everything that is categorized as a restaurant.
You can also see an example of this in the Scrumptious sample app (in the PickerActivity class).
I'm trying to make speaking dictionary.
LogCat shows "Successfully bound to com.android.tts" but when the Speak button clicked, it shows "failed speak : not bound to tts engine".
But on AVD it runs smoothly, why?
This Is my goTranslator class:
package sk.team;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import android.content.Intent;
import android.content.res.Configuration;
import java.util.Locale;
public class goTranslator extends Activity implements TextToSpeech.OnInitListener{
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private SQLiteDatabase db = null;
private Cursor translatorCursor = null;
private EditText txtSearch;
private EditText txtResult;
private AppDatabase dbtranslator = null;
private RadioButton Eng,Ind;
private Button Translate,Speak;
public static final String ENGLISH = "english";
public static final String INDONESIA = "indonesia";
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(goTranslator.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(goTranslator.this,
"Error occurred while initializing Text-To-Speech engine",
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbtranslator = new AppDatabase(this);
db = dbtranslator.getWritableDatabase();
setContentView(R.layout.main);
dbtranslator.createTable(db);
dbtranslator.generateData(db);
Eng = (RadioButton) findViewById(R.id.Eng);
Ind = (RadioButton) findViewById(R.id.Ind);
Translate = (Button) findViewById(R.id.Translate);
Speak = (Button) findViewById(R.id.Speak);
txtSearch = (EditText) findViewById(R.id.txtSearch);
txtResult = (EditText) findViewById(R.id.txtResult);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
Speak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = txtResult.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(goTranslator.this, "Saying: " + text,
Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
public void Translate (View view) {
if (view == Translate) {
if (Eng.isChecked()) {
txtSearch.setHint("Masukkan Kata");
Locale loc = new Locale ("es_ES");
tts.setLanguage(loc);
String result = "";
String englishword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where ENGLISH='" + englishword
+ "' ORDER BY ENGLISH", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(2);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(2);
}
}
if (result.equals("")) {
result = "Kata Tidak Tersedia";
}
txtResult.setText(result);
}
if (Ind.isChecked()) {
txtSearch.setHint("Enter Word");
Locale loc = new Locale ("en_US");
tts.setLanguage(loc);
String result = "";
String indonesiaword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where INDONESIA='" + indonesiaword
+ "' ORDER BY INDONESIA", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(1);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(1);
}
}
if (result.equals("")) {
result = "Result Not Found";
}
txtResult.setText(result);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
#Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (translatorCursor != null) {
translatorCursor.close();
db.close();
}
}
}
Log.w(TAG, method + " failed: not bound to TTS engine");
I caused by
mServiceConnection;
Being null
Does your testing device lack an internet connection?
Ok so first off, the issue is when i install my app and open it, it is starting a activity without being declared in my manifest as here below.
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
I know that this above declare the a activity to be the activity ran when the app is launched, therefore should be the only one. Well i have some source code that i didn't originally write, Its for a launcher replacement app, therefore inside the source code i cant figure out how it is being launcher when its not declared in the manifest for this activity to be ran from the intial start, Its declare, but there isnt even a intent filter for it.
Is there some sort of java code you can declare a activity to be ran when the app is launched for the first time??? thats mainly my question.
Here The source im working with
classic.java
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.Toast;
public class classic extends Activity {
/** Called when the activity is first created. */
private static String mPackageName = Constants.PACKAGE_LAUNCHER;
private ComponentName mCn = null;
private Activity currentActivity = null;
private boolean mApplyTheme = false;
private AlertDialog mConfirmDialog = null;
private ProgressDialog mProgressDialog = null;
private final String GOLAUNCHER_PKG_NAME = "com.gau.go.launcherex";
AttachInfo mAi = null;
class CustomAlertDialog extends AlertDialog {
public CustomAlertDialog(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = super.onKeyDown(keyCode, event);
finish();
return ret;
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
private Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
AlertDialog.Builder localBuilder2 = new AlertDialog.Builder(
classic.this);
localBuilder2.setTitle("Go Launcher EX not Found");
localBuilder2
.setMessage("Do you want to vist the Go Launcher EX on Google Play?");
localBuilder2.setIcon(R.drawable.golauncherex);
localBuilder2.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface paramDialogInterface,
int paramInt) {
Intent localIntent = new Intent(
"android.intent.action.VIEW").setData(Uri
.parse("market://details?id=com.gau.go.launcherex"));
classic.this.startActivity(localIntent);
}
});
localBuilder2.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface paramDialogInterface,
int paramInt) {
}
});
localBuilder2.show();
}
};
#Override
protected void onResume() {
super.onResume();
currentActivity = this;
ThemeUtils.sendInactiveApplyThemeFlagBroadcast(this);
if (isExistGO(GOLAUNCHER_PKG_NAME))
{
final Result result = new Result();
displayStartGoLauncherDialog(result);
setVisible(false);
return;
}
setVisible(false);
mAi = MergeUtil.getAttachInfo(this);
// 判æ–é™„åŠ çš„æ˜¯åœ°å�€è¿˜æ˜¯apk
if(mAi != null && mAi.IsAttachApk())
{
// �动�并
MergeUtil.DoMergeFileTask(mHandler, this);
setVisible(false);
return;
}
AlertDialog.Builder localBuilder2 = new AlertDialog.Builder(
classic.this);
localBuilder2.setTitle("Go Launcher EX not Found");
localBuilder2
.setMessage("Do you want to vist the Go Launcher EX on Google Play?");
localBuilder2.setIcon(R.drawable.golauncherex);
localBuilder2.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface paramDialogInterface,
int paramInt) {
Intent localIntent = new Intent(
"android.intent.action.VIEW").setData(Uri
.parse("market://details?id=com.gau.go.launcherex"));
classic.this.startActivity(localIntent);
}
});
localBuilder2.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface paramDialogInterface,
int paramInt) {
}
});
localBuilder2.show();
}
private boolean isExistGO(String packageName) {
Result result = GoLauncherUtils.isGoLauncherExist(this);
mPackageName = result.packageName == null ? Constants.PACKAGE_LAUNCHER
: result.packageName;
mCn = result.componentName;
return result.isExist;
}
private void startGOLauncher(String packageName) throws Throwable {
GoLauncherUtils.startGoLauncher(this, packageName, mCn);
}
private void displayStartGoLauncherDialog(final Result result) {
String dialogtitle = null;
String dialogmsg = null;
String dialogok = null;
String dialogcancel = null;
String language = Locale.getDefault().getLanguage(); // zh
if(language.equals("zh"))
{
dialogtitle = "信�";
dialogmsg = "点击确定立刻�用桌�支�软件";
dialogok = "确定";
dialogcancel = "�消";
}
else
{
dialogtitle = "Go Launcher EX";
dialogmsg = "Press OK button to launch GO Launcher EX";
dialogok = "OK";
dialogcancel = "Cancel";
}
mConfirmDialog = new AlertDialog.Builder(this)
.setTitle(dialogtitle)
.setMessage(dialogmsg)
.setPositiveButton(dialogok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// NotificationActivity.this.finish();
startGoLauncher(
result.packageName == null ? Constants.PACKAGE_LAUNCHER
: result.packageName,
result.componentName);
}
})
.setNegativeButton(dialogcancel,
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
classic.this.finish();
}
}).setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
classic.this.finish();
}
return false;
}
}).show();
}
private void startGoLauncher(final String packageName,
final ComponentName componentName) {
mApplyTheme = true;
new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPreExecute() {
String msg = null;
String language = Locale.getDefault().getLanguage(); // zh
if(language.equals("zh"))
{
msg = "GOæ¡Œé�¢EXå�¯ç”¨ä¸ï¼Œè¯·ç¨�å�Ž";
}
else
{
msg = "Applying The Galaxy S3 Theme, Please Wait";
}
mProgressDialog = ProgressDialog.show(
classic.this,
null,
msg,
true);
}
#Override
protected Boolean doInBackground(Void... v) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
classic.this.finish();
try {
GoLauncherUtils.startGoLauncher(classic.this,
packageName, componentName);
} catch (Throwable e) {
return false;
}
return true;
}
protected void onPostExecute(Boolean success) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (!success) {
String msg = null;
String language = Locale.getDefault().getLanguage();
// zh
if(language.equals("zh"))
{
msg = "GO桌��用失败,请�新安装GO桌�";
}
else
{
msg = "Start GO Launcher EX failed, please reinstall GO Launcher EX";
}
Toast.makeText(
classic.this,
msg,
Toast.LENGTH_LONG).show();
}
};
}.execute();
}
#Override
protected void onStop() {
super.onStop();
if (mApplyTheme) {
mApplyTheme = false;
ThemeUtils.sendApplyThemeBroadcast(this);
}
}
#Override
protected void onDestroy() {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
if (mConfirmDialog != null) {
mConfirmDialog.dismiss();
mConfirmDialog = null;
}
super.onDestroy();
}
}
GoLauncherUtils.java
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
public class GoLauncherUtils {
public static final String NAME_GOLAUNCHER = "go_launcher";
public static final String KEY_UNINSTALLED = "uninstalled";
public static void startGoLauncher(Context context, String packageName,
ComponentName componentName) throws Throwable {
PackageManager packageMgr = context.getPackageManager();
Intent launchIntent = packageMgr.getLaunchIntentForPackage(packageName);
if (launchIntent != null) {
try {
context.startActivity(launchIntent);
} catch (Throwable t1) {
t1.printStackTrace();
if (componentName != null) {
Intent intent = new Intent(Intent.ACTION_MAIN);
//intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(componentName);
try {
context.startActivity(intent);
} catch (Throwable t2) {
t2.printStackTrace();
throw t2;
}
} else {
throw t1;
}
}
} else {
if (componentName != null) {
Intent intent = new Intent(Intent.ACTION_MAIN);
//intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(componentName);
try {
context.startActivity(intent);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
}
}
public static void downloadGoLauncher(Context context , final String aUrl) {
Intent intent = new Intent();
intent.setClass(context, GoDownloadService.class);
String fileName = "GO Launcher EX";
intent.putExtra("downloadFileName", fileName);
intent.putExtra(Constants.DOWNLOAD_URL_KEY, aUrl);
context.startService(intent);
}
public static Result isGoLauncherExist(Context context) {
Result result = new Result();
PackageManager pm = context.getPackageManager();
// Launcher
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.HOME");
intent.addCategory("android.intent.category.DEFAULT");
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
int launcherSz = infos.size();
for (int i = 0; i < launcherSz; i++) {
ResolveInfo info = infos.get(i);
if (null == info || null == info.activityInfo
|| null == info.activityInfo.packageName) {
continue;
}
String packageStr = info.activityInfo.packageName;
if (packageStr.contains(Constants.PACKAGE_LAUNCHER)) {
result.packageName = packageStr;
result.componentName = new ComponentName(packageStr,
info.activityInfo.name);
result.isExist = true;
return result;
}
}
return result;
}
public static boolean isGoLauncherRunning(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
// List<RunningAppProcessInfo> infos = am.getRunningAppProcesses();
// for (RunningAppProcessInfo info : infos) {
// System.out.println("---------------running process: "
// + info.processName);
//
// if
// ("com.gau.go.launcherex".equals(info.importanceReasonComponent.getPackageName()))
// {
// goLauncherRunning = true;
// break;
// }
// }
List<RunningServiceInfo> infos = am.getRunningServices(500);
for (RunningServiceInfo info : infos) {
if (Constants.PACKAGE_LAUNCHER
.equals(info.service.getPackageName())) {
return true;
}
}
return false;
}
public static boolean isGoLauncherUninstalled(Context context) {
SharedPreferences sp = context.getSharedPreferences(NAME_GOLAUNCHER,
Context.MODE_PRIVATE);
return sp.getBoolean(KEY_UNINSTALLED, false);
}
public static void setGoLauncherUninstalled(Context context,
boolean uninstalled) {
SharedPreferences sp = context.getSharedPreferences(NAME_GOLAUNCHER,
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putBoolean(KEY_UNINSTALLED, uninstalled);
editor.commit();
}
}
All i need help with is just disabling anything starting onstartup of the application, i only need this to be used when i send a intent over to it from a button click from another activity. please any help with find where i can disable this from the intial startup would be awesome.