How to add value on Permission Manager - android

I was wondering how to set value on manager? Here's how I initialize PermissionManager manager or PermissionManager manager = new?
public PermissionManager manager = new PermissionManager(PermissionManager.mActivity, PermissionManager.mContext);
protected void onStart() {
super.onStart();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/*String[] list = new String[]{PermissionConsts.PHONE_STATE, PermissionConsts.READ_CONTACTS, PermissionConsts.READ_EXTERNAL_STORAGE,
PermissionConsts.READ_SMS};*/
manager.requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
}
Intent serviceIntent = new Intent(this, LocationFetcherService.class);
startService(serviceIntent);
}
Here it doesn't work:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
initLocationFetching(this);
}
}
Here is BaseActivityLocation class
public class BaseActivityLocation extends AppCompatActivity implements LocationManagerInterface {
public SmartLocationManager mLocationManager;
public PermissionManager manager = new PermissionManager(BaseActivityLocation.this, BaseActivityLocation.this);
public LocationFetcherService mLocationFetcherService;
private static final int REQUEST_FINE_LOCATION = 1;
private Activity mCurrentActivity;
private int count = 0;
#Override
public void locationFetched(Location mLocation, Location oldLocation, String time, String locationProvider) {
// storing it on application level
GetAccurateLocationApplication.mCurrentLocation = mLocation;
GetAccurateLocationApplication.oldLocation = oldLocation;
GetAccurateLocationApplication.locationProvider = locationProvider;
GetAccurateLocationApplication.locationTime = time;
}
public void instatntiate(Activity mActivity){
/*3rd Parametr*/
//For One time Gps Usage: SmartLocationManager.USE_ONE_TIME_GPS;
//For every 10 seconds Gps Usage: SmartLocationManager.USE_UPDATE_TIME_GPS;
/*4th parameter*/
//For All netwrok Provider: SmartLocationManager.ALL_PROVIDERS;
//For Network Provider only: SmartLocationManager.NETWORK_PROVIDER;
//For GPS Provider only: SmartLocationManager.GPS_PROVIDER;
/*Last Parameter*/
//For using Any Api location: SmartLocationManager.ANY_API; //The priority will be google api.
//For using google Api location: SmartLocationManager.ONLY_GOOGLE_API;
//For using android Api Location: SmartLocationManager.ONLY_ANDROID_API;
mLocationManager = new SmartLocationManager(getApplicationContext(), mActivity, SmartLocationManager.USE_ONE_TIME_GPS, this, SmartLocationManager.ALL_PROVIDERS, LocationRequest.PRIORITY_HIGH_ACCURACY, 10 * 1000, 1 * 1000, SmartLocationManager.LOCATION_PROVIDER_RESTRICTION_NONE, SmartLocationManager.ANY_API); // init location manager
}
public void initLocationFetching(Activity mActivity) {
mCurrentActivity = mActivity;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager = new PermissionManager(mCurrentActivity, getApplicationContext());
PermissionManagerInterface permissionManagerInterface = new PermissionManagerInterface() {
#Override
public void onPermissionGranted(String message, int requestCode) {
}
Here is the code of Permission Manager class but I am having a null value where I want to eliminate
public class PermissionManager implements RequestPermissionsResultInterface {
public static Activity mActivity;
public static Context mContext;
public String[] permissionList;
public boolean flag;
private PermissionManagerInterface mManagerInterface = new PermissionManagerInterface() {
#Override
public void onPermissionGranted(String message, int requestCode) {
}
#Override
public void onPermissionDenied(String message, int requestCode) {
}
#Override
public void isAllGranted(boolean flag) {
}
};
public PermissionManager(Activity mActivity, Context mContext) {
this.mActivity = mActivity;
this.mContext = mContext;
}
public void requestPermission(String[] mList){
permissionList = mList;
ActivityCompat.requestPermissions(mActivity, mList, REQ_CODE);
}
public void getManagerInterface(PermissionManagerInterface mInterface){
mManagerInterface = mInterface;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == REQ_CODE){
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];
String packageStrippedPermissionName = permissions[i].substring(permissions[0].lastIndexOf(".")+1);
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
// user rejected the permission
boolean showRationale = mActivity.shouldShowRequestPermissionRationale( permission );
if (! showRationale) {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(permission + " Required");
builder.setMessage("You have to grant this permission , otherwise app will not be able to continue, Click Yes to go to Settings else app will not resume!");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
intent.setData(uri);
mActivity.startActivityForResult(intent, REQ_CODE);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(mContext, "App will not Start without this Permission", Toast.LENGTH_SHORT).show();
mActivity.finish();
}
});
builder.setCancelable(false);
builder.show();
// user also CHECKED "never ask again"
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
}else{
mManagerInterface.onPermissionDenied("\'" + packageStrippedPermissionName + "': permission denied", requestCode);
Alert(mActivity, permissions[i]);
}
}else if(grantResults[i] == PackageManager.PERMISSION_GRANTED){
mManagerInterface.onPermissionGranted("\'" + packageStrippedPermissionName + "\': permission granted", requestCode);
}
}
ArrayList<String> list = new ArrayList<>();
for(int k=0; k<grantResults.length; k++){
if(grantResults[k] == PackageManager.PERMISSION_GRANTED){
list.add(permissions[k]);
}
}
if(list.size() == permissions.length){
flag = true;
mManagerInterface.isAllGranted(flag);
}else{
flag = false;
mManagerInterface.isAllGranted(flag);
}
}
}
BaseActivityLocation java class:
BaseActivityLocation extends AppCompatActivity implements LocationManagerInterface {
public SmartLocationManager mLocationManager;
public PermissionManager manager = null;
public LocationFetcherService mLocationFetcherService;
private static final int REQUEST_FINE_LOCATION = 1;
private Activity mCurrentActivity;
private int count = 0;
#Override
public void locationFetched(Location mLocation, Location oldLocation, String time, String locationProvider) {
// storing it on application level
GetAccurateLocationApplication.mCurrentLocation = mLocation;
GetAccurateLocationApplication.oldLocation = oldLocation;
GetAccurateLocationApplication.locationProvider = locationProvider;
GetAccurateLocationApplication.locationTime = time;
}
protected void onStart() {
super.onStart();
manager = new PermissionManager(BaseActivityLocation.this, BaseActivityLocation.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/*String[] list = new String[]{PermissionConsts.PHONE_STATE, PermissionConsts.READ_CONTACTS, PermissionConsts.READ_EXTERNAL_STORAGE,
PermissionConsts.READ_SMS};*/
manager.requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
}
Intent serviceIntent = new Intent(this, LocationFetcherService.class);
startService(serviceIntent);
}
protected void onResume(){
super.onResume();
//showLocationPermission();
}
Permission Manager Interface
public interface PermissionManagerInterface extends Serializable
{
String TAG = PermissionManagerInterface.class.getSimpleName();
void onPermissionGranted(String message, int requestCode);
void onPermissionDenied(String message, int requestCode);
void isAllGranted(boolean flag);
}

Try this if this is inside a activity. YourActivity is your activity name:
public PermissionManager manager = null;
protected void onStart() {
super.onStart();
manager = new PermissionManager(YourActivity.this, YourActivity.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/*String[] list = new String[]{PermissionConsts.PHONE_STATE, PermissionConsts.READ_CONTACTS, PermissionConsts.READ_EXTERNAL_STORAGE,
PermissionConsts.READ_SMS};*/
manager.requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
}
Intent serviceIntent = new Intent(this, LocationFetcherService.class);
startService(serviceIntent);
}

Related

Get Distance & UUID of Google Beacon

I have registered my beacon on the Google Beacon Platform and download the "Beacon Tools" android app to scan the beacon. Below I have attached its screenshot.
Now I'm developing an android app for that beacon and using this app I can get attachments that I set for the beacon. I 'am using Nearby Messages API for this. Now I want to get UUID and distance between user & beacon. I 'm new to these things and read many stackoverflow questions and answers. but those didn't solve my problem
Below I have mentioned my classes.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_CODE = 1111;
private static final String KEY_SUBSCRIBED = "subscribed";
/**
* The entry point to Google Play Services.
*/
private GoogleApiClient mGoogleApiClient;
/**
* The container {#link android.view.ViewGroup} for the minimal UI associated with this sample.
*/
private RelativeLayout mContainer;
/**
* Tracks subscription state. Set to true when a call to
* {#link Messages#subscribe(GoogleApiClient, MessageListener)} succeeds.
*/
private boolean mSubscribed = false;
/**
* Adapter for working with messages from nearby beacons.
*/
private ArrayAdapter<String> mNearbyMessagesArrayAdapter;
/**
* Backing data structure for {#code mNearbyMessagesArrayAdapter}.
*/
private List<String> mNearbyMessagesList = new ArrayList<>();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
if (savedInstanceState != null) {
mSubscribed = savedInstanceState.getBoolean(KEY_SUBSCRIBED, false);
}
mContainer = (RelativeLayout) findViewById(R.id.main_activity_container);
if (!havePermissions()) {
Log.i(TAG, "Requesting permissions needed for this app.");
requestPermissions();
}
final List<String> cachedMessages = Utils.getCachedMessages(this);
if (cachedMessages != null) {
mNearbyMessagesList.addAll(cachedMessages);
}
final ListView nearbyMessagesListView = (ListView) findViewById(
R.id.nearby_messages_list_view);
mNearbyMessagesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
mNearbyMessagesList);
if (nearbyMessagesListView != null) {
nearbyMessagesListView.setAdapter(mNearbyMessagesArrayAdapter);
}
}
#Override
protected void onResume() {
super.onResume();
getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE)
.registerOnSharedPreferenceChangeListener(this);
if (havePermissions()) {
buildGoogleApiClient();
}
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != PERMISSIONS_REQUEST_CODE) {
return;
}
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
if (shouldShowRequestPermissionRationale(permission)) {
Log.i(TAG, "Permission denied without 'NEVER ASK AGAIN': " + permission);
showRequestPermissionsSnackbar();
} else {
Log.i(TAG, "Permission denied with 'NEVER ASK AGAIN': " + permission);
showLinkToSettingsSnackbar();
}
} else {
Log.i(TAG, "Permission granted, building GoogleApiClient");
buildGoogleApiClient();
}
}
}
private synchronized void buildGoogleApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Nearby.MESSAGES_API, new MessagesOptions.Builder()
.setPermissions(NearbyPermissions.BLE).build())
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.build();
}
}
#Override
protected void onPause() {
getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE)
.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (mContainer != null) {
Snackbar.make(mContainer, "Exception while connecting to Google Play services: " +
connectionResult.getErrorMessage(),
Snackbar.LENGTH_INDEFINITE).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "Connection suspended. Error code: " + i);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "GoogleApiClient connected");
subscribe();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (TextUtils.equals(key, Utils.KEY_CACHED_MESSAGES)) {
mNearbyMessagesList.clear();
mNearbyMessagesList.addAll(Utils.getCachedMessages(this));
mNearbyMessagesArrayAdapter.notifyDataSetChanged();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_SUBSCRIBED, mSubscribed);
}
private boolean havePermissions() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_CODE);
}
/**
* Calls {#link Messages#subscribe(GoogleApiClient, MessageListener, SubscribeOptions)},
* using a {#link Strategy} for BLE scanning. Attaches a {#link ResultCallback} to monitor
* whether the call to {#code subscribe()} succeeded or failed.
*/
private void subscribe() {
// In this sample, we subscribe when the activity is launched, but not on device orientation
// change.
if (mSubscribed) {
Log.i(TAG, "Already subscribed.");
return;
}
SubscribeOptions options = new SubscribeOptions.Builder()
.setStrategy(Strategy.BLE_ONLY)
.build();
Nearby.Messages.subscribe(mGoogleApiClient, getPendingIntent(), options)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Subscribed successfully.");
startService(getBackgroundSubscribeServiceIntent());
} else {
Log.e(TAG, "Operation failed. Error: " +
NearbyMessagesStatusCodes.getStatusCodeString(
status.getStatusCode()));
}
}
});
}
private PendingIntent getPendingIntent() {
return PendingIntent.getService(this, 0,
getBackgroundSubscribeServiceIntent(), PendingIntent.FLAG_UPDATE_CURRENT);
}
private Intent getBackgroundSubscribeServiceIntent() {
return new Intent(this, BackgroundSubscribeIntentService.class);
}
/**
* Displays {#link Snackbar} instructing user to visit Settings to grant permissions required by
* this application.
*/
private void showLinkToSettingsSnackbar() {
if (mContainer == null) {
return;
}
Snackbar.make(mContainer,
R.string.permission_denied_explanation,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}).show();
}
/**
* Displays {#link Snackbar} with button for the user to re-initiate the permission workflow.
*/
private void showRequestPermissionsSnackbar() {
if (mContainer == null) {
return;
}
Snackbar.make(mContainer, R.string.permission_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_CODE);
}
}).show();
}
}
BackgroundSubscribeIntentService.java
public class BackgroundSubscribeIntentService extends IntentService {
private static final String TAG = "BackSubIntentService";
private static final int MESSAGES_NOTIFICATION_ID = 1;
private static final int NUM_MESSAGES_IN_NOTIFICATION = 5;
public BackgroundSubscribeIntentService() {
super("BackgroundSubscribeIntentService");
}
#Override
public void onCreate() {
super.onCreate();
updateNotification();
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Nearby.Messages.handleIntent(intent, new MessageListener() {
#Override
public void onFound(Message message) {
Utils.saveFoundMessage(getApplicationContext(), message);
updateNotification();
}
#Override
public void onLost(Message message) {
Utils.removeLostMessage(getApplicationContext(), message);
updateNotification();
}
});
}
}
private void updateNotification() {
List<String> messages = Utils.getCachedMessages(getApplicationContext());
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
launchIntent.setAction(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String contentTitle = getContentTitle(messages);
String contentText = getContentText(messages);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.star_on)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText))
.setOngoing(true)
.setContentIntent(pi);
notificationManager.notify(MESSAGES_NOTIFICATION_ID, notificationBuilder.build());
}
private String getContentTitle(List<String> messages) {
switch (messages.size()) {
case 0:
return getResources().getString(R.string.scanning);
case 1:
return getResources().getString(R.string.one_message);
default:
return getResources().getString(R.string.many_messages, messages.size());
}
}
private String getContentText(List<String> messages) {
String newline = System.getProperty("line.separator");
if (messages.size() < NUM_MESSAGES_IN_NOTIFICATION) {
return TextUtils.join(newline, messages);
}
return TextUtils.join(newline, messages.subList(0, NUM_MESSAGES_IN_NOTIFICATION)) +
newline + "…";
}
}
Utils.java
public final class Utils {
static final String KEY_CACHED_MESSAGES = "cached-messages";
/**
* Fetches message strings stored in {#link SharedPreferences}.
*
* #param context The context.
* #return A list (possibly empty) containing message strings.
*/
static List<String> getCachedMessages(Context context) {
SharedPreferences sharedPrefs = getSharedPreferences(context);
String cachedMessagesJson = sharedPrefs.getString(KEY_CACHED_MESSAGES, "");
if (TextUtils.isEmpty(cachedMessagesJson)) {
return Collections.emptyList();
} else {
Type type = new TypeToken<List<String>>() {}.getType();
return new Gson().fromJson(cachedMessagesJson, type);
}
}
/**
* Saves a message string to {#link SharedPreferences}.
*
* #param context The context.
* #param message The Message whose payload (as string) is saved to SharedPreferences.
*/
static void saveFoundMessage(Context context, Message message) {
ArrayList<String> cachedMessages = new ArrayList<>(getCachedMessages(context));
Set<String> cachedMessagesSet = new HashSet<>(cachedMessages);
String messageString = new String(message.getContent());
if (!cachedMessagesSet.contains(messageString)) {
cachedMessages.add(0, new String(message.getContent()));
getSharedPreferences(context)
.edit()
.putString(KEY_CACHED_MESSAGES, new Gson().toJson(cachedMessages))
.apply();
}
}
/**
* Removes a message string from {#link SharedPreferences}.
* #param context The context.
* #param message The Message whose payload (as string) is removed from SharedPreferences.
*/
static void removeLostMessage(Context context, Message message) {
ArrayList<String> cachedMessages = new ArrayList<>(getCachedMessages(context));
cachedMessages.remove(new String(message.getContent()));
getSharedPreferences(context)
.edit()
.putString(KEY_CACHED_MESSAGES, new Gson().toJson(cachedMessages))
.apply();
}
/**
* Gets the SharedPReferences object that is used for persisting data in this application.
*
* #param context The context.
* #return The single {#link SharedPreferences} instance that can be used to retrieve and
modify values.
*/
static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(
context.getApplicationContext().getPackageName(),
Context.MODE_PRIVATE);
}
}
How can I get UUID and distance of the beacon and where I can apply the code. I have no prior experience of beacons.
The code shown in the question sets up a background subscription to BLE beacon Nearby messages that are delivered to a service by a PendingIntent: Nearby.Messages.subscribe(mGoogleApiClient, getPendingIntent(), options).setResultCallback(...);
Unfortunately, Google Nearby does not support delivering signal strength or distance estimates to background subscriptions. You can only do this with foreground subscriptions:
RSSI and Distance Callbacks
In addition to found and lost callbacks, a foreground subscription can update your MessageListener when Nearby has new information about the BLE signal associated with a message.
Note:
These extra callbacks are currently only delivered for BLE beacon messages (both attachments and beacon IDs).
These extra callbacks are not delivered to background (PendingIntent) subscriptions.
See https://developers.google.com/nearby/messages/android/advanced
If you want to get signal strength and distance estimates, with Google Nearby you must rewrite your code to use a foreground only subscription. The results will only be delivered if your app is in the foreground.
MessageListener messageListener = new MessageListener() {
#Override
public void onFound(final Message message) {
Log.i(TAG, "Found message: " + message);
}
#Override
public void onBleSignalChanged(final Message message, final BleSignal bleSignal) {
Log.i(TAG, "Message: " + message + " has new BLE signal information: " + bleSignal);
}
#Override
public void onDistanceChanged(final Message message, final Distance distance) {
Log.i(TAG, "Distance changed, message: " + message + ", new distance: " + distance);
}
#Override
public void onLost(final Message message) {
Log.i(TAG, "Lost message: " + message);
}
};
Nearby.getMessagesClient(this).subscribe(messageListener, options);
The link above shows a full example of how to do that.

Stop Timer on return to previous Activity

I have created a timer that starts timing on a handleClick() and continues timing throughout the app. When I return to the firstActivity I would like the timer to stop in the onResume(). however whenever I return to the firstActivity I get the following error below. How do I solve this?
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.warrenedy.julyfinal.TimeTracker2.isTracking()' on a null object reference
Code Below
#Override
protected void onResume() {
super.onResume();
prepareActivityTextsAndButtons();
prepareTimingButtons();
mTimeTracker2.stopTracker();
Toast.makeText(this, "Onresume call", Toast.LENGTH_SHORT).show();
}
public void handleClick(View v) {
if (DBG) Log.d(LOG_TAG, "handleClick()..");
if (!mServiceBound) return;
switch (v.getId()) {
case R.id.button_activity_start_stop:
onActivityButtonClick(v);
break;
}
}
private void onActivityButtonClick(View v) {
if (DBG)
Log.d(LOG_TAG, "onMeditateButtonClick().. tracking " + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (mTimeTracker2.isTracking()) {
if (mCurrentTrackingActivity == null) return;
if (button == mButtonActivityTimers[mCurrentTrackingActivity.ordinal()]) {
mTimeTracker2.stopTracker();
Utils2.playStopAudio(getApplicationContext());
// button.setText(R.string.str_start);
mCurrentTime.setText(Utils2.secToString(0));
button.setChecked(false);
}
}
}
Code Continued
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) Log.d(LOG_TAG, "onCreate()..");
setContentView(R.layout.activity_meditation_tracker);
getSupportActionBar().hide();
mContext = getApplicationContext();
mSharedpreferences = getSharedPreferences(Utils.MyPREFERENCES, Context.MODE_PRIVATE);
exercise_star = sharedpreferences.getInt("exercise_star", 0);
meditation_star = sharedpreferences.getInt("meditation_star", 0);
study_star = sharedpreferences.getInt("study_star", 0);
isAlarmSet = sharedpreferences.getBoolean("isAlarmSet", false);
/* Retrieve a PendingIntent that will perform a broadcast */
mActivity = MeditationTrackerActivity.this;
mButtonSavePoints = (Button) findViewById(R.id.btn_save_points);
mButtonRestorePoints = (Button) findViewById(R.id.btn_restore_points);
btnHelpBut = (Button) findViewById(R.id.btnHelp);
ACTIVITY_NAMES = getResources().getStringArray(R.array.activity_names);
mCurrentTime = (TextView) findViewById(R.id.tv_current_time);
mCurrentTime.setText(Utils2.secToString(0));
if (!isAlarmSet) {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAlarmSet", true);
ed.commit();
startAlarmService();
}
isAuthenticated = sharedpreferences.getBoolean("isAuth", true);
if (Build.VERSION.SDK_INT < 23) {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
insertPermissionWrapper();
}
}
### StartAlarmService
public void startAlarmService() {
Intent alarmIntent = new Intent(MeditationTrackerActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MeditationTrackerActivity.this, 0, alarmIntent, 0);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 23); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 45); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(this, "Main Alarm Set", Toast.LENGTH_SHORT).show();
}
### CancelAlarm
public void cancelAlarmService() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
### StartService
private void startService() {
Intent serIntent = new Intent(this, TimeTrackingService2.class);
startService(serIntent);
bindService(serIntent, mServiceConnection, BIND_AUTO_CREATE);
}
### UpdateCurrentTime
private void updateCurrentTime() {
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mCurrentTime.setText(sdf.format(date));
}
### ClientAuthenticationFromServer
private void clientAuthenticationFromServer() {
if (Utils2.getConnectivityStatus(mContext)) {
new Auth(mContext, mActivity).execute(Utils2.URL_VALIDATE_CLIENT);
} else {
Utils2.alertPopup(mContext, "You are not connected to internet.kindly connect with internet and try again.The internet is needed only first time for the authentication of client.After authentication no need of internet.", mActivity);
}
}
###Task Complete
#Override
public void onTaskComplete(boolean result) {
if (!result) {
Utils2.alertPopup(mContext, "You are not a valid client.Contact with the owner of the App.", mActivity);
return;
} else {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAuth", true);
ed.commit();
startService();
}
}
### OnStart
#Override
protected void onStart() {
super.onStart();
// updateCurrentTime();
// IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
// registerReceiver(mTimeTickReceiver, filter);
}
###OnStop
#Override
protected void onStop() {
super.onStop();
// unregisterReceiver(mTimeTickReceiver);
}
### onDestroy
#Override
protected void onDestroy() {
super.onDestroy();
if (mServiceBound) {
unbindService(mServiceConnection);
}
}
### onTimeButtonClick
private void onTimeButtonClick(View v) {
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. tracking" + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. checked ? " + button.isChecked());
if (mTimeTracker2.isTracking()) {
showStopToast();
Utils2.playStopAudio(getApplicationContext());
button.setChecked(false);
return;
} else {
Utils2.playStartAudio(getApplicationContext());
if (button.isChecked()) {
if (mCurrentCheckedButton != null) mCurrentCheckedButton.setChecked(false);
int time = (Integer) v.getTag();
mCountDownSecs = time;
mCurrentCheckedButton = button;
} else {
mCountDownSecs = 0;
mCurrentCheckedButton = null;
}
}
}
###ShowStopToast
private void showStopToast() {
Toast.makeText(this, "Please stop running activity..", Toast.LENGTH_SHORT).show();
}
### onTimerProgress
#Override
public void onTimerProgress(int sec, ACTIVITIES activity) {
if (mCurrentTrackingActivity == null) {
mCurrentTrackingActivity = activity;
}
mCurrentTime.setText(Utils2.secToString(sec));
if (activity == ACTIVITIES.STUDY) {
if (sec == 3600) {
mTimeTracker2.stopTracker();
}
}
}
### onTimerFinish
#Override
public void onTimerFinish(int end, ACTIVITIES activity) {
mCurrentTime.setText(Utils2.secToString(end));
mButtonActivityTimers[activity.ordinal()].setChecked(false);
mCurrentTrackingActivity = null;
Utils2.playStopAudio(getApplicationContext());
}
private void prepareActivityTextsAndButtons() {
for (int i = 0; i < ACTIVITY_COUNT; i++) {
View parent = findViewById(ACTIVITY_LAYOUT_IDS[i]);
mTextActivityNames[i] = (TextView) parent.findViewById(R.id.tv_activity_name);
mTextActivityNames[i].setText(ACTIVITY_NAMES[i]);
//mTextActivityTimers[i] = (TextView) parent.findViewById(R.id.tv_timer_progress);
mRatingBars[i] = (RatingBar) parent.findViewById(R.id.ratingBar);
mButtonActivityTimers[i] = (ToggleButton) parent.findViewById(R.id.button_activity_start_stop);
mButtonActivityTimers[i].setText(null);
mButtonActivityTimers[i].setTextOn(null);
mButtonActivityTimers[i].setTextOff(null);
mButtonActivityTimers[i].setTag(ACTIVITIES.values()[i]);
}
}
private void prepareTimingButtons() {
mTimingButtons = new ToggleButton[7];
mTimingButtons[0] = (ToggleButton) findViewById(R.id.button_timer_0);
addTextToTimingButtons(5, mTimingButtons[0]);
}
private void addTextToTimingButtons(int min, Button button) {
// button.setText(min + " " + getString(R.string.str_min));
button.setTag(min * 60);
}
public void onCustomTimeStarted(int secs) {
if (DBG) Log.d(LOG_TAG, "onCustomTimeStarted : secs " + secs);
if (mTimeTracker2.isTracking()) {
showStopToast();
} else {
int oneday = 24 * 3600;
if (secs > oneday) {
Toast.makeText(this, "Adjusted to 24 hrs", Toast.LENGTH_SHORT).show();
secs = oneday;
} else if (secs < 60) {
Toast.makeText(this, "Should be at least a minute.", Toast.LENGTH_SHORT).show();
return;
}
mTimingButtons[6].setChecked(true);
mTimingButtons[6].setTag(secs);
onTimeButtonClick(mTimingButtons[6]);
//mTimeTracker2.startTracker(secs, this);
//mButtonMeditate.setText(R.string.meditate_stop);
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void insertPermissionWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add("READ_PHONE_STATE");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
return;
} else {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
}
// insertDummyContact();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.app.AlertDialog.Builder(MeditationTrackerActivity.this)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
) {
// All Permissions Granted
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
// Permission Denied
Toast.makeText(MeditationTrackerActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void setBootReceiverEnabled(int componentEnabledState) {
ComponentName componentName = new ComponentName(this, DeviceBootReceiver.class);
PackageManager packageManager = getPackageManager();
packageManager.setComponentEnabledSetting(componentName,
componentEnabledState,
PackageManager.DONT_KILL_APP);
};
TimeTracker2.class
public class TimeTracker2 {
private static final int MSG_TRACKER_STOPPED = 1;
private static final int MSG_TRACKER_PROGRESS_UPDATE = 2;
private Context mContext;
private boolean mIsTrackingInProgress;
private TrackerServiceCallback mServiceCallback;
private TimerProgressCallback2 mProgressCallback;
private Timer mTimer = new Timer();
private TimerHandler mTimerHandler = new TimerHandler();
private TimerTask mIncrementTask, mDecrementTask;
private int mCounter;
private int mMaxCounter;
private MeditationTrackerActivity.ACTIVITIES mCurrentTrackingActivity;
private class IncrementTask extends TimerTask {
IncrementTask() {
mCounter = 0;
}
#Override
public void run() {
mCounter++;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
private class DecrementTask extends TimerTask {
DecrementTask(int sec) {
mCounter = sec;
}
#Override
public void run() {
if (mCounter == 0) {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_PIP, 500);
cancel();
mTimerHandler.sendEmptyMessage(MSG_TRACKER_STOPPED);
return;
}
mCounter --;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
public interface TimerProgressCallback2 {
void onTimerProgress(int sec, MeditationTrackerActivity.ACTIVITIES activity);
void onTimerFinish(int end, MeditationTrackerActivity.ACTIVITIES activity);
}
public TimeTracker2(Context context, TrackerServiceCallback serviceCallback) {
mContext = context;
mServiceCallback = serviceCallback;
}
public void startTracker(int time_secs, TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = time_secs;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mDecrementTask = new DecrementTask(time_secs);
mTimer.scheduleAtFixedRate(mDecrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void startTracker(TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = 0;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mIncrementTask = new IncrementTask();
mTimer.scheduleAtFixedRate(mIncrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void setTimerProgressCallback(TimerProgressCallback2 callback) {
if (!mIsTrackingInProgress) return;
mProgressCallback = callback;
}
public void removeTimerProgressCallback() {
mProgressCallback = null;
}
public void stopTracker() {
if (!mIsTrackingInProgress) {
Log.i(LOG_TAG, "stopTracker().. Tracker NOT started!!");
return;
}
mIsTrackingInProgress = false;
mServiceCallback.onTrackerStarted(false);
if (mProgressCallback != null) mProgressCallback.onTimerFinish(mCounter, mCurrentTrackingActivity);
mProgressCallback = null;
if (mIncrementTask != null) mIncrementTask.cancel();
if (mDecrementTask != null) mDecrementTask.cancel();
updateDb();
mCurrentTrackingActivity = null;
}
public boolean isTracking() {
return mIsTrackingInProgress;
}
public MeditationTrackerActivity.ACTIVITIES getCurrentTrackingActivity() {
return mCurrentTrackingActivity;
}
private class TimerHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if (DBG) Log.d(LOG_TAG, "handleMessage()..");
switch (msg.what) {
case MSG_TRACKER_PROGRESS_UPDATE:
if (mProgressCallback != null) mProgressCallback.onTimerProgress(mCounter, mCurrentTrackingActivity);
break;
case MSG_TRACKER_STOPPED:
default:
stopTracker();
break;
}
}
}
private void updateDb() {
final int secs = mMaxCounter > 0 ? mMaxCounter - mCounter : mCounter;
final MeditationTrackerActivity.ACTIVITIES activity = mCurrentTrackingActivity;
AsyncTask.execute(new Runnable() {
#Override
public void run() {
TrackerDb3.insertOrUpdateMeditation(mContext, secs, activity);
}
});
}
}

How to save state of a progressbar when app is killed?

I am building a simple downloader app, with a pause/resume button. When I click on pause button and kill the app the download progress isn't shown anymore, after I open the app again. I want to save the download progress state even if the app is killed. Can anyone help me with this? I'm building the app using download manager pro library from github.
here's the code:
Activity Class:
public class MainActivity extends AppCompatActivity {
String[] permissions = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 100;
EditText edt_url;
Button btn_download;
TextView fileNametv, ProgressbarTv;
private MyDownloadService mService;
ProgressBar progressBar;
String filename, url;
/* UrlFileNameListener listener;*/
Integer progress;
MyReceiver receiver;
public static MainActivity instance;
/* RecyclerView recyclerView;
List<Model> downloadList;
LinearLayoutManager manager;
DownloadAdapter adapter;
// ImageView pausebtn;
int position;*/
File myDirectory;
Boolean mBound = false;
Button pause_btn;
int tasktoken;
/* Model model;
Parcelable mListState;
private final String KEY_RECYCLER_STATE = "recycler_state";
private final String KEY_LIST_STATE = "list_state";*/
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mBound = true;
MyDownloadService.LocalBinder localBinder = (MyDownloadService.LocalBinder) iBinder;
mService = localBinder.getService();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* if(savedInstanceState!=null){
mListState = savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
downloadList =savedInstanceState.getParcelableArrayList(KEY_LIST_STATE);
} */
setContentView(R.layout.activity_main);
edt_url = findViewById(R.id.edt_url);
btn_download = findViewById(R.id.btn_download);
pause_btn = findViewById(R.id.pause_resume);
/*recyclerView = findViewById(R.id.recycler_view);
downloadList = new ArrayList<>();
manager = new LinearLayoutManager(this);
adapter = new DownloadAdapter(downloadList, this);
recyclerView.setLayoutManager(manager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
manager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);*/
fileNametv = findViewById(R.id.download_file_name);
ProgressbarTv = findViewById(R.id.progress_tv);
progressBar = findViewById(R.id.download_progress);
// pausebtn = findViewById(R.id.pause_resume);
instance = this;
/* if (progress!= null && filename != null) {
savedInstanceState.putInt("progress", progress);
savedInstanceState.putString("filename",filename);
// savedInstanceState.putString("filename", model.getFileName());
// savedInstanceState.putParcelable("list",mListState);
}*/
receiver = new MyReceiver();
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDownloadProcess();
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mService.pauseDownload(tasktoken);
}
});
LocalBroadcastManager.getInstance(this)
.registerReceiver(receiver,
new IntentFilter("download"));
if (checkAndRequestPermissions()) {
myDirectory = new File(Environment.getExternalStorageDirectory() + "/" + "RITSDownloads2");
if (!myDirectory.exists()) {
myDirectory.mkdir();
}
}
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this,MyDownloadService.class);
bindService(intent,mServiceConnection,Context.BIND_AUTO_CREATE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("progress", progress);
outState.putString("filename",filename);
/* mListState = manager.onSaveInstanceState();
outState.putParcelable(KEY_RECYCLER_STATE,mListState);
outState.putParcelableArrayList(KEY_LIST_STATE, (ArrayList<? extends Parcelable>) adapter.getDownloadList());*/
}
#Override
protected void onPause() {
super.onPause();
//mListState = manager.onSaveInstanceState();
}
#Override
protected void onResume() {
super.onResume();
// manager.onRestoreInstanceState(mListState);
}
#Override
public void onBackPressed() {
progress = progressBar.getProgress();
super.onBackPressed();
}
/* #Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
manager.onRestoreInstanceState(mListState);
savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
savedInstanceState.getParcelableArrayList(KEY_LIST_STATE);
}
*/
private void getDownloadProcess() {
url = edt_url.getText().toString();
filename = URLUtil.guessFileName(url, null, null);
//listener.setUrl(url,filename);
edt_url.setText("");
/* model = new Model();
model.setFileName(filename);
downloadList.add(model);
adapter.notifyDataSetChanged();*/
fileNametv.setText(filename);
Intent intent = new Intent(MainActivity.this, MyDownloadService.class);
intent.putExtra("filename", filename);
intent.putExtra("url", url);
intent.setAction(DownloadActions.ACTION.Download_ACTION);
startService(intent);
}
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
progress = intent.getIntExtra("progress", 1);
ReportStructure reportStructure = MyDownloadService.downloadManagerPro.singleDownloadStatus(intent.getIntExtra("tasktoken",1));
tasktoken = intent.getIntExtra("tasktoken",1);
// model.setProgress(progress);
/*int position = downloadList.indexOf(model);
DownloadAdapter.DownloadHolder holder = getDownloadHolder(position);
holder.progressBar.setProgress(progress);*/
progressBar.setProgress(progress);
}
}
/* public DownloadAdapter.DownloadHolder getDownloadHolder(int position) {
return (DownloadAdapter.DownloadHolder) recyclerView.findViewHolderForLayoutPosition(position);
}
*/
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getInt("progress");
savedInstanceState.getString("filename");
/* Log.d("savedInstancestate",savedInstanceState.toString());
//savedInstanceState.getInt("position");
if(savedInstanceState!=null){
List<Model> downloadList = savedInstanceState.getParcelableArrayList(KEY_LIST_STATE);
adapter = new DownloadAdapter(downloadList,this);
}
*/
}
private boolean checkAndRequestPermissions() {
if (ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, permissions[1]) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permissions, REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], #NonNull int[] grantResults) {
String TAG = "LOG_PERMISSION";
Log.d(TAG, "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
perms.put(this.permissions[0], PackageManager.PERMISSION_GRANTED);
perms.put(this.permissions[1], PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(this.permissions[0]) == PackageManager.PERMISSION_GRANTED
&& perms.get(this.permissions[1]) == PackageManager.PERMISSION_GRANTED
) {
Log.d(TAG, "Phone state and storage permissions granted");
// process the normal flow
//else any one or both the permissions are not granted
//TODO Do your stuff here after permissions granted
} else {
Log.d(TAG, "Some permissions are not granted ask again ");
//permissions is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permissions
// //shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, this.permissions[0]) ||
ActivityCompat.shouldShowRequestPermissionRationale(this, this.permissions[1])) {
showDialogOK("Phone state and storage permissions required for this app",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
}
});
}
//permissions is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
//proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
}
Service Class:
public class MyDownloadService extends Service implements DownloadManagerListener {
private static final String LOG_TAG = "tag";
public static DownloadManagerPro downloadManagerPro;
File myDirectory;
int taskToken;
String name;
Intent notificationIntent;
Notification notification;
PendingIntent pendingIntent;
private IBinder binder = new LocalBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(DownloadActions.ACTION.Download_ACTION)) {
Log.d(LOG_TAG, "Received Start Foreground Intent");
}
name = intent.getStringExtra("filename");
final String url = intent.getStringExtra("url");
Log.d(LOG_TAG, name);
Log.d(LOG_TAG, url);
downloadManagerPro = new DownloadManagerPro(this.getApplicationContext());
downloadManagerPro.init("RITSDownloads2/", 16, this);
myDirectory = new File(Environment.getExternalStorageDirectory() + "/" + "RITSDownloads2");
if (!myDirectory.exists()) {
myDirectory.mkdir();
}
taskToken = downloadManagerPro.addTask(name, url, 16, true, true);
Log.d(LOG_TAG, String.valueOf(taskToken));
try {
downloadManagerPro.startDownload(taskToken);
notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(DownloadActions.ACTION.Download_ACTION);
pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Downloading")
.setTicker("Rits Download")
.setContentText(name)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(DownloadActions.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
// stopForeground(true);
// stopSelf();
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void OnDownloadStarted(long taskId) {
Log.d(LOG_TAG, "DownloadStarted");
}
#Override
public void OnDownloadPaused(long taskId) {
}
#Override
public void onDownloadProcess(long taskId, double percent, long downloadedLength) {
final int progress = (int) percent;
final int taskToken = (int) taskId;
// int position = positions.get(taskToken);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Downloading")
.setTicker("Rits Download")
.setContentText(name)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setProgress(100, progress, false)
.build();
startForeground(DownloadActions.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("progress", progress);
intent.setAction("download");
intent.putExtra("tasktoken",taskToken);
ReportStructure structure = downloadManagerPro.singleDownloadStatus(taskToken);
String name =structure.name;
intent.putExtra("name",name);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
#Override
public void OnDownloadFinished(long taskId) {
}
#Override
public void OnDownloadRebuildStart(long taskId) {
}
#Override
public void OnDownloadRebuildFinished(long taskId) {
}
public void pauseDownload(int taskToken){
ReportStructure reportStructure = downloadManagerPro.singleDownloadStatus(taskToken);
if(reportStructure.state == TaskStates.DOWNLOADING){
downloadManagerPro.pauseDownload(taskToken);
} else if(reportStructure.state == TaskStates.PAUSED){
try {
downloadManagerPro.startDownload(taskToken);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void OnDownloadCompleted(long taskId) {
Log.d(LOG_TAG, "Download Complete");
/* MainActivity.instance.pausebtn.post(new Runnable() {
#Override
public void run() {
MainActivity.instance.pausebtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_done));
}
});*/
notification = new NotificationCompat.Builder(this)
.setContentTitle("Download Complete")
.setTicker("Rits Download")
.setContentText(name)
.setSmallIcon(R.drawable.ic_action_done)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.build();
startForeground(DownloadActions.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
#Override
public void connectionLost(long taskId) {
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/* Intent restartService = new Intent(getApplicationContext(),this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartService, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);*/
}
public class LocalBinder extends Binder{
public MyDownloadService getService(){
return MyDownloadService.this;
}
}
}
I don't know how you want to save the state but I do know that an activity has a onStop() method that you can override.
The onStop() method runs when the app is killed so I would imagine you would want to do your "saving" in this method.
As for saving something I believe you would want to use the SharedPreferences class. You can find more information about that here.
You can find the lifecycle of an activity here
hope this helps
Save the progress on SharedPreferences onDestroy() and retrieve it from there when activity is created.
Cache:
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences sharedPreferences = getSharedPreferences("space_name", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("progress", progress).apply();
}
And retrieve:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = getSharedPreferences("space_name", MODE_PRIVATE);
progress = sharedPreferences.getInt("progress", 0); // 0 default value in case is empty
}

HERE Map Turn By Turn Activate

i'm developing turn by turn based navigation application on android. I'm using HERE maps sdk for android. I can't switch to navigation driver mode for turn by turn navigation. How can i switch normal map to turn by turn mode.
Note: I changed to map scheme mode
map.setMapScheme(Map.Scheme.CARNAV_TRAFFIC_DAY);
public class BasicMapActivity extends Activity {
// permissions request code
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private PositioningManager posManager;
private MapRoute mapRoute;
private Route route;
private GeoPosition myPosition;
/**
* Permissions that need to be explicitly requested from end user.
*/
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE };
// map embedded in the map fragment
private Map map = null;
// map fragment embedded in this activity
private MapFragment mapFragment = null;
private PositioningManager.OnPositionChangedListener positionListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
Log.v("HERE MAP",geoPosition.getCoordinate().toString());
myPosition = geoPosition;
map.setCenter(geoPosition.getCoordinate(),
Map.Animation.BOW);
// Set the zoom level to the average between min and max
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
}
#Override
protected void onResume() {
super.onResume();
if (posManager != null) {
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}
}
#Override
protected void onPause() {
super.onPause();
if (posManager != null) {
posManager.stop();
}
}
public void onDestroy() {
if (posManager != null) {
// Cleanup
posManager.removeListener(
positionListener);
}
map = null;
super.onDestroy();
}
private void initialize() {
setContentView(R.layout.activity_main);
findViewById(R.id.btnDrawRoute).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawRoute();
}
});
findViewById(R.id.btnChangeMap).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setNavigationManager();
NavigationManager.Error error = NavigationManager.getInstance().startNavigation(route);
if(error.equals(NavigationManager.Error.NONE)){
map.setExtrudedBuildingsVisible(false);
}
}
});
// Search for the map fragment to finish setup by calling init().
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center to the Vancouver region (no animation)
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
map.setCartoMarkersVisible(true);
map.setLandmarksVisible(true);
map.setMapScheme(Map.Scheme.CARNAV_DAY);
map.setTrafficInfoVisible(true);
map.setExtrudedBuildingsVisible(true);
map.setStreetLevelCoverageVisible(true);
mapFragment.getPositionIndicator().setVisible(true);
try {
posManager = PositioningManager.getInstance();
posManager.addListener(new WeakReference<>(positionListener));
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}catch (Exception ex){
Log.v("Error",ex.getMessage());
}
} else {
System.out.println("ERROR: Cannot initialize Map Fragment");
}
}
});
}
private void setNavigationManager() {
NavigationManager.getInstance().setMap(map);
NavigationManager.getInstance().setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
NavigationManager.getInstance().setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
NavigationManager.getInstance().setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
NavigationManager.getInstance().setDistanceUnit(NavigationManager.UnitSystem.METRIC);
ArrayList<NavigationManager.NaturalGuidanceMode> arrayList = new ArrayList<NavigationManager.NaturalGuidanceMode>();
arrayList.add(NavigationManager.NaturalGuidanceMode.JUNCTION);
arrayList.add(NavigationManager.NaturalGuidanceMode.STOP_SIGN);
arrayList.add(NavigationManager.NaturalGuidanceMode.TRAFFIC_LIGHT);
EnumSet<NavigationManager.NaturalGuidanceMode> enumSet = EnumSet.copyOf(arrayList);
NavigationManager.getInstance().setNaturalGuidanceMode(enumSet);
setVoice();
ArrayList<NavigationManager.AudioEvent> audioEvents = new ArrayList<>();
audioEvents.add(NavigationManager.AudioEvent.ROUTE);
audioEvents.add(NavigationManager.AudioEvent.GPS);
NavigationManager.getInstance().setEnabledAudioEvents(EnumSet.copyOf(audioEvents));
NavigationManager.getInstance().addNewInstructionEventListener(new WeakReference<NavigationManager.NewInstructionEventListener>(new NavigationManager.NewInstructionEventListener() {
#Override
public void onNewInstructionEvent() {
super.onNewInstructionEvent();
Maneuver maneuver = NavigationManager.getInstance().getNextManeuver();
Log.v("Manevra",maneuver.getNextRoadName() + " "+maneuver.getRoadName());
maneuver.getRoadName();
}
}));
NavigationManager.getInstance().addManeuverEventListener(new WeakReference<NavigationManager.ManeuverEventListener>(new NavigationManager.ManeuverEventListener() {
#Override
public void onManeuverEvent() {
super.onManeuverEvent();
}
}));
NavigationManager.getInstance().addPositionListener(new WeakReference<NavigationManager.PositionListener>(new NavigationManager.PositionListener() {
#Override
public void onPositionUpdated(GeoPosition geoPosition) {
super.onPositionUpdated(geoPosition);
geoPosition.getCoordinate();
geoPosition.getHeading();
geoPosition.getSpeed();
// also remaining time and distance can be
// fetched from navigation manager
NavigationManager.getInstance().getTta(Route.TrafficPenaltyMode.DISABLED, true);
NavigationManager.getInstance().getDestinationDistance();
}
}));
}
private void setVoice() {
// Get the list of voice packages from the voice catalog list
List<VoicePackage> voicePackages = VoiceCatalog.getInstance().getCatalogList();
long id = -1;
// select
for (VoicePackage vPackage : voicePackages) {
if (vPackage.getMarcCode().compareToIgnoreCase("eng") == 0) {
if (vPackage.isTts()) {
id = vPackage.getId();
break;
}
}
}
if(id>-1)
NavigationManager.getInstance().setVoiceSkin(VoiceCatalog.getInstance().getLocalVoiceSkin(id));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Checks the dynamically controlled permissions and requests missing permissions from end user.
*/
protected void checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
initialize();
break;
}
}
private void drawRoute(){
CoreRouter router = new CoreRouter();
GeoCoordinate gebzeCoord = new GeoCoordinate(40.9047617,29.4065243);
GeoCoordinate maslakCoord = new GeoCoordinate(41.1066509,29.0204711);
// Create the RoutePlan and add two waypoints
RoutePlan routePlan = new RoutePlan();
routePlan.addWaypoint(new RouteWaypoint(myPosition.getCoordinate()));
routePlan.addWaypoint(new RouteWaypoint(maslakCoord));
// Create the RouteOptions and set its transport mode & routing type
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.CAR);
routeOptions.setRouteType(RouteOptions.Type.FASTEST);
routePlan.setRouteOptions(routeOptions);
// Calculate the route
router.calculateRoute(routePlan, new RouteListener());
TrafficUpdater trafficUpdater = TrafficUpdater.getInstance();
trafficUpdater.request(route, new TrafficUpdater.Listener() {
#Override
public void onStatusChanged(TrafficUpdater.RequestState requestState) {
}
});
}
private class RouteListener implements CoreRouter.Listener {
// Method defined in Listener
public void onProgress(int percentage) {
// Display a message indicating calculation progress
}
// Method defined in Listener
public void onCalculateRouteFinished(List<RouteResult> routeResult, RoutingError error) {
// If the route was calculated successfully
if (error == RoutingError.NONE) {
// Render the route on the map
mapRoute = new MapRoute(routeResult.get(0).getRoute());
route = routeResult.get(0).getRoute();
map.addMapObject(mapRoute);
}
else {
// Display a message indicating route calculation failure
}
}
}
}
Declare NavigationManager's object as a global object.
private NavigationManager m_navigationManager;
after that initialize it in your setNavigationManager() method.
m_navigationManager = NavigationManager.getInstance();
m_navigationManager.setMap(map);
// try to change current MapUpdateMode to POSITION_ANIMATION
m_navigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.POSITION_ANIMATION);
m_navigationManager.setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
m_navigationManager.setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
// set all other method on this object.
m_navigationManager.......
After you have to start navigation like this
NavigationManager.Error error = m_navigationManager.startNavigation(route);
if (error != NavigationManager.Error.NONE) {
m_navigationManager.setMap(null);
}
//set Tilt to at some angle that you can look in 3d mode
map.setTilt(70f, com.here.android.mpa.mapping.Map.Animation.NONE);
map.setZoomLevel(18);

SCAN_RESULTS_AVAILABLE_ACTION: BroadcastReceiver#onReceive not called on Android 7.0

I'm developing an app for Android in which I have to scan the available WiFi LANs.
I'm testing the app and it works on devices with Android from 4.4 to 6.x, but on Nougat (in fact I've tested on 2 different devices, a Huawei and a HTC, with Android 7) the onReceive of my BroadcastReceiver is never called.
If I try with WIFI_STATE_CHANGED_ACTION I'm able to receive this action even on Android 7.
I've checked the changes' documentation in Nougat, but I found nothing about this. Why doesn't it work on Nougat? What do I have to add/change?
Here is a stripped down version of my app.
In AndroidManifest.xml I've added:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ListView _listSSID;
private ArrayAdapter<String> _adapter;
private WiFiConnection _wifiConnection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
_wifiConnection = new WiFiConnection(this);
_adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, _wifiConnection.getBestSSIDs());
_listSSID = (ListView) findViewById(R.id.listSSID);
_listSSID.setAdapter(_adapter);
_listSSID.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ssid = _adapter.getItem(position);
Log.d("OnClick", ssid);
}
});
startScan();
}
#Override
protected void onStop() {
super.onStop();
_wifiConnection.stopScan();
unregisterReceiver(_wifiScanReceiver);
}
void startScan() {
checkPermission(this);
registerReceiver(_wifiScanReceiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Thread t = new Thread(_wifiConnection.getWifiScanner());
t.start();
}
private final BroadcastReceiver _wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
if (_wifiConnection != null && _wifiConnection.isWifiEnabled()) {
_wifiConnection.updateScanData("No WLANs found");
}
_adapter.notifyDataSetChanged();
}
}
};
static final int MY_PERMISSIONS_REQUEST = 1042;
private static final String PERMISSIONS_TAG = "PERMISSION";
#TargetApi(Build.VERSION_CODES.M)
public static boolean checkPermission(Activity activity) {
boolean permission = true;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
permission = activity.checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "ACCESS_WIFI_STATE: " + permission);
permission = activity.checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "CHANGE_WIFI_STATE: " + permission);
permission = activity.checkSelfPermission(Manifest.permission.CHANGE_WIFI_MULTICAST_STATE) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "CHANGE_WIFI_MULTICAST_STATE: " + permission);
List<String> requiringList = new ArrayList<>();
permission = activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "WRITE_EXTERNAL_STORAGE: " + permission);
if (!permission) {
requiringList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
permission = activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "ACCESS_COARSE_LOCATION: " + permission);
if (!permission) {
requiringList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (requiringList.size() > 0) {
String[] stringArray = requiringList.toArray(new String[0]);
activity.requestPermissions(stringArray, MY_PERMISSIONS_REQUEST);
}
}
return permission;
}
}
WiFiConnection.java
class WiFiConnection
{
private static final int SCAN_INTERVAL = 1200;
final private List<String> _bestSSIDs = new ArrayList<>();
private WifiManager _wifiManager;
private final WiFiScanner _startScan = new WiFiScanner();
WiFiConnection(Activity activity) {
_wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
List<String> getBestSSIDs() {return _bestSSIDs; }
WiFiScanner getWifiScanner() { return _startScan; }
void stopScan() { _startScan.stop(); }
boolean isWifiEnabled() { return _wifiManager.isWifiEnabled(); }
void updateScanData(final String noLansMsg) {
if ((_wifiManager != null && _wifiManager.isWifiEnabled())) {
List<ScanResult> scanResults = _wifiManager.getScanResults();
Log.d("WiFi", "found nets: " + scanResults.size());
// my sorting code
}
}
private class WiFiScanner implements Runnable
{
private boolean _stop = false;
public void stop() {_stop = true;}
#Override
public void run() {
while (!_stop) {
_wifiManager.startScan();
try {
Thread.sleep(SCAN_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
#TargetApi(Build.VERSION_CODES.M) remove this it will execute for Android M only other wise write greater or equal M version code.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
// Do something for M and above versions
} else{
It seems it is necessary to turn on GPS to receive SCAN_RESULTS_AVAILABLE_ACTION on Android 7.0.

Categories

Resources