How can I use sharedPreferences on spinner in the next code, I tried to do it like this line:
txtWebsite.setText(sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite));
and I tried this:
spinner.setSelection(sharedPreferences.getString("userName", ""));
but it does not work sharepreferences. this is an activitymain code, this code send data for update MySQL BD.
package com.websmithing.gpstracker;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.util.UUID;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class GpsTrackerActivity extends AppCompatActivity {
public static final String EmployeeNamearray = "EmpName";
public static final String EmployeeName = "EmpName";
public static final String EmployeeMailid = "EmpMailid";
public static final String JSON_ARRAY = "result";
private JSONArray result;
Spinner spinner;
String EmpName;
private ArrayList<String> arrayList;
TextView employeename,mailid;
private static final String TAG = "GpsTrackerActivity";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private EditText txtUserName;
private Spinner spnrEmployee;
private EditText txtWebsite;
private Button trackingButton;
private boolean currentlyTracking;
private RadioGroup intervalRadioGroup;
private int intervalInMinutes = 1;
private AlarmManager alarmManager;
private Intent gpsTrackerIntent;
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_tracker);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
defaultUploadWebsite = getString(R.string.default_upload_website);
txtWebsite = (EditText)findViewById(R.id.txtWebsite);
txtUserName = (EditText)findViewById(R.id.txtUserName);
spnrEmployee = (Spinner)findViewById(R.id.spnrEmployee);
intervalRadioGroup = (RadioGroup)findViewById(R.id.intervalRadioGroup);
trackingButton = (Button)findViewById(R.id.trackingButton);
txtUserName.setImeOptions(EditorInfo.IME_ACTION_DONE);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
currentlyTracking = sharedPreferences.getBoolean("currentlyTracking", false);
boolean firstTimeLoadingApp = sharedPreferences.getBoolean("firstTimeLoadingApp", true);
if (firstTimeLoadingApp) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("firstTimeLoadingApp", false);
editor.putString("appID", UUID.randomUUID().toString());
editor.apply();
}
intervalRadioGroup.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
saveInterval();
}
});
trackingButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
trackLocation(view);
}
});
//SAAG
spinner= (Spinner) findViewById(R.id.spnrEmployee);
employeename= (TextView) findViewById(R.id.tvName);
mailid= (TextView) findViewById(R.id.tvmailid);
arrayList = new ArrayList<String>();
getdata();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
employeename.setText("Name: "+getemployeeName(position));
mailid.setText("Mail Id: "+getmailid(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
employeename.setText("");
mailid.setText("");
}
});
}
private void getdata() {
StringRequest stringRequest = new StringRequest("http://190.147.68.37/ejemplos/datos.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
empdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void empdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList.add(json.getString(EmployeeNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
// arrayList.add(0,"Select Employee");
spinner.setAdapter(new ArrayAdapter<String>(GpsTrackerActivity.this, android.R.layout.simple_spinner_dropdown_item, arrayList));
}
//Method to get student name of a particular position
private String getemployeeName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString( EmployeeName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getmailid(int position){
String mailid="";
try {
JSONObject json = result.getJSONObject(position);
mailid = json.getString( EmployeeMailid);
} catch (JSONException e) {
e.printStackTrace();
}
return mailid;
}
private void saveInterval() {
if (currentlyTracking) {
Toast.makeText(getApplicationContext(), R.string.user_needs_to_restart_tracking, Toast.LENGTH_LONG).show();
}
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (intervalRadioGroup.getCheckedRadioButtonId()) {
case R.id.i1:
editor.putInt("intervalInMinutes", 1);
break;
case R.id.i5:
editor.putInt("intervalInMinutes", 5);
break;
case R.id.i15:
editor.putInt("intervalInMinutes", 15);
break;
}
editor.apply();
}
private void startAlarmManager() {
Log.d(TAG, "startAlarmManager");
Context context = getBaseContext();
alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
gpsTrackerIntent = new Intent(context, GpsTrackerAlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, gpsTrackerIntent, 0);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
intervalInMinutes = sharedPreferences.getInt("intervalInMinutes", 1);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
intervalInMinutes * 60000, // 60000 = 1 minute
pendingIntent);
}
private void cancelAlarmManager() {
Log.d(TAG, "cancelAlarmManager");
Context context = getBaseContext();
Intent gpsTrackerIntent = new Intent(context, GpsTrackerAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, gpsTrackerIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
// called when trackingButton is tapped
protected void trackLocation(View v) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (!saveUserSettings()) {
return;
}
if (!checkIfGooglePlayEnabled()) {
return;
}
if (currentlyTracking) {
cancelAlarmManager();
currentlyTracking = false;
editor.putBoolean("currentlyTracking", false);
editor.putString("sessionID", "");
} else {
startAlarmManager();
currentlyTracking = true;
editor.putBoolean("currentlyTracking", true);
editor.putFloat("totalDistanceInMeters", 0f);
editor.putBoolean("firstTimeGettingPosition", true);
editor.putString("sessionID", UUID.randomUUID().toString());
}
editor.apply();
setTrackingButtonState();
}
private boolean saveUserSettings() {
if (textFieldsAreEmptyOrHaveSpaces()) {
return false;
}
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (intervalRadioGroup.getCheckedRadioButtonId()) {
case R.id.i1:
editor.putInt("intervalInMinutes", 1);
break;
case R.id.i5:
editor.putInt("intervalInMinutes", 5);
break;
case R.id.i15:
editor.putInt("intervalInMinutes", 15);
break;
}
//editor.putString("userName", txtUserName.getText().toString().trim());
editor.putString("userName", spnrEmployee.getSelectedItem().toString().trim());
editor.putString("defaultUploadWebsite", txtWebsite.getText().toString().trim());
editor.apply();
return true;
}
private boolean textFieldsAreEmptyOrHaveSpaces() {
String tempUserName = txtUserName.getText().toString().trim();
String tempWebsite = txtWebsite.getText().toString().trim();
if (tempWebsite.length() == 0 || hasSpaces(tempWebsite) || tempUserName.length() == 0 || hasSpaces(tempUserName)) {
Toast.makeText(this, R.string.textfields_empty_or_spaces, Toast.LENGTH_LONG).show();
return true;
}
return false;
}
private boolean hasSpaces(String str) {
return ((str.split(" ").length > 1) ? true : false);
}
private void displayUserSettings() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
intervalInMinutes = sharedPreferences.getInt("intervalInMinutes", 1);
switch (intervalInMinutes) {
case 1:
intervalRadioGroup.check(R.id.i1);
break;
case 5:
intervalRadioGroup.check(R.id.i5);
break;
case 15:
intervalRadioGroup.check(R.id.i15);
break;
}
txtWebsite.setText(sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite));
//this line for modify and sharepreferences
spinner.setSelection(sharedPreferences.getString("userName", ""));
}
private boolean checkIfGooglePlayEnabled() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
} else {
Log.e(TAG, "unable to connect to google play services.");
Toast.makeText(getApplicationContext(), R.string.google_play_services_unavailable, Toast.LENGTH_LONG).show();
return false;
}
}
private void setTrackingButtonState() {
if (currentlyTracking) {
trackingButton.setBackgroundResource(R.drawable.green_tracking_button);
trackingButton.setTextColor(Color.BLACK);
trackingButton.setText(R.string.tracking_is_on);
} else {
trackingButton.setBackgroundResource(R.drawable.red_tracking_button);
trackingButton.setTextColor(Color.WHITE);
trackingButton.setText(R.string.tracking_is_off);
}
}
Save the current position of your spinner here:
private boolean saveUserSettings() {
if (textFieldsAreEmptyOrHaveSpaces()) {
return false;
}
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (intervalRadioGroup.getCheckedRadioButtonId()) {
case R.id.i1:
editor.putInt("intervalInMinutes", 1);
break;
case R.id.i5:
editor.putInt("intervalInMinutes", 5);
break;
case R.id.i15:
editor.putInt("intervalInMinutes", 15);
break;
}
//editor.putString("userName", txtUserName.getText().toString().trim());
editor.putString("userName", spnrEmployee.getSelectedItem().toString().trim());
editor.putString("defaultUploadWebsite", txtWebsite.getText().toString().trim());
editor.putInt("position", spnrEmployee.getSelectedItemPosition());
editor.apply();
return true;
}
Then, when you want to display your stored values, just use this :
private void displayUserSettings() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
intervalInMinutes = sharedPreferences.getInt("intervalInMinutes", 1);
switch (intervalInMinutes) {
case 1:
intervalRadioGroup.check(R.id.i1);
break;
case 5:
intervalRadioGroup.check(R.id.i5);
break;
case 15:
intervalRadioGroup.check(R.id.i15);
break;
}
txtWebsite.setText(sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite));
//this line for modify and sharepreferences
spinner.setSelection(sharedPreferences.getInt("position",0));
}
Don't forget, you should call this method : displayUserSettings , after you set the adapter data to your spinner
Related
Why is my activity unable to upload pictures taken by camera while it easily uploads the picture picked from the gallery?
The picture uploaded through the gallery is available on the server but the file(picture) taken through the camera is not found on the server after the API hit.
Opening the directory on the server gives 'File not found' error for the file uploaded via camera.
Here is my code:
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import static com.app.engage.Interfaces.Keys.userDetails.*;
import com.app.engage.Interfaces.ApiResponse;
import com.app.engage.Interfaces.NetworkConnectivityListener;
import com.app.engage.R;
import com.app.engage.Utilities.ConnectionDetector;
import com.app.engage.Utilities.GetServerData;
import com.app.engage.Utilities.ImageOnlyOptionsDialog;
import com.app.engage.Utilities.ProgressDialog;
import com.app.engage.Utilities.RoleSectDialog;
import com.app.engage.Utilities.RoundCorner;
import com.app.engage.Utilities.SharedPreference_Main;
import com.app.engage.Utilities.Utilities;
import com.bumptech.glide.Glide;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import com.app.engage.Interfaces.OnButtonClicked;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SignupActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, ApiResponse.Api_hit, View.OnClickListener {
private TextView toolbarText;
public static TextView selections;
private ProgressDialog progressDialog;
private String selected_role = null;
private String selectedRole = "", selectedOrgType = "";
public static String selectedNatPriArea = "";
private ArrayList<String> role_list, org_type, nat_pri_area;
private ApiResponse apiResponse;
private ImageView dp;
private Uri uriFilePath;
private int REQUEST_CODE_CAMERA = 1002;
private int REQUEST_PICK_IMAGE = 1003;
private AlertDialog.Builder builder;
private TextView upload_dp;
private AppCompatCheckBox stayLoggedIn;
private Spinner roleSpinner, organisationTypeSpinner;
private Button signUp;
private SharedPreference_Main sharedPreference_main;
private String mCurrentPhotoPath;
// private Utilities utilities;
private TextView select_nat_pri_area;
private ConnectionDetector receiver;
private EditText fullName, email, orgName, password, reEnterPassword;
private File file = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
getWindow().setBackgroundDrawableResource(R.drawable.blurred_background); //setting background here
android.support.v7.widget.Toolbar toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
role_list = new ArrayList<>(); //arraylist that will hold the roles coming from the server
org_type = new ArrayList<>();//arraylist that will hold the roles coming from the server
nat_pri_area = new ArrayList<>();
sharedPreference_main = new SharedPreference_Main(this);
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeAsUpIndicator(R.drawable.white_back_icon_for_toolbar);
toolbarText = findViewById(R.id.toolbarText);
select_nat_pri_area = findViewById(R.id.nat_pri_areaaa);
toolbarText.setText("Sign Up");
apiResponse = new ApiResponse(this);
roleSpinner = findViewById(R.id.select_role_spinner);
organisationTypeSpinner = findViewById(R.id.organisation_type_spinner);
fullName = findViewById(R.id.full_name_editText);
email = findViewById(R.id.email_editText_signUp);
password = findViewById(R.id.pass_edit_text);
reEnterPassword = findViewById(R.id.reEnterPword);
orgName = findViewById(R.id.org_edit_text);
selections = findViewById(R.id.selectionss);
signUp = findViewById(R.id.signUp_Button);
dp = findViewById(R.id.dp);
progressDialog = new ProgressDialog(this);
select_nat_pri_area.setOnClickListener(this);
upload_dp = findViewById(R.id.upload_dp);
dp.setOnClickListener(this);
selections.setOnClickListener(this);
upload_dp.setOnClickListener(this);
// utilities = new Utilities(this);
receiver = new ConnectionDetector(new NetworkConnectivityListener() {
#Override
public void onNetworkConnected() //if network connection is available
{
if (role_list.size() <= 0 || org_type.size() <= 0 || nat_pri_area.size() <= 0) {
getData();
}
}
#Override
public void onNetworkDisconnected() {
displayAlert();
}
}, this);
// sharedPreference_main = SharedPreference_Main.getInstance(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) //initialising the AlertDialogue builder
{
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
roleSpinner.setOnItemSelectedListener(this);
organisationTypeSpinner.setOnItemSelectedListener(org_type_selection);
dp.setOnClickListener(this);
upload_dp.setOnClickListener(this);
// natPriorityAreaSpinner.setAdapter(adapterSetter(priorityArea));
signUp.setOnClickListener(this);
}
private ArrayAdapter<String> adapterSetter(ArrayList<String> data) //to temporarily populate the spinners
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.custom_spinner, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, filter);
receiver.isNetworkAvailable();
//checkConnection();
}
public void signup() {
if (!validate()) { //if the conditions in the validate function are not met return
onSignupFailed();
Toast.makeText(this, "Something went wrong sign-up failed", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(this, "signing up", Toast.LENGTH_SHORT).show();
// signUp.setEnabled(false);
progressDialog.progressDialogStart("Please Wait...");
try {
apiResponse.hitVolleyMultipartApi(this, "signup", getparams(), prof_pic, file);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
// TODO: Implement your own signup logic here.'
// save();
}
public void onSignupSuccess() //if signup is successful
{
signUp.setEnabled(true);
setResult(RESULT_OK, null);
//Toast.makeText(this, "snkflsndkfl", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, HomeActivity.class);
//i.putExtra("Back Functionality", true);
startActivity(i);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Signup failed", Toast.LENGTH_LONG).show();
signUp.setEnabled(true);
}
public boolean validate() //to check the entered information
{
boolean valid = true;
String name = fullName.getText().toString();
String mail = email.getText().toString();
String pword = password.getText().toString();
String org_Name = orgName.getText().toString();
String reEnterPword = reEnterPassword.getText().toString();
if (name.isEmpty() || name.length() < 3) {
fullName.setError("at least 3 characters", null);
valid = false;
} else {
fullName.setError(null);
}
if (mail.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(mail).matches()) {
email.setError("enter a valid email address", null);
valid = false;
} else {
email.setError(null);
}
if (org_Name.isEmpty()) {
orgName.setError("Please enter the organisation's name", null);
valid = false;
} else {
orgName.setError(null);
}
if (pword.isEmpty() || password.length() < 4 || password.length() > 10) {
password.setError("between 4 and 10 alphanumeric characters", null);
valid = false;
} else {
password.setError(null);
}
if (reEnterPword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPword.equals(pword))) {
reEnterPassword.setError("Password Do not match", null);
valid = false;
} else {
reEnterPassword.setError(null);
}
return valid;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
selectedRole = "Facilitator";
break;
case 1:
selectedRole = "Provider Administrator";
break;
case 2:
selectedRole = "Provider Executive";
break;
case 3:
selectedRole = "School PLD Administrator";
break;
case 4:
selectedRole = "MOE National Priority";
break;
case 5:
selectedRole = "Senior Leadership";
break;
case 6:
selectedRole = "Teacher";
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
AdapterView.OnItemSelectedListener org_type_selection = new AdapterView.OnItemSelectedListener() //for organisation type selection
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
selectedOrgType = "Education";
break;
case 1:
selectedOrgType = "IT";
break;
case 2:
selectedOrgType = "Medical";
break;
case 3:
selectedOrgType = "";
break;
case 4:
selectedOrgType = "";
break;
case 5:
selectedOrgType = "";
break;
case 6:
selectedOrgType = "";
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.dp:
case R.id.upload_dp:
ImageOnlyOptionsDialog imageOnlyOptionsDialog = new ImageOnlyOptionsDialog();
imageOnlyOptionsDialog.setonButtonClickListener(new OnButtonClicked() {
#Override
public void onButtonCLick(int buttonId) {
switch (buttonId) {
case R.id.btnCamera:
startCamera();
break;
case R.id.btnGallery:
pickFromGallery();
break;
default:
break;
}
}
});
imageOnlyOptionsDialog.show(getSupportFragmentManager(), ImageOnlyOptionsDialog.class.getSimpleName());
break;
case R.id.signUp_Button:
signup();
break;
case R.id.nat_pri_areaaa:
case R.id.selectionss:
Bundle data = new Bundle();
data.putStringArrayList("pri_areas", nat_pri_area);
RoleSectDialog roleSectDialog = new RoleSectDialog();
roleSectDialog.setArguments(data);
roleSectDialog.show(getSupportFragmentManager(), RoleSectDialog.class.getSimpleName());
roleSectDialog.setonButtonClickListener(new OnButtonClicked() {
#Override
public void onButtonCLick(int buttonId) {
switch (buttonId) {
case R.id.k:
break;
default:
break;
}
}
});
break;
default:
break;
}
}
public void startCamera() {
PackageManager packageManager = this.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
if (!mainDirectory.exists())
mainDirectory.mkdirs();
Calendar calendar = Calendar.getInstance();
uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis() + ".jpeg"));
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
startActivityForResult(intent1, REQUEST_CODE_CAMERA);
}
}
public void pickFromGallery() //this is the intent creation for picking image from gallery
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) //this receives the intent's result
{
if (requestCode == REQUEST_CODE_CAMERA) {
if (resultCode == RESULT_OK) {
try {
ExifInterface exif = new ExifInterface(uriFilePath.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
}
String filePath = getRealPathFromURI(uriFilePath);
file = new File(new URI("file://" + filePath.replace(" ", "%20")));//photo is file type that is global
Glide.with(this)
.load(file)
.placeholder(R.drawable.upload_image)
.into(dp);
// getImageDetails(photo);
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_PICK_IMAGE) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
Toast.makeText(this, selectedImagePath, Toast.LENGTH_SHORT).show();
try {
file = new File(new URI("file://" + selectedImagePath.replace(" ", "%20")));
Glide.with(this).load(file).placeholder(R.drawable.upload_image)
.into(dp);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
}
public String getRealPathFromURI(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(projection[0]);
return cursor.getString(column_index);
}
return uri.getPath();
}
public HashMap<String, String> getparams() { //parameters passed while hitting the API
HashMap<String, String> params = new HashMap<>();
params.put(rulee, "sign_up");
params.put(emaill, email.getText().toString());
params.put(word, password.getText().toString());
params.put(f_name, fullName.getText().toString());
params.put(n_p_a, selections.getText().toString());
params.put(or_name, orgName.getText().toString());
params.put(or_type, selectedOrgType);
Toast.makeText(this, selectedRole, Toast.LENGTH_SHORT).show();
params.put(rolId, selectedRole);
return params;
}
#Override
public void response(String responseObject, String method_call) //this gets the response when API is hit
{
progressDialog.dismissDialog();
try {
JSONObject response = new JSONObject(responseObject);
if (response.getString("flag").equalsIgnoreCase("success")) {
JSONObject object = response.getJSONObject("response");
sharedPreference_main.setUserName(object.getString(f_name));
sharedPreference_main.setUserEmail(object.getString(emaill));
sharedPreference_main.setUserOrganisation(object.getString(or_name));
sharedPreference_main.setUserRole(object.getString(rol));
sharedPreference_main.setOrgType(object.getString(or_type));
sharedPreference_main.setNPA(object.getString(n_p_a));
sharedPreference_main.setUserProfilePic(object.getString(prof_pic));
onSignupSuccess(); //if everything works out call the home activity
} else if (response.getString("flag").equalsIgnoreCase("0")) {
String resp = response.getString("response");
builder.setTitle("Error:"); //building up the dialog
builder.setMessage(resp);
displayAlert(resp);
} else if (response.getString("flag").equalsIgnoreCase("1")) {
// Toast.makeText(this, response.getString("flag"), Toast.LENGTH_SHORT).show();
JSONArray data = response.getJSONArray("message");
if (data.length() > 0) {
for (int i = 0; i < data.length(); i++) {
JSONObject inData = data.getJSONObject(i);
if (inData.has("role_name")) {
role_list.add(inData.getString("role_name"));
} else if (inData.has("organisation_type")) {
org_type.add(inData.getString("organisation_type"));
} else if (inData.has("prior_name")) {
nat_pri_area.add(inData.getString("prior_name"));
}
// N_P_A.add(inData.getString("prior_name"));
}
}
if (role_list.size() > 0) {
// String[] role = role_list.toArray(new String[role_list.size()]);
roleSpinner.setAdapter(adapterSetter(role_list));
}
if (org_type != null) {
// String organisationType[] =org_type.toArray(new String[org_type.size()]);
organisationTypeSpinner.setAdapter(adapterSetter(org_type));
}
// String[] priorityArea = org_type.toArray(new String[org_type.size()]);
//
}
// onSignupSuccess();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void error(String error) {
progressDialog.dismissDialog();
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
private void displayAlert(final String code) {
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
fullName.setText("");
email.setText("");
password.setText("");
orgName.setText("");
}
}).show();
}
private void displayAlert() //overloaded function
{
builder.setTitle("No internet connection");
builder.setTitle("Please switch on the internet");
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// checkConnection();
if (receiver.isNetworkAvailable()) {
dialogInterface.c**strong text**ancel();
} else {
displayAlert();
}
}
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// checkConnection();
dialogInterface.cancel();
}
}).show();
}
public void getData() {
GetServerData getServerData = new GetServerData(this);
getServerData.getRoles();
}
}
Note:
Language version - Java
Target SDK -23
Any help would be appreciated.
This was happening because the permissions were not being provided to the application while running it on the smartphone. Newer versions of Android require the apps to be granted permissions from within the smartphone.
Use this and upvote after your issue gets resolve.
private File profilePic;
private Uri photoFileUri;
/**
* Method below will work for Camera Intent.
*/
private void clickPicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = AppUtils.getInstance().createImageFile(); // Create the File where the photo should go
outputFileUri = FileProvider.getUriForFile(SignUpActivity.this, getApplicationContext().getPackageName() + ".provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePictureIntent, CAMERA_IMAGE_REQUEST);
} catch (IOException io) {
io.printStackTrace(); // Error occurred while creating the File
}
//outputFileUri = Uri.fromFile(photoFile);//At this Uri the image captured will get saved.
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case AppConstants.MediaConstants.REQUEST_CAPTURE_IMAGE:
profilePic = new File(AppUtils.getInstance().getRealPathFromURI(photoFileUri, mActivity));
break;
}
}
}
Use this method below directly in your classs
/**
* method to get real path from uri
*
* #param contentURI
* #param context
* #return
*/
public String getRealPathFromURI(Uri contentURI, Context context) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
create "provide_paths.xml" file in folder name "xml" in res directory and add code below in it
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>
What i am trying to do is getting images from gallery and camera and placing it in an recyclerview.
Now main parts comes after image is now placedd in the recyclerview ,
but can anyone just tell me how can i get back these images shown in the recyclerview back to the mainActivity only when i click my upload button.
Thank you in advance.
My Main Activity.
package www.welkinfort.com.pphc;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import butterknife.ButterKnife;
public class XenImageUploading extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
ArrayAdapter<String> des_dataAdapter;
ArrayList<String> discription_list = new ArrayList<>();
//#BindView(R.id.selct_prject_spinner)
Spinner select_pro_spn;
TextView datetextTextView;
Calendar myCalendar;
static Bitmap rotatedBitmap;
static Bitmap finalrotatedBitmap;
DatePickerDialog.OnDateSetListener date;
static final int REQUEST_TAKE_PHOTO = 1;
private int SELECT_FILE = 2;
private static String bitmap_overdraw_str;
private static ImageButton cameraclick;
private static ImageButton galleryclick;
private static ImageButton videoclick;
private static String mCurrentPhotoPath;
private static RecyclerView recyclerView;
ArrayList<Data_Model> arrayList;
ImageView image_view;
MyAdapter m;
Bitmap finalbitmap;
static String clickpath;
int i = 0;
String path ;
private static final String TAG = "XenImageUploading";
static File photoFile_1 = null;
private String userChoosenTask;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xen_image_upload);
ButterKnife.bind(this);
setTitle("XEN IMAGE UPLOAD");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
cameraclick = (ImageButton) findViewById(R.id.camera_btn);
galleryclick = (ImageButton) findViewById(R.id.gallery_btn);
image_view = (ImageView) findViewById(R.id.image_view);
arrayList = new ArrayList<>();
Log.d("oncreate", "set adapter");
bitmap_overdraw_str = "Lat:" + "aaaaaaaa" + "\nLong:" + "aaaaaaaa" + "\nDate:" + "aaaaaaaa";
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
///////////////////////////////////////////////////////////////////
//select_pro_spn = (Spinner) findViewById(R.id.selct_prject_spinner);
//datetextTextView = (TextView) findViewById(R.id.selctdate__txtv);
discription_list.add("Traffic light broken/not working");
discription_list.add("Traffic light pole hit by vehicle");
discription_list.add("No electricity connection");
discription_list.add("Traffic light not visible/partially visible");
// select_pro_spn.setOnItemSelectedListener(this);
// Creating adapter for spinner
des_dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, discription_list);
// Drop down layout style - list view with radio button
des_dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
// select_pro_spn.setAdapter(des_dataAdapter);
myCalendar = Calendar.getInstance();
date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
// datetextTextView.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// new DatePickerDialog(XenImageUploading.this, date, myCalendar
// .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
// myCalendar.get(Calendar.DAY_OF_MONTH)).show();
// }
// });
cameraclick.setOnClickListener(this);
galleryclick.setOnClickListener(this);
recyclerView.setOnClickListener(this);
}
private void updateLabel() {
String myFormat = "MM-dd-yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
datetextTextView.setText(sdf.format(myCalendar.getTime()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
// case R.id.selct_prject_spinner:
// String selected_intersection = parent.getSelectedItem().toString();
// Log.e("Selected item ", selected_intersection);
// //parent.notifyAll();
// break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.camera_btn:
selectImage();
break;
case R.id.recycler_view:
getImageall();
break;
case R.id.gallery_btn:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, SELECT_FILE);
break;
}
}
private void getImageall() {
}
private void selectImage() {
takepicture();
}
public void takepicture() {
Log.d(TAG, "takepicture");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
photoFile_1 = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile_1 != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile_1));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && null != data) {
// Save Image To Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
////////////////setting image to adapter on capturing///////////////////////////
clickpath = mCurrentPhotoPath;
Bitmap bitmap = BitmapUtility.decodeSampledBitmapFromResource(clickpath, 560, 300);
setCameraDisplayOrientation(bitmap);
try {
FileOutputStream fos = new FileOutputStream(photoFile_1);
finalrotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
Data_Model data_model = new Data_Model();
data_model.setImage(finalrotatedBitmap);
image_view.setImageBitmap(finalrotatedBitmap);
arrayList.add(data_model);
m = new MyAdapter(this, arrayList);
recyclerView.setAdapter(m);
m.notifyDataSetChanged();
}
if (requestCode == SELECT_FILE && resultCode == RESULT_OK && null != data) {
InputStream stream = null;
Uri uri = data.getData();
//for (int i =0 ; i<numberOfImages ;i++){
getImagePath(uri);
Data_Model data_model = new Data_Model();
data_model.setImage(finalbitmap);
image_view.setImageBitmap(finalbitmap);
arrayList.add(data_model);
m = new MyAdapter(this, arrayList);
recyclerView.setAdapter(m);
m.notifyDataSetChanged();
// }
}
}
public String getImagePath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
finalbitmap = BitmapUtility.decodeSampledBitmapFromResource(path, 560, 300);
//targetImage = (ImageView)findViewById(R.id.imageView1);
image_view.setImageBitmap(finalbitmap);
return path;
}
public static void setCameraDisplayOrientation(Bitmap fileresult) {
Log.e(TAG, "setCameraDisplayOrientation");
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(clickpath, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(clickpath, opts);
ExifInterface exif = null;
try {
exif = new ExifInterface(clickpath);
} catch (IOException e) {
e.printStackTrace();
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
finalrotatedBitmap = AddTextonBitmap.textAsBitmap(rotatedBitmap, bitmap_overdraw_str);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
}
Adapter class
package www.welkinfort.com.pphc;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
/**
* Created by Admin on 13-Jul-17.
*/
class MyAdapter extends RecyclerView.Adapter<MyAdapter.Myviewholder> {
private static final String TAG = "Adapter";
static Data_Model m;
XenImageUploading xenImageUploading;
ArrayList<Data_Model> arrayList;
private Context mContext;
public MyAdapter(XenImageUploading xenImageUploading, ArrayList<Data_Model> arrayList) {
this.arrayList = arrayList;
this.xenImageUploading = xenImageUploading;
}
#Override
public Myviewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.abc, parent, false);
Myviewholder myviewholder = new Myviewholder(view);
Log.d("myactivty ", "oncreateViewHolder");
return myviewholder;
}
#Override
public void onBindViewHolder(final Myviewholder holder, final int position) {
m = arrayList.get(position);
Log.d(" myactivty", "onBindviewholder" + position);
holder.imageView.setImageBitmap(m.getImage());
}
#Override
public int getItemCount() {
return arrayList == null ? 0 : arrayList.size();
}
public class Myviewholder extends RecyclerView.ViewHolder {
// public View view;
public ImageView imageView;
public Myviewholder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
}
try this create one method in your adapter like this
public ArrayList<Data_Model> getArray() {
return arrayList;
}
now on your button click just call this method
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Data_Model> arrayList= adapter.getArray();
}
});
ask me in case of any query
Im following the tutorial of In-app Billing from the following link:
Android Studio Google Play In-app Billing Tutorial.
Im implementing this logic in a Contact Adapter class which extends Base Adapter. In tutorial it is implemented in a class which extends Activity.
Error comes on onActivityResult(). I read several questions on this and I understand this method should be written in class which extends Activity but in my case the scenario is different.
Is there any way to solve this without writing onActivityResult method in MainActivity class.. and if not what should I do?
Heres ContactAdapter.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.neirx.myco.smsproject.util.IabHelper;
import com.neirx.myco.smsproject.util.IabResult;
import com.neirx.myco.smsproject.util.Inventory;
import com.neirx.myco.smsproject.util.Purchase;
import java.util.List;
public class ContactAdapter extends BaseAdapter {
private static final java.lang.String CLASS_NAME = "<ContactAdapter> ";
Context context;
List<Contact> objects;
LayoutInflater lInflater;
MainActivity activity;
static final String ITEM_SKU = "android.test.purchased";
IabHelper mHelper;
int count = 0;
int get_limit;
private int limit_counter = 0;
private int max_limit = 2;
boolean testbool = true;
public ContactAdapter(Context context, List<Contact> contact) {
this.context = context;
objects = contact;
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = (MainActivity) context;
}
#Override
public int getCount() {
int selectedCount = 0;
int nonSelectedCount = 0;
int size = 0;
for(Contact contact : objects){
if(contact.isChecked()) selectedCount++;
else nonSelectedCount++;
}
if(activity.isShowSelected()) size += selectedCount;
if(activity.isShowNonSelected()) size += nonSelectedCount;
return size;
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void buyClick() {
mHelper.launchPurchaseFlow(activity, ITEM_SKU, 10001, mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (!mHelper.handleActivityResult(requestCode,resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,Purchase purchase)
{
if (result.isFailure()) {
// Handle error
Log.d("----FAILURE 1---", "FAIL 1");
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
//buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,Inventory inventory) {
if (result.isFailure()) {
// Handle failure
Log.d("----FAILURE 2---", "FAIL 2");
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,IabResult result) {
if (result.isSuccess()) {
//clickButton.setEnabled(true);
Log.d("----Success ----", "Success");
} else {
// handle error
Log.d("----FAILURE 3---", "FAIL 3");
}
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxW650UixX2dLFECVdOpTh5OpBTqHwsznQAKd/cVcqKhrXROy4+Gj6B7M6wbkhTaloNSzTOf+nw9t1LZZ19Vlr6kcwmtxP+V/HOFwjf/NB69StOONogXtGKDyRrxtVaPM5es3yGy/aP/LXWfTLFQYJvur4AePonuRXz33iufBq5ITDQJ0+0D/o/mGtadJv0ZMsP9LV/qrMqruoqpSdaIiw5TGXdzYlJTuoP3GwS9kRyZKDeG/70KZ28W/ZclVWAdnZ7aCeDURYDV3a4pmGp5/cIvKwbex6Y7KbQYENX5ObSgNoFHLdyPTdkYaeuU9O6pet2TjGUCKr8n4M5KUMZVm8QIDAQAB";
mHelper = new IabHelper(context, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d("---MY TAG---", "In-app Billing setup failed: " +
result);
} else {
Log.d("---MY TAG---", "In-app Billing is set up OK");
}
}
});
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
get_limit = limit_pref.getInt("LIMIT_KEY",0);
//Log.d("----- STORED VALUE-----", "Value is: "+get_limit);
Log.d("----- Max VALUE-----", "Value is: "+max_limit);
if (view == null) {
view = lInflater.inflate(R.layout.view_contact, parent, false);//create view file
}
if (position == 0) {
count = 0;
}
if (!activity.isShowSelected()) {
while (objects.get(position + count).isChecked()) {
count++;
}
}
if (!activity.isShowNonSelected()) {
while (!objects.get(position + count).isChecked()) {
count++;
}
}
final Contact contact = objects.get(position + count);
String contactFirstName = contact.getFirstName();
String contactSecondName = contact.getSecondName();
String contactMiddleName = contact.getMiddleName();
String[] contactNumbers = contact.getNumbers();
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvNumber = (TextView) view.findViewById(R.id.tvNumber);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
if(get_limit == max_limit)
{
//checkBox.setChecked(contact.isChecked());
//testbool = false;
limit_counter = get_limit;
}
else if (get_limit == 1)
{
limit_counter = 1;
}
String fullName;
switch (MainActivity.sortMode) {
case Contact.COMPARE_SECOND_NAME:
fullName = getFullName(contactSecondName, contactFirstName);
break;
case Contact.COMPARE_MIDDLE_NAME:
fullName = getFullName(contactMiddleName, contactFirstName, contactSecondName);
break;
default:
fullName = getFullName(contactFirstName, contactSecondName);
break;
}
tvName.setText(fullName);
StringBuilder sbNumber = new StringBuilder();
for (int i = 0; i < contactNumbers.length; i++) {
sbNumber.append(contactNumbers[i]);
if (i < contactNumbers.length - 1) {
sbNumber.append(", ");
}
}
tvNumber.setText(sbNumber);
if (testbool) {
//Log.d("Check Boolean Tag 2 ", "testbool: "+testbool);
checkBox.setChecked(contact.isChecked());
}
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences selected = context.getSharedPreferences(Statical.CONTACTS_SELECTED, Context.MODE_PRIVATE);
SharedPreferences.Editor editSelected = selected.edit();
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
SharedPreferences.Editor edit_limit_pref = limit_pref.edit();
int k = 0;
if(limit_counter == max_limit)
{
checkBox.setChecked(false);
//Toast.makeText(context,"Limit reached !! ", Toast.LENGTH_SHORT).show();
Log.d("-------LIMIT REACH-----", "value: "+limit_counter);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
showAlertDialog();
}
if (contact.isChecked() && limit_counter <= max_limit && limit_counter >= 0) {
limit_counter = limit_counter - 1;
editSelected.putBoolean(contact.getContactId(), false);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(false);
Log.d("-------UN CHECKED-----", "Un Checked value: "+limit_counter);
k = -1;
}
else if(!contact.isChecked() && limit_counter < max_limit){
limit_counter = limit_counter + 1;
editSelected.putBoolean(contact.getContactId(), true);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(true);
Log.d("------- CHECKED -----", "Checked value: "+limit_counter);
k = 1;
}
editSelected.apply();
edit_limit_pref.apply();
activity.updateCount(k);
}
});
return view;
}
public void showAlertDialog()
{
Log.d("-------VALUE-----", "value: "+limit_counter);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Limit Reached!");
alertDialog.setMessage("Buy Pro Version");
alertDialog.setIcon(R.drawable.action_bar_logo);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
buyClick();
Log.d("-------OK PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("----LATER PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.show();
}
private String getFullName(String first, String second, String third) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second).append(" ");
}
if (!third.isEmpty()) {
sbName.append(third);
}
return sbName.toString();
}
private String getFullName(String first, String second) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second);
}
return sbName.toString();
}
}
I recommend you to create an activity just to process this payment and then you can back to your normal flow.
I have an activity with uses onOptionsItemSelected(MenuItem item) method in FolderActivity and I want to call this method on another activity (MainActivity)
the main activity uses CMU Sphinx - Speech Recognition Toolkit.
I need to call some methods from FolderActivity to MainActivity.
package com.evolution.filemanager.folders;
import static android.widget.Toast.makeText;
import java.io.File;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.evolution.filemanager.FileManagerApplication;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.clipboard.Clipboard;
import com.evolution.filemanager.clipboard.Clipboard.ClipboardListener;
import com.evolution.filemanager.clipboard.ClipboardFileAdapter;
import com.evolution.filemanager.favourites.FavouritesManager;
import com.evolution.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.evolution.filemanager.nav_drawer.NavDrawerAdapter;
import com.evolution.utils.FontApplicator;
import com.evolution.utils.ListViewUtils;
import edu.cmu.pocketsphinx.demo.R;
public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
public static class FolderNotOpenException extends Exception
{
}
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
public static Activity FOLDERACTIVITY;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_folder);
setupDrawers();
Clipboard.getInstance().addListener(this);
FOLDERACTIVITY = this;
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
#Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
#Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
public void setActionbarVisible(boolean visible)
{
ActionBar actionBar = getActionBar();
if (actionBar == null) return;
if (visible)
{
actionBar.show();
setSystemBarTranslucency(false);
}
else
{
actionBar.hide();
setSystemBarTranslucency(true);
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void setSystemBarTranslucency(boolean translucent)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
if (translucent)
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else
{
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setAttributes(params);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;
#Override
public void onDrawerOpened(View drawerView)
{
makeText(getApplicationContext(), "drawer open", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
makeText(getApplicationContext(), "drawer close", Toast.LENGTH_SHORT).show();
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
drawerLayout.setFocusableInTouchMode(false);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
#Override
public void onBackPressed()
{
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else if (drawerLayout.isDrawerOpen(GravityCompat.END))
drawerLayout.closeDrawer(GravityCompat.END);
else
super.onBackPressed();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
// add listview header to push items below the actionbar
ListView navListView = (ListView) findViewById(R.id.listNavigation);
ListViewUtils.addListViewPadding(navListView, this, true);
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
ListViewUtils.addListViewHeader(clipboardListView, this);
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
makeText(getApplicationContext(), "unsa ni?", Toast.LENGTH_SHORT).show();
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
public File getCurrentFolder() throws FolderNotOpenException
{
FolderFragment folderFragment = getFolderFragment();
if (folderFragment == null)
throw new FolderNotOpenException();
else return folderFragment.currentDir;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerAdapter.NavDrawerItem item = (NavDrawerAdapter.NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
FolderFragment folderFragment = getFolderFragment();
if (folderFragment != null)
{
// TODO: paste single file
}
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
#Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
#Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event)
{
Log.d("Key Long Press", event.toString());
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
return true;
}
else return super.onKeyLongPress(keyCode, event);
}
}
and the activity where I want to call
package edu.cmu.pocketsphinx.demo;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.folders.FolderActivity;
import com.evolution.utils.DataClearer;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
public class MainActivity extends Activity implements
RecognitionListener {
public AnimationDrawable rocketAnimation;
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "frost";
private static final String GO_BACK = "back";
private static final String PREVIOUS = "previous";
private static final String OPEN_FILE_MANAGER = "open file manager";
private static final String OPEN_ABOUT = "open about";
private static final String OPEN_MUSIC = "open music";
private static final String OPEN_PICTURES = "open pictures";
private static final String OPEN_VIDEOS = "open videos";
private static final String SHOW_COMMANDS = "show commands";
private static final String CLOSE_FILE_MANAGER = "close file manager";
private static final String CLOSE_ABOUT = "close about";
private static final String CLOSE_MUSIC = "close music";
private static final String CLOSE_PICTURES = "close pictures";
private static final String CLOSE_VIDEOS = "close videos";
private static final String CLOSE_COMMANDS = "close commands";
private static final String SHOW_DRAWER = "show drawer";
private static final String HIDE_DRAWER = "hide drawer";
public static boolean isOPEN_FILE_MANAGER = false;
private static boolean isOPEN_ABOUT = false;
private static boolean isOPEN_MUSIC = false;
private static boolean isOPEN_PICTURES = false;
private static boolean isOPEN_VIDEOS = false;
private static boolean isSHOW_COMMANDS = false;
private static boolean isSHOW_DRAWER = false;
private static String MENU_CAPTION;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
ImageView rocketImage = (ImageView) findViewById(R.id.imageViewAnim);
rocketImage.setBackgroundResource(R.drawable.heart_animation);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
TextView tv = ((TextView) findViewById(R.id.caption_text));
if (text.equals(KEYPHRASE))
{
switchSearch(MENU_SEARCH);
rocketAnimation.start();
}
else if (text.equals(OPEN_FILE_MANAGER))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , FolderActivity.class);
startActivity(intent);
isOPEN_FILE_MANAGER = true;
}
else if (text.equals(CLOSE_FILE_MANAGER))
{
if(isOPEN_FILE_MANAGER == true)
{
switchSearch(KWS_SEARCH);
FolderActivity.FOLDERACTIVITY.finish();
isOPEN_FILE_MANAGER = false;
}
}
else if (text.equals(SHOW_COMMANDS))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , Commands.class);
startActivity(intent);
isSHOW_COMMANDS = true;
}
else if (text.equals(CLOSE_COMMANDS))
{
if(isSHOW_COMMANDS == true)
{
switchSearch(KWS_SEARCH);
Commands.SHOWCOMMANDS.finish();
}
}
else if (text.equals(OPEN_PICTURES))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , AboutActivity.class);
startActivity(intent);
}
else if(text.equals(OPEN_ABOUT))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent(PocketSphinxActivity.this, AboutActivity.class);
startActivity(intent);
isOPEN_ABOUT = true;
}
else if(text.equals(CLOSE_ABOUT))
{
if (isOPEN_ABOUT == true)
{
switchSearch(KWS_SEARCH);
AboutActivity.ABOUTACTIVITY.finish();
}
}
else if(text.equals(GO_BACK) || text.equals(PREVIOUS))
{
if(isOPEN_FILE_MANAGER == true )
{
FolderActivity.FOLDERACTIVITY//where i want to call onOptionsItemSelected
switchSearch(KWS_SEARCH);
}
}
else
{
switchSearch(KWS_SEARCH);
((TextView) findViewById(R.id.result_text)).setText(text);
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName())
|| OPEN_FILE_MANAGER.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/menu.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this); //clear cache to minimize the app size
DataClearer.getInstance().clearApplicationData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
the FolderActivity runs on top of the MainActivty but the voice recognition in MainActivity is still active and I want the voice itself do some manipulation in the FolderActivity
Here's a few suggestions:
Have FolderActivity register a BroadcastReceiver as a listener for a certain Intent. When MainActivity wants to do something in FolderActivity, it can send a broadcast Intent which will be seen by the BroadcastReceiver in FolderActivity, which can then call the appropriate method in the `Activity.
When MainActivity wants to do something in FolderActivity, it can launch FolderActivity again using an Intent with flag Intent.FLAG_ACTIVITY_SINGLE_TOP and some "extra" that describes what FolderActivity should do. In FolderActivity override onNewIntent(), read the passed Intent parameter and use it to determine what method to call in FolderActivity. Because the Activity was launched withIntent.FLAG_ACTIVITY_SINGLE_TOP, Android won't create a new instance of the Activity, it will just callonNewIntent()` on the existing instance.
Have FolderActivity set a public static variable of type Activity to a reference to itself in onCreate(). MainActivity can then call a method on FolderActivity by doing something like FolderActivity.activityReference.doSomething()
Method 3 is not the preferred method, since you need to make sure that you set the public static variable to null in FolderActivity.onDestroy() and there are other concerns (timing issues, memory leaks, etc.) that need to be dealt with properly.
NOTE: You probably don't want to call onOptionsItemSelected() directly. This method is called by the Android framework when an options item is selected by the user. You should call directly the method that actually does something, not this framework callback method.
I have a BaseAdapter class using ViewHolders to display a list of checked apps. I store the checked apps with SharedPreferences so the apps that are checked stay checked. What I am trying to achieve is getting the checked apps in my Service Class as ideally store it in an arraylist or something of the sort.
The problem is that the keys are what I used to the get the values are in the BaseAdapter class too and I can't get it from the service class so I had to recreate the methods for getting the list of packages and iterating through with a for loop.
I also cannot checked if the holder checkbox is checked in my Service class since that is done in my BaseAdapter class.
Despite passing the context in BaseAdapter and using getApplicationContext with SharedPreferences I cannot get the list of checked apps in the service class. I am not sure where to turn now. I have tried everything from messing around with static variables, trying everything with getting the context from the BaseAdapter class etc.
Here is my Adapter Class (I have commented where I get the apps which are checked):
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.ArrayList;
import java.util.List;
//
public class ApkAdapter extends BaseAdapter {
//Pastebin link: http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
// http://pastebin.com/Te2g072w, http://pastebin.com/NLT5iUiA ,
SharedPreferences sharedPrefs;
List<PackageInfo> packageList;
ArrayList <String> appchecklist;
static ArrayList <String> newappchecklist;
Context mContext;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
String PACKAGE_NAME;
static TinyDB appcheckdb;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.mContext = mContext;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
appchecklist = new ArrayList<String>();
newappchecklist = new ArrayList<String>();
appcheckdb = new TinyDB(context);
}
public ApkAdapter(Context heartBeat) {
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
TextView packageName;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
holder.packageName = (TextView) convertView.findViewById(R.id.app_package);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
final PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
// Make sure to define it again!
PACKAGE_NAME = packageInfo.packageName;
final String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 80, 80);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
//holder.packageName.setText(PACKAGE_NAME);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
for(int i= 0; i<packageList.size(); i++){
PACKAGE_NAME = packageInfo.packageName;
//Log.d("lol", PACKAGE_NAME);
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
newappchecklist = appcheckdb.getList("appcheck");
holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));
}
// appchecklist has all the checked apps!!!!!
// it is right here!!!!!!
if(holder.ck1.isChecked()){
appchecklist.add(packageInfo.packageName);
appcheckdb.putList("appcheck", appchecklist);
for (Object data : appchecklist) {
Log.e("HUH!?: ",(String) data);
}
}
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = context.getSharedPreferences(packageInfo.packageName, Context.MODE_PRIVATE).edit();
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
editor.putBoolean(packageInfo.packageName, true);
editor.apply();
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
/* editor.putBoolean(packageInfo.packageName, false);
editor.apply();*/
}
}
});
return convertView;
}
public void check( View convertView, int position){
final ViewHolder holder;
holder = new ViewHolder();
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
convertView.setTag(holder);
final PackageInfo packageInfo = (PackageInfo) getItem(position);
PACKAGE_NAME = packageInfo.packageName;
if(holder.ck1.isChecked()){
appchecklist.add(packageInfo.packageName);
appcheckdb.putList("appcheck", appchecklist);
for (Object data : appchecklist) {
Log.e("HUH!?: ",(String) data);
}
}
}
public static ArrayList getArrayList()
{
newappchecklist = appcheckdb.getList("appcheck");
return newappchecklist;
}
}
Here is my service class! I commented where I am trying to get the list:
package com.ibc.android.demo.appslist.app;
import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
public class HeartBeat extends Service {
private static final String TAG = HeartBeat.class.getSimpleName();
public Timer TIMER;
String CURRENT_PACKAGE_NAME;
private static Set<AccessGranted> mAccessGrantedList = new HashSet<AccessGranted>();
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
private BroadcastReceiver mAccessGrantedReceiver;
private File mLockedAppsFile;
private ArrayList newArrayList = null;
SharedPreferences sharedPrefs;
PackageManager pm = null;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, HeartBeat.class));
pm = getPackageManager();
List<PackageInfo> packageList = pm
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//TRYING TO GET IT OVER HERE!
for(int i = 0; i < packageList1.size(); i++) {
Log.e("hannnnnnn values ", packageList1.get(i)+ "");
sharedPrefs = getApplicationContext().getSharedPreferences(String.valueOf(packageList1.get(i)), Context.MODE_PRIVATE);
}
//TRYING TO CHECK IT OVER HERE!
Map<String, ?> allEntries = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.e("map values", entry.getKey() + ": " + entry.getValue().toString());
}
// Log.i("LocalService", "Received start id " + startId + ": " +
// intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
mAccessGrantedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String packageName = intent.getStringExtra("packageName");
if (action.equals(Constants.ACTION_GRANT_ACCESS) && packageName != null) {
AccessGranted ag = new AccessGranted(packageName);
mAccessGrantedList.remove(ag);
mAccessGrantedList.add(ag);
}
}
};
IntentFilter filter2 = new IntentFilter(Constants.ACTION_GRANT_ACCESS);
registerReceiver(mAccessGrantedReceiver, filter2);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, HeartBeat.class));
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
// Log.e("activity on Top", "" + activityOnTop);
// Log.e(" My package name", "" + getApplicationContext().getPackageName());
// newArrayList = ApkAdapter.getArrayList();
// for (Object data : newArrayList) {
// Provide the packagename(s) of apps here, you want to show password activity
if ((activityOnTop.contains("com.android.camera")) &&
(!activityOnTop.contains(getApplicationContext().getPackageName()
))) { // you have to make this check even better
Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra( "", "");
startActivity(i);
}
//}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
}
Ultimately, I can just tryna get the job done for getting a list of checked apps in my service class. So no matter what whenever I have the service running I have the list of checked apps. Whenever the app opens, re opens, restarts or does whatever, etc.
Help is appreciated. Let me know if there is anything else I can add.
I ended up creating a new database in my SharedPreferences to store only checked apps.
Here is my BaseAdapter class:
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.HashSet;
import java.util.List;
//
public class ApkAdapter extends BaseAdapter {
//Pastebin link: http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
// http://pastebin.com/Te2g072w, http://pastebin.com/NLT5iUiA ,
SharedPreferences sharedPrefs;
SharedPreferences sharedPrefsapp;
List<PackageInfo> packageList;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
HashSet checked;
String PACKAGE_NAME;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
TextView packageName;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
holder.packageName = (TextView) convertView.findViewById(R.id.app_package);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
final PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
// Make sure to define it again!
PACKAGE_NAME = packageInfo.packageName;
final String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 80, 80);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
//holder.packageName.setText(PACKAGE_NAME);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
// CHANGE UP EVERYTHING! MAKE THIS SHIT WORK, TIGGA!
checked = new HashSet();
PACKAGE_NAME = packageInfo.packageName;
//Log.d("just here: ", PACKAGE_NAME);
sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = context.getSharedPreferences("appdb", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE).edit();
SharedPreferences.Editor editorapp = context.getSharedPreferences("appdb", Context.MODE_PRIVATE).edit();
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
editor.putBoolean(packageInfo.packageName, true);
editorapp.putString(packageInfo.packageName, packageInfo.packageName);
editor.apply();
editorapp.apply();
// sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
editor.putBoolean(packageInfo.packageName, false);
editorapp.remove(packageInfo.packageName);
editor.apply();
editorapp.apply();
//sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
}
}
});
return convertView;
}
}
I retrieve the values in service class with key "appdb"
package com.ibc.android.demo.appslist.app;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HeartBeat extends Service {
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//startService(new Intent(this, HeartBeat.class));
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
//Log.e("right key: ", entry.getKey() + "right value: " + entry.getValue().toString() );
packagezList.add(entry.getKey());
}
for(Object object: packagezList){
Log.e("YO!", (String) object);
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
// Log.e("activity on Top", "" + activityOnTop);
// Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
// Provide the packagename(s) of apps here, you want to show password activity
if ((activityOnTop.contains((CharSequence) object)) &&
(!activityOnTop.contains(getApplicationContext().getPackageName()
))) { // you have to make this check even better
Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra( "", "");
startActivity(i);
}
}
} catch (Exception e) {
// Log.e("Foreground App", e.getMessage(), e);
}
Intent ishintent = new Intent(this, HeartBeat.class);
PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),150000, pintent);
return START_STICKY;
}
// Log.i("LocalService", "Received start id " + startId + ": " +
// intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
#Override
public void onDestroy() {
Intent ishintent = new Intent(this, HeartBeat.class);
PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),150000, pintent);
//startService(new Intent(this, HeartBeat.class));
}
// this.stopSelf();
//startforeground goes here
}