I try to solve using below code:
[Reference: Android: Clear Cache of All Apps?
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
and add permission in AndroidMenifest.xml file
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
But when i run this code, then throw exception :
java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2
Any suggestion to overcome this exception or another solution for clear cache of all apps programmatically. Thanks
follow the link. hopefully get a solutions
https://fossdroid.com/s.html?q=cache+cleaner
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.frozendevs.cache.cleaner.R;
import com.frozendevs.cache.cleaner.activity.SettingsActivity;
import com.frozendevs.cache.cleaner.model.AppsListItem;
import com.frozendevs.cache.cleaner.model.CleanerService;
import com.frozendevs.cache.cleaner.model.adapter.AppsListAdapter;
import com.frozendevs.cache.cleaner.widget.DividerDecoration;
import com.frozendevs.cache.cleaner.widget.RecyclerView;
import java.util.List;
public class CleanerFragment extends Fragment implements CleanerService.OnActionListener {
private static final int REQUEST_STORAGE = 0;
private static final String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private CleanerService mCleanerService;
private AppsListAdapter mAppsListAdapter;
private TextView mEmptyView;
private SharedPreferences mSharedPreferences;
private ProgressDialog mProgressDialog;
private View mProgressBar;
private TextView mProgressBarText;
private LinearLayoutManager mLayoutManager;
private Menu mOptionsMenu;
private boolean mAlreadyScanned = false;
private boolean mAlreadyCleaned = false;
private String mSearchQuery;
private String mSortByKey;
private String mCleanOnAppStartupKey;
private String mExitAfterCleanKey;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mCleanerService = ((CleanerService.CleanerServiceBinder) service).getService();
mCleanerService.setOnActionListener(CleanerFragment.this);
updateStorageUsage();
if (!mCleanerService.isCleaning() && !mCleanerService.isScanning()) {
if (mSharedPreferences.getBoolean(mCleanOnAppStartupKey, false) &&
!mAlreadyCleaned) {
mAlreadyCleaned = true;
cleanCache();
} else if (!mAlreadyScanned) {
mCleanerService.scanCache();
}
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mCleanerService.setOnActionListener(null);
mCleanerService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
mSortByKey = getString(R.string.sort_by_key);
mCleanOnAppStartupKey = getString(R.string.clean_on_app_startup_key);
mExitAfterCleanKey = getString(R.string.exit_after_clean_key);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mAppsListAdapter = new AppsListAdapter();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.cleaning_cache);
mProgressDialog.setMessage(getString(R.string.cleaning_in_progress));
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
getActivity().getApplication().bindService(new Intent(getActivity(), CleanerService.class),
mServiceConnection, Context.BIND_AUTO_CREATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleaner_fragment, container, false);
mEmptyView = (TextView) rootView.findViewById(R.id.empty_view);
mLayoutManager = new LinearLayoutManager(getActivity());
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAppsListAdapter);
recyclerView.setEmptyView(mEmptyView);
recyclerView.addItemDecoration(new DividerDecoration(getActivity()));
mProgressBar = rootView.findViewById(R.id.progressBar);
mProgressBarText = (TextView) rootView.findViewById(R.id.progressBarText);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
mOptionsMenu = menu;
inflater.inflate(R.menu.main_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
mSearchQuery = query;
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (ViewCompat.isLaidOut(searchView) && mSearchQuery != null) {
String oldText = mSearchQuery;
mSearchQuery = newText;
if (!oldText.equals(newText)) {
mAppsListAdapter.sortAndFilter(getActivity(), getSortBy(), newText);
}
}
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
if (mSearchQuery == null) {
mSearchQuery = "";
}
mAppsListAdapter.setShowHeaderView(false);
mEmptyView.setText(R.string.no_such_app);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mSearchQuery = null;
mAppsListAdapter.clearFilter();
mAppsListAdapter.setShowHeaderView(true);
if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
mLayoutManager.scrollToPosition(0);
}
mEmptyView.setText(R.string.empty_cache);
return true;
}
});
if (mSearchQuery != null) {
MenuItemCompat.expandActionView(searchItem);
searchView.setQuery(mSearchQuery, false);
}
updateOptionsMenu();
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clean:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning() && mCleanerService.getCacheSize() > 0) {
mAlreadyCleaned = false;
cleanCache();
}
return true;
case R.id.action_refresh:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mCleanerService.scanCache();
}
return true;
case R.id.action_settings:
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
case R.id.action_sort_by_app_name:
setSortBy(AppsListAdapter.SortBy.APP_NAME);
updateOptionsMenu();
return true;
case R.id.action_sort_by_cache_size:
setSortBy(AppsListAdapter.SortBy.CACHE_SIZE);
updateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
updateOptionsMenu();
}
#Override
public void onDestroyOptionsMenu() {
mOptionsMenu = null;
}
#Override
public void onResume() {
updateStorageUsage();
updateOptionsMenu();
if (mCleanerService != null) {
if (mCleanerService.isScanning() && !isProgressBarVisible()) {
showProgressBar(true);
} else if (!mCleanerService.isScanning() && isProgressBarVisible()) {
showProgressBar(false);
}
if (mCleanerService.isCleaning() && !mProgressDialog.isShowing()) {
mProgressDialog.show();
}
}
super.onResume();
}
#Override
public void onPause() {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
super.onPause();
}
#Override
public void onDestroy() {
getActivity().getApplication().unbindService(mServiceConnection);
super.onDestroy();
}
private void updateOptionsMenu() {
if (mOptionsMenu != null) {
mOptionsMenu.findItem(R.id.action_sort_by_app_name).setVisible(
getSortBy() == AppsListAdapter.SortBy.CACHE_SIZE);
mOptionsMenu.findItem(R.id.action_sort_by_cache_size).setVisible(
getSortBy() == AppsListAdapter.SortBy.APP_NAME);
}
}
private void updateStorageUsage() {
if (mAppsListAdapter != null) {
StatFs stat = new StatFs(Environment.getDataDirectory().getAbsolutePath());
long totalMemory = (long) stat.getBlockCount() * (long) stat.getBlockSize();
long medMemory = mCleanerService != null ? mCleanerService.getCacheSize() : 0;
long lowMemory = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
!Environment.isExternalStorageEmulated()) {
stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
totalMemory += (long) stat.getBlockCount() * (long) stat.getBlockSize();
lowMemory += (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
long highMemory = totalMemory - medMemory - lowMemory;
mAppsListAdapter.updateStorageUsage(totalMemory, lowMemory, medMemory, highMemory);
}
}
private AppsListAdapter.SortBy getSortBy() {
try {
return AppsListAdapter.SortBy.valueOf(mSharedPreferences.getString(mSortByKey,
AppsListAdapter.SortBy.CACHE_SIZE.toString()));
} catch (ClassCastException e) {
return AppsListAdapter.SortBy.CACHE_SIZE;
}
}
private void setSortBy(AppsListAdapter.SortBy sortBy) {
mSharedPreferences.edit().putString(mSortByKey, sortBy.toString()).apply();
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mAppsListAdapter.sortAndFilter(getActivity(), sortBy, mSearchQuery);
}
}
private boolean isProgressBarVisible() {
return mProgressBar.getVisibility() == View.VISIBLE;
}
private void showProgressBar(boolean show) {
if (show) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
mProgressBar.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_out));
mProgressBar.setVisibility(View.GONE);
}
}
private void showStorageRationale() {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
dialog.setTitle(R.string.rationale_title);
dialog.setMessage(getString(R.string.rationale_storage));
dialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private void cleanCache() {
if (!CleanerService.canCleanExternalCache(getActivity())) {
if (shouldShowRequestPermissionRationale(PERMISSIONS_STORAGE[0])) {
showStorageRationale();
} else {
requestPermissions(PERMISSIONS_STORAGE, REQUEST_STORAGE);
}
} else {
mCleanerService.cleanCache();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_STORAGE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCleanerService.cleanCache();
} else {
showStorageRationale();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onScanStarted(Context context) {
if (isAdded()) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mProgressBarText.setText(R.string.scanning);
showProgressBar(true);
}
}
#Override
public void onScanProgressUpdated(Context context, int current, int max) {
if (isAdded()) {
mProgressBarText.setText(getString(R.string.scanning_m_of_n, current, max));
}
}
#Override
public void onScanCompleted(Context context, List<AppsListItem> apps) {
mAppsListAdapter.setItems(getActivity(), apps, getSortBy(), mSearchQuery);
if (isAdded()) {
updateStorageUsage();
showProgressBar(false);
}
mAlreadyScanned = true;
}
#Override
public void onCleanStarted(Context context) {
if (isAdded()) {
if (isProgressBarVisible()) {
showProgressBar(false);
}
if (!getActivity().isFinishing()) {
mProgressDialog.show();
}
}
}
#Override
public void onCleanCompleted(Context context, boolean succeeded) {
if (succeeded) {
mAppsListAdapter.trashItems();
}
if (isAdded()) {
updateStorageUsage();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
Toast.makeText(context, succeeded ? R.string.cleaned : R.string.toast_could_not_clean,
Toast.LENGTH_LONG).show();
if (succeeded && getActivity() != null && !mAlreadyCleaned &&
mSharedPreferences.getBoolean(mExitAfterCleanKey, false)) {
getActivity().finish();
}
}
}
It looks like there is an additional freeStorage() method added in Android 6 (Marshmallow) that takes an additional volumeUuid parameter:
public void freeStorage(long freeStorageSize, IntentSender pi)
public abstract void freeStorage(String volumeUuid, long freeStorageSize,
IntentSender pi)
Obviously, the new method is showing up first in the returned list of declared methods.
To get around this, you can alter the orginal code so that it looks like this:
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
Class[] params = m.getParameterTypes();
if (params.length == 2) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
}
Related
I am new to Android Studio and to BLE. I am working on a program that will scan for a beacon to read information. I am following this tutorial and the closest solution to my problem I found so far was this post. I am trying to get my app to respond to a button press by showing a list of devices that are available to connect through BLE. I keep running into this error from the LeDeviceListAdapter variable initialization...
Unresolved Reference: LeDeviceListAdapter
I figure that I need to add a class to my code, which I have tried to do directly from this source, but I was unsuccessful.
My question is, how do I add the class to my project if that's the solution and which file in the solution do I add it to? If that's not the solution, can someone help me pinpoint what it is?
Also, could it have something to do with the Android API I'm using for the project?
Here is my code...
view.findViewById<Button>(R.id.button_first).setOnClickListener {
val bluetoothManager: BluetoothManager = activity!!.getSystemService(BluetoothManager::class.java)
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
val text = "This device does not support BlueTooth"
val duration = Toast.LENGTH_SHORT
Toast.makeText(context, text, duration)
return#setOnClickListener
}
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner
var scanning = false
val handler = Handler()
// Stops scanning after 10 seconds.
val SCAN_PERIOD: Long = 10000
val leDeviceListAdapter = LeDeviceListAdapter()
// Device scan callback.
val leScanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
leDeviceListAdapter.addDevice(result.device)
leDeviceListAdapter.notifyDataSetChanged()
}
}
fun scanLeDevice() {
if (!scanning) { // Stops scanning after a pre-defined scan period.
handler.postDelayed({
scanning = false
bluetoothLeScanner.stopScan(leScanCallback)
}, SCAN_PERIOD)
scanning = true
bluetoothLeScanner.startScan(leScanCallback)
} else {
scanning = false
bluetoothLeScanner.stopScan(leScanCallback)
}
}
}
}
Thank you in advance!
I don't know if I understood correctly the question, but you need to create a new class file with the LeDeviceListAdapter class definition. Then you need to import it inside the file you are using it.
For some info about BLE you can check my question:
QUESTION
And my answer:
ANSWER
In my answer you can find a class (TagBLE and DataTagBLE) to manage the bluetooth device you find ^^ You can use it and implement a list of them to manage the results from your scan then use a RecyclerView with specific RecyclerView Adapter to show all the devices :D
If you need any help just ask me, I can provice you the code I'm using and explain it to you (: For example I can give you the services and activities I'm using to scan and retrieve BLE :D
Also check this answer:
Answer about LeDeviceListAdapter
I had the code for a service that do the background scan for the BLE and a Base Activity that manage getting the TAG INFO. You can use this for references or import it in your project. It will use a service to scan for the BLE and get the results in the activity
BaseTagsScanService.java:
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseTagsScanService extends Service {
private static final String TAG = BaseTagsScanService.class.getName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBLEScanner;
private ScanCallback mScanCallback;
private boolean mIsScanning;
/** Abstract Methods **/
protected abstract ScanSettings getScanSettings();
protected abstract List<ScanFilter> getScanFilters();
protected abstract void manageScanResult(ScanResult result);
protected abstract void onScanFail(int errorCode);
/** Override Lifecycle Methods **/
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
initBluetooth();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
initBluetooth();
return null;
}
#Override
public void onDestroy() {
unsetAll();
super.onDestroy();
}
/** Protected Methods **//** Init Methods **/
protected void initBluetooth(){
initBluetoothAdapter();
if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
initBluetoothLeScanner();
initBluetoothScanCallback();
}
}
/** Getter Methods **/
#Nullable
protected BluetoothAdapter getBluetoothAdapter(){
return mBluetoothAdapter;
}
#Nullable
protected BluetoothManager getBluetoothManager(){
return mBluetoothManager;
}
#Nullable
protected BluetoothLeScanner getBLEScanner(){
return mBLEScanner;
}
#Nullable
protected ScanCallback getScanCallback(){
return mScanCallback;
}
/** BLEScanner Methods **/
protected void unsetBLEScanner(){
if(mBLEScanner != null && mIsScanning && mBluetoothAdapter.isEnabled()){
mBLEScanner.stopScan(mScanCallback);
}
mBLEScanner = null;
}
/** Scan Methods **/
protected boolean isScanning(){
return mIsScanning;
}
protected void setIsScanning(boolean isScanning){
mIsScanning = isScanning;
}
protected boolean startScan(){
boolean ret = false;
if(checkStartScan()){
ret = true;
mIsScanning = true;
if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
mBLEScanner.startScan(getScanFilters(), getScanSettings(), mScanCallback);
}
}
return ret;
}
protected boolean stopScan(){
boolean ret = false;
if(checkStopScan()){
ret = true;
mIsScanning = false;
if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
mBLEScanner.stopScan(mScanCallback);
}
}
return ret;
}
/** ScanFilter Methods **/
protected List<ScanFilter> buildScanFilters(List<String> macs){
List<ScanFilter> scanFilters = new ArrayList<>();
if(macs != null && macs.size() > 0x0){
scanFilters = new ArrayList<>();
for(String mac : macs){
ScanFilter filter = new ScanFilter
.Builder()
.setDeviceAddress(mac)
.build();
scanFilters.add(filter);
}
} else {
scanFilters.add(new ScanFilter.Builder().build());
}
return scanFilters;
}
/** Private Methods **//** Init Methods **/
private void initBluetoothAdapter(){
mBluetoothManager = (BluetoothManager) getBaseContext().getSystemService(Context.BLUETOOTH_SERVICE);
if(mBluetoothManager != null){
mBluetoothAdapter = mBluetoothManager.getAdapter();
}
}
private void initBluetoothLeScanner(){
mBLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
private void initBluetoothScanCallback(){
mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
manageScanResult(result);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
onScanFail(errorCode);
Log.e("CheckInOut_Admin", "onScanFailed - errorCode = " + errorCode);
}
};
}
/** Unset Methods **/
private void unsetAll(){
unsetBLEScanner();
unsetBluetoothAdapter();
}
private void unsetBluetoothAdapter(){
mBluetoothAdapter = null;
mBluetoothManager = null;
}
/** Check Scan Methods **/
private boolean checkStartScan(){
return !mIsScanning && mBLEScanner != null;
}
private boolean checkStopScan(){
return mIsScanning && mBLEScanner != null;
}
}
TagsScanService.java:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import com.emax.it.lib_base.BaseConstants;
import com.emax.it.lib_base.BaseEnvironment;
import com.emax.it.lib_base.modules.handlers.MessageHandler;
import com.emax.it.lib_base.modules.handlers.MessageManager;
import com.emax.it.lib_base.ui.receivers.BluetoothStatusChangedReceiver;
import com.emax.it.lib_base.ui.receivers.ProviderStatusChangedReceiver;
import com.emax.it.lib_ble.base_activities.BaseTagsScanActivity;
import com.emax.it.lib_ble.models.TagBle;
import com.emax.it.lib_ble.services.base.BaseTagsScanService;
import com.emax.it.lib_ble.utils.BluetoothUtils;
import java.util.ArrayList;
import java.util.List;
public class TagsScanService extends BaseTagsScanService
implements BluetoothStatusChangedReceiver.IOnBluetoothStatusChanged,
ProviderStatusChangedReceiver.IOnProviderStatusChanged,
MessageHandler.IOnHandleMessage {
private static final String TAG = TagsScanService.class.getSimpleName();
// Messages Whats
public static final int MSG_WHAT_SCAN_START = 0x5C1;
public static final int MSG_WHAT_SCAN_STOP = 0x5C2;
public static final int MSG_WHAT_BLUETOOTH_OFF = 0x5C3;
public static final int MSG_WHAT_GPS_OFF = 0x5C4;
public static final int MSG_WHAT_BLE_TAG = 0x5C5;
// Messages Args
public static final int MSG_ARG_ONE_FAIL = 0x0;
public static final int MSG_ARG_ONE_SUCCESS = 0x1;
private BluetoothStatusChangedReceiver mBluetoothReceiver;
private ProviderStatusChangedReceiver mProviderReceiver;
private MessageManager mMessenger;
/** Override BaseTagsScanService Methods **/
#Override
protected ScanSettings getScanSettings(){
return new ScanSettings
.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
}
#Override
protected List<ScanFilter> getScanFilters(){
return new ArrayList<>();
}
#Override
protected void manageScanResult(ScanResult result) {
if(result != null){
BluetoothDevice device = result.getDevice();
if(!TextUtils.isEmpty(device.getAddress())){
sendTag(TagBle.initInstanceFromScanResult(result, BluetoothUtils.getBeaconTxPower(result)), result.getRssi());
}
}
}
#Override
protected void onScanFail(int errorCode) {
switch (errorCode){
case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
if(getBLEScanner() != null){
getBLEScanner().stopScan(getScanCallback());
getBLEScanner().startScan(getScanFilters(), getScanSettings(), getScanCallback());
}
break;
case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
if(getBluetoothAdapter() != null){
getBLEScanner().stopScan(getScanCallback());
getBluetoothAdapter().disable();
new Handler().postDelayed(() -> {
getBluetoothAdapter().enable();
new Handler().postDelayed(() -> getBLEScanner().startScan(getScanFilters(), getScanSettings(), getScanCallback()), BaseConstants.MILLIS_QUARTER_SECOND);
}, BaseConstants.MILLIS_QUARTER_SECOND);
}
break;
}
}
/** Override Lifecycle Methods **/
#Override
public void onCreate() {
super.onCreate();
initOnCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
initMessageManager();
return mMessenger.getMsgReceiver().getBinder();
}
#Override
public void onDestroy() {
unsetBluetoothStatusReceiver();
unsetProviderStatusReceiver();
super.onDestroy();
}
/** Override BluetoothStatusChangedReceiver.IOnBluetoothStatusChanged Methods **/
public void onBluetoothStatusChanged(int status){
if(status == BluetoothAdapter.STATE_TURNING_OFF){
stopScan();
sendBluetoothOff();
} else if(BluetoothUtils.checkBLE(this)){
initBluetooth();
}
}
/** Override ProviderStatusChangedReceiver.IOnProviderStatusChanged Methods **/
#Override
public void onProviderStatusChanged(int status) {
if(status == ProviderStatusChangedReceiver.IOnProviderStatusChanged.STATUS_DISABLED){
stopScan();
sendGpsOff();
} else if(BluetoothUtils.checkBLE(this)){
initBluetooth();
}
}
/** Override IOnHandleMessage Callback Methods **/
#Override
public void onHandleMessage(Message msg) {
switch(msg.what){
case MSG_WHAT_SCAN_START:
boolean started = startScan();
sendScanStarted(started ? MSG_ARG_ONE_SUCCESS : MSG_ARG_ONE_FAIL, msg.arg2);
break;
case MSG_WHAT_SCAN_STOP:
boolean stopped = stopScan();
sendScanStopped(stopped ? MSG_ARG_ONE_SUCCESS : MSG_ARG_ONE_FAIL, msg.arg2);
break;
}
}
/** Protected Methods **/
protected <T extends Parcelable> void sendTag(T tag, int rssi){
if(mMessenger != null){
Bundle data = new Bundle();
data.putParcelable(BaseTagsScanActivity.EXTRA_BLE_TAG, tag);
data.putInt(BaseTagsScanActivity.EXTRA_RSSI_VALUE, rssi);
mMessenger.sendMessage(MSG_WHAT_BLE_TAG, 0x0, 0x0, data);
}
}
protected MessageManager getMessenger(){
return mMessenger;
}
/** Private Methods **//** Init Methods **/
private void initOnCreate(){
initRegisterBluetoothStatusChangedReceiver();
initRegisterProviderStatusChangedReceiver();
}
private void initMessageManager(){
mMessenger = new MessageManager(this);
}
private void initRegisterBluetoothStatusChangedReceiver(){
initBluetoothAdapterReceiver();
registerBluetoothAdapterReceiver();
}
private void initRegisterProviderStatusChangedReceiver(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
initProviderStatusChangedReceiver();
registerProviderStatusChangedReceiver();
} else {
mProviderReceiver = null;
}
}
private void initBluetoothAdapterReceiver(){
mBluetoothReceiver = new BluetoothStatusChangedReceiver(this);
}
private void initProviderStatusChangedReceiver(){
mProviderReceiver = new ProviderStatusChangedReceiver(this);
}
/** Register Receivers Methods **/
private void registerBluetoothAdapterReceiver(){
if(mBluetoothReceiver != null && !mBluetoothReceiver.isRegistered()) {
registerReceiver(mBluetoothReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
mBluetoothReceiver.setIsRegistered(true);
}
}
private void registerProviderStatusChangedReceiver(){
if(mProviderReceiver != null && !mProviderReceiver.isRegistered()){
registerReceiver(mProviderReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
mProviderReceiver.setIsRegistered(true);
}
}
/** Unset Methods **/
private void unsetBluetoothStatusReceiver(){
if(mBluetoothReceiver != null) {
try {
unregisterReceiver(mBluetoothReceiver);
} catch (RuntimeException rE) {
BaseEnvironment.onExceptionLevelLow(TAG, rE);
}
mBluetoothReceiver = null;
}
}
private void unsetProviderStatusReceiver(){
if(mProviderReceiver != null){
try {
unregisterReceiver(mProviderReceiver);
} catch (RuntimeException rE){
BaseEnvironment.onExceptionLevelLow(TAG, rE);
}
mProviderReceiver = null;
}
}
/** Messenger Methods **/
private void sendScanStarted(int arg1, int arg2){
if(mMessenger != null ){
mMessenger.sendMessage(MSG_WHAT_SCAN_START, arg1, arg2, null);
}
}
private void sendScanStopped(int arg1, int arg2){
if(mMessenger != null){
mMessenger.sendMessage(MSG_WHAT_SCAN_STOP, arg1, arg2,null);
}
}
private void sendBluetoothOff(){
if(mMessenger != null){
mMessenger.sendMessage(MSG_WHAT_BLUETOOTH_OFF, 0x0, 0x0, null);
}
}
private void sendGpsOff(){
if(mMessenger != null){
mMessenger.sendMessage(MSG_WHAT_GPS_OFF, 0x0, 0x0, null);
}
}
}
BaseTagsScanActivity.java:
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.emax.it.lib_base.modules.handlers.MessageHandler;
import com.emax.it.lib_base.modules.handlers.MessageManager;
import com.emax.it.lib_base.ui.activities.BaseAppCompatActivity;
import com.emax.it.lib_ble.LibBleConstants;
import com.emax.it.lib_ble.R;
import com.emax.it.lib_ble.models.TagBle;
import com.emax.it.lib_ble.services.TagsScanService;
import com.emax.it.lib_ble.utils.BluetoothUtils;
public abstract class BaseTagsScanActivity extends BaseAppCompatActivity
implements MessageHandler.IOnHandleMessage,
BluetoothUtils.ICheckStatusBLE {
private static final String TAG = BaseTagsScanActivity.class.getSimpleName();
private static final String EXTRA = TAG + ".extra";
// Intents Extras
public static final String EXTRA_BLE_TAG = EXTRA + ".tagBLE";
public static final String EXTRA_RSSI_VALUE = EXTRA + ".valueRSSI";
protected Handler mScanHandler;
protected MessageManager mMessenger;
protected BLEScanServiceConnection mServiceConnection;
protected boolean mBound;
/** Override Lifecycle Methods **/
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initOnCreate();
}
#Override
protected void onStart() {
super.onStart();
BluetoothUtils.doFullCheckEnableBLE(this, this);
}
#Override
protected void onStop() {
super.onStop();
unbindToService();
}
#Override
protected void onDestroy() {
if(mScanHandler != null){
mScanHandler.removeCallbacksAndMessages(null);
mScanHandler = null;
}
mMessenger = null;
unbindToService();
stopTagsScanService();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LibBleConstants.REQ_PERMISSION_BLUETOOTH_LOCATION) {
if (grantResults.length > 0x0 && grantResults[0x0] == PackageManager.PERMISSION_GRANTED) {
BluetoothUtils.doFullCheckEnableBLE(this, this);
} else {
Toast.makeText(this, getString(R.string.error_permission_not_granted), Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case LibBleConstants.REQ_CODE_ENABLE_BT:
if(resultCode == RESULT_OK){
BluetoothUtils.doFullCheckEnableBLE(this, this);
} else {
finish();
}
break;
case LibBleConstants.REQ_CODE_BLE_ENABLE_GPS:
LocationManager lM = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lM != null && lM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
onSuccessCheckBLE();
} else {
Toast.makeText(this, getString(R.string.error_scan_tags_require_gps), Toast.LENGTH_LONG).show();
finish();
}
break;
}
}
/** Override Actionbar Listener Methods **/
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
/** Override ICheckStatusBLE Methods **/
#Override
public void onCheckStatusBleOk(){
onSuccessCheckBLE();
}
#Override
public void onCheckStatusBleError(int err) {
finish();
}
/** Protected Methods **/
protected void callBaseOnCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
protected void callBaseOnStart(){
super.onStart();
}
protected void initOnCreate(){
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
mBound = false;
initMyServiceConnection();
initScanHandler();
}
protected void initScanHandler(){
mScanHandler = new Handler();
}
/** Service Methods **/
protected void stopTagsScanService(){
stopService(new Intent(this, TagsScanService.class));
}
protected void bindToTagsScanService(){
bindService(new Intent(this, TagsScanService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
}
protected void unbindToService(){
if(mBound) {
unbindService(mServiceConnection);
mBound = false;
}
}
/** Scan Methods **/
protected void startScan(int arg1, int arg2, #Nullable Bundle data){
startScan(TagsScanService.MSG_WHAT_SCAN_START, arg1, arg2, data);
}
protected void startScan(int what, int arg1, int arg2, #Nullable Bundle data){
if(mMessenger != null){
mMessenger.sendMessage(what, arg1, arg2, data);
}
}
protected void stopScan(int arg1, int arg2, #Nullable Bundle data){
if(mMessenger != null){
mMessenger.sendMessage(TagsScanService.MSG_WHAT_SCAN_STOP, arg1, arg2, data);
}
}
protected void startScanHandler(Runnable runnable, long time){
if(mScanHandler == null){
initScanHandler();
}
mScanHandler.postDelayed(runnable, time);
}
/** Check Methods **/
protected boolean checkStartStopScan(){
boolean ret = false;
boolean checkBLE = BluetoothUtils.checkBLE(this);
if(mBound && checkBLE){
ret = true;
} else if(!mBound && checkBLE){
showMessageServiceError();
} else {
BluetoothUtils.doFullCheckEnableBLE(this, this);
}
return ret;
}
/** Handle Message Methods **/
protected void onHandleMessageBluetoothOff(){
BluetoothUtils.doFullCheckEnableBLE(this, this);
}
protected void onHandleMessageGpsOff(){
BluetoothUtils.doFullCheckEnableBLE(this, this);
}
protected <T extends Parcelable> T getTagBleFromBundle(Bundle data){
if(data != null && data.containsKey(EXTRA_BLE_TAG)){
return (T) data.getParcelable(EXTRA_BLE_TAG);
}
return null;
}
protected int getRssiFromBundle(Bundle data){
if(data != null && data.containsKey(BaseTagsScanActivity.EXTRA_RSSI_VALUE)){
return data.getInt(BaseTagsScanActivity.EXTRA_RSSI_VALUE, 0x0);
}
return 0x0;
}
/** Messages Methods **/
protected void showMessageServiceError(){
Toast.makeText(this, R.string.error_scan_service_not_started, Toast.LENGTH_SHORT).show();
}
protected void showMessageScanStartError(){
Toast.makeText(this, R.string.error_start_scan, Toast.LENGTH_LONG).show();
}
protected void showMessageScanStopError(){
Toast.makeText(this, R.string.error_stop_scan, Toast.LENGTH_SHORT).show();
}
/** Private Methods **//** Init Methods **/
private void initMyServiceConnection(){
mServiceConnection = new BLEScanServiceConnection();
}
private void initMyMessenger(IBinder iBinder){
mMessenger = new MessageManager(this, iBinder);
mMessenger.sendHandshake();
}
/** Service Methods **/
private void onSuccessCheckBLE(){
bindToTagsScanService();
}
/** Private Classes **/
protected class BLEScanServiceConnection implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
initMyMessenger(iBinder);
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mMessenger = null;
mBound = false;
}
}
}
Rest of code you have the classes in my answer above and the message handlers in this answer:
Message Handlers between service and activity
Looks like you haven't implemented correctly,
You first need to create a new class file with the name "LeDeviceListAdapter" in the same package.
Once you created this class, you need to import this class in your activity/fragment.
This adapter is using BaseAdapter class.
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
Layout File listitem_device.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2013 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/device_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"/>
<TextView android:id="#+id/device_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12dp"/>
</LinearLayout>
ViewHolder class inside the Adapter class file
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
I'm not even sure if this is the right thing to do any more with Google not supporting 'Google Now', but I can't seem to find any suitable alternative.
Using this https://antonioleiva.com/voice_search_google_now/#comment-8611 as a guide I am trying o implement a voice search in my App, but not having much luck.
I already have a search facility for users. What I have done so far:-
GlobalApplication.java
public static Queries getQueriesInstance(Context context) {
if(q == null) {
dbHelper = new DbHelper(context);
q = new Queries(db, dbHelper);
}
return q;
}
Then in MainActivity.java
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Intent i;
int id = item.getItemId();
...
...
if(id == R.id.nav_search) {
i = new Intent(this, SearchActivity.class);
startActivity(i);
}
...
...
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And finally, before adding anything, my SearchActivity.java file
package com.projects.activities;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.SpannableString;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.application.GlobalApplication;
import com.config.Config;
import com.db.Queries;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Deal;
import com.models.DealCategory;
import com.models.Status;
import com.projects.adapp.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity implements
GlobalApplication.OnLocationListener{
private AsyncTaskNoDialog task;
SeekBar seekBarRadius;
SwipeRefreshLayout swipeRefresh;
Queries q;
Button btnSearch;
ArrayList<DealCategory> selectedCategories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.activity_list_swipe_search);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.search);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
q = GlobalApplication.getQueriesInstance(this);
seekBarRadius = (SeekBar) findViewById(R.id.seekBarRadius);
seekBarRadius.setMax(Config.SEARCH_RADIUS_MAX_VALUE);
seekBarRadius.setProgress(Config.SEARCH_RADIUS_DEFAULT_VALUE);
seekBarRadius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) { }
#Override
public void onStartTrackingTouch(SeekBar arg0) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
updateRadius(progress);
}
});
updateRadius(seekBarRadius.getProgress());
selectedCategories = new ArrayList<DealCategory>();
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
FrameLayout frameCategory = (FrameLayout) findViewById(R.id.frameCategory);
frameCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SearchActivity.this, CategorySearchActivity.class);
startActivityForResult(i, Config.RESULT_CODE_CATEGORY);
}
});
seekBarRadius.setEnabled(false);
btnSearch.setEnabled(false);
if(!MGUtilities.isLocationEnabled(this) && GlobalApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
Toast.makeText(SearchActivity.this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
});
utils.showAlertView(
this,
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
refetch();
}
GlobalApplication app = (GlobalApplication)getApplication();
app.sendScreenView(Config.kGAIScreenNameSearch);
}
public void refetch() {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(this, this);
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(null, this);
seekBarRadius.setEnabled(true);
btnSearch.setEnabled(true);
}
#Override
public void onLocationRequestDenied() {
MGUtilities.showAlertView(this, R.string.permission_error, R.string.permission_error_details_location);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Config.RESULT_CODE_CATEGORY && resultCode == RESULT_OK) {
selectedCategories = (ArrayList<DealCategory>) data.getSerializableExtra("categories");
if(selectedCategories != null && selectedCategories.size() > 0) {
TextView tvCategory = (TextView) findViewById(R.id.tvCategory);
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += cat.getCategory();
if(x < selectedCategories.size() - 1)
cats += ", ";
}
if(!cats.isEmpty()) {
tvCategory.setText(cats);
}
else {
tvCategory.setText(R.string.all_categories);
}
}
}
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(this))
refetch();
else {
Toast.makeText(this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
}
}
public void updateRadius(int progress){
String strSeekVal = String.format("%d %s",
progress,
MGUtilities.getStringFromResource(SearchActivity.this, R.string.km));
TextView tvRadius = (TextView) findViewById(R.id.tvRadius);
tvRadius.setText(strSeekVal);
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
public void search() {
showRefresh(true);
beginParsing();
}
public ArrayList<Deal> searchLocal() {
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
int radius = seekBarRadius.getProgress();
int countParams = 0;
countParams += searchStr.length() > 0 ? 1 : 0;
countParams += radius > 0 ? 1 : 0;
countParams += selectedCategories != null && selectedCategories.size() > 0 ? 1 : 0;
ArrayList<Deal> array = q.getDeals();
ArrayList<Deal> results = new ArrayList<>();
for(Deal event : array) {
try {
int qualifyCount = 0;
if(searchStr.length() > 0) {
boolean isFound = searchStr.contains(event.getTitle()) ||
searchStr.contains(event.getAddress()) ||
searchStr.contains(event.getDesc()) ||
event.getTitle().contains(searchStr) ||
event.getAddress().contains(searchStr) ||
event.getDesc().contains(searchStr);
if(isFound)
qualifyCount += 1;
}
if(GlobalApplication.currentLocation != null) {
Location loc1 = new Location("Loc1");
loc1.setLatitude(event.getLat());
loc1.setLongitude(event.getLon());
Location loc2 = new Location("Loc2");
loc2.setLatitude(GlobalApplication.currentLocation.getLatitude());
loc2.setLongitude(GlobalApplication.currentLocation.getLongitude());
double distance = loc1.distanceTo(loc2) * Config.METERS_TO_KM;
event.setDistance(distance);
if(distance <= radius)
qualifyCount += 1;
}
ObjectMapper mapper = new ObjectMapper();
DataResponse categories = mapper.readValue(event.getCategories(), DataResponse.class);
if(categories != null && categories.getCategories() != null) {
for(DealCategory cat : categories.getCategories()) {
boolean isFound = false;
for(DealCategory selectedCat : selectedCategories) {
if(selectedCat.getCategory_id() == cat.getCategory_id()) {
isFound = true;
break;
}
}
if(isFound) {
qualifyCount += 1;
break;
}
}
}
if(qualifyCount == countParams)
results.add(event);
}
catch(Exception e) {
e.printStackTrace();
}
}
return results;
}
public void beginParsing() {
if(task != null)
task.cancel(true);
task = new MGAsyncTaskNoDialog(this);
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
DataResponse response;
ArrayList<Deal> events;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
updateData(response, events);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(MGUtilities.hasConnection(SearchActivity.this)) {
response = syncData();
}
else{
events = searchLocal();
}
}
});
task.execute();
}
public DataResponse syncData() {
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += String.valueOf(cat.getCategory_id());
if (x < selectedCategories.size() - 1)
cats += ",";
}
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
double radius = seekBarRadius.getProgress() * Config.KM_TO_MILES;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keywords", searchStr ));
params.add(new BasicNameValuePair("lat", String.valueOf(GlobalApplication.currentLocation.getLatitude()) ));
params.add(new BasicNameValuePair("lon", String.valueOf(GlobalApplication.currentLocation.getLongitude()) ));
params.add(new BasicNameValuePair("category_ids", cats) );
params.add(new BasicNameValuePair("radius", String.valueOf(radius)) );
params.add(new BasicNameValuePair("api_key", Config.API_KEY ));
GlobalApplication.params = params;
DataResponse response = DataParser.getJSONFromUrlWithPostRequest(Config.SEARCH_DEALS_JSON_URL, params);
return response;
}
public void updateData(DataResponse response, ArrayList<Deal> deals) {
showRefresh(false);
if(response != null) {
Status status = response.getStatus();
if(status.getStatus_code() == -1 && response.getDeals() != null ) {
if(response.getDeals().size() == 0) {
Toast.makeText(SearchActivity.this, R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", response.getDeals());
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, status.getStatus_text());
}
}
else if(deals != null && deals.size() > 0) {
GlobalApplication.params = null;
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", deals);
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, R.string.problems_encountered_while_syncing);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
// Handle action bar actions click
switch (item.getItemId()) {
default:
finish();
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(android.view.Menu menu) {
// if nav drawer is opened, hide the action items
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onDestroy() {
super.onDestroy();
if(task != null)
task.cancel(true);
}
}
Taken from the tutorial link above, I then added the following to my Manifest
AndroidManifest.xml
<activity
android:name="com.projects.activities.SearchActivity">
<intent-filter>
<action android:name="com.google.android.gms.actions.SEARCH_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I then added the following to my SearchActivity.java file
private static final String ACTION_VOICE_SEARCH =
"com.google.android.gms.actions.SEARCH_ACTION";
private void handleVoiceSearch(Intent intent) {
if (intent != null && ACTION_VOICE_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
setSearchViewVisible(true);
searchView.setQuery(query, true);
}
}
The in various places and in slightly different ways, I have tried adding
handleVoiceSearch(getIntent());
to the SearchActivity.java file, but I don't seem to be having much luck. I am testing from an Alpha version uploaded to Play Store.
Is there anything obvious anyone can see I am missing?
Thanks
I need to create 3 custom Cordova WebView using Cordova Android 5.1.0. Previously I have succeeded to create custom WebView using Cordova Android 2.7 by modifying/overwriting file platform/android/src/com/hello/helloapp.java. Below is my previous code:
package com.hello.helloapp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import com.hello.helloapp.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class HelloApp extends Activity implements CordovaInterface {
int SCREEN_WIDTH;
int SCREEN_HEIGHT;
static String parentUrl;;
CordovaWebView view2;
CordovaWebView view1;
CordovaWebView view3;
static String htmlStr;
LinearLayout layout;
boolean connectionStatus;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Config.init(this);
this.getScreenSize();
view1 = (CordovaWebView) findViewById(R.id.local_web_view);
view1.loadUrl("file:///android_asset/www/index.html");
view2 = (CordovaWebView) findViewById(R.id.external_web_view);
view2.loadUrl("http://google.com");
view2.requestFocus(WebView.FOCUS_DOWN);
view2.setWebViewClient(new MyWebViewClient(this, view2));
view3 = (CordovaWebView) findViewById(R.id.articles_web_view);
view3.loadUrl("file:///android_asset/www/articles.html");
view2.addJavascriptInterface(this, "GetHTML");
layout = (LinearLayout) findViewById(R.id.progressBar);
if (!isTabletDevice(this)) {
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (isAirplaneModeOn(this)) {
connectionStatus = false;
} else if (isNetworkOnline()) {
connectionStatus = true;
} else
connectionStatus = false;
System.out.println(connectionStatus);
if (!connectionStatus) {
view2.setVisibility(View.GONE);
view3.loadUrl("file:///android_asset/www/articles.html");
view3.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isNetworkOnline() {
boolean status = false;
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
NetworkInfo netInfo1 = cm.getNetworkInfo(1);
if ((netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
|| (netInfo1 != null && netInfo1.getState() == NetworkInfo.State.CONNECTED)) {
status = true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println(status);
return status;
}
public static boolean isTabletDevice(Context activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
#SuppressWarnings("deprecation")
private static boolean isAirplaneModeOn(Context context)
throws SettingNotFoundException {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
#Override
public Activity getActivity() {
return this;
}
#Override
public ExecutorService getThreadPool() {
return threadPool;
}
public void getScreenSize() {
Display display = getWindowManager().getDefaultDisplay();
SCREEN_WIDTH = display.getWidth();
SCREEN_HEIGHT = display.getHeight();
}
public class MyWebViewClient extends CordovaWebViewClient {
private CordovaInterface cordova;
public MyWebViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
this.cordova = ctx;
}
#Override
public void onReceivedError(WebView arg0, int arg1, String arg2,
String arg3) {
arg0.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
}
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
connectionStatus = isNetworkOnline();
System.out.println(connectionStatus);
if (connectionStatus) {
System.out.println("---------shouldoverride-------" + url);
if (url.contains(".pdf")&& !url.contains("originUrl")) {
System.out.println(HelloApp.htmlStr);
view1.loadUrl("javascript:downloadFile(\"" + url + "\",\""
+ HelloApp.htmlStr + "\",\"" + HelloApp.parentUrl
+ "\");");
return false;
} else if (url.contains("search?")
&& HelloApp.parentUrl
.equalsIgnoreCase("http://google.com/")) {
System.out.println("parenturl");
url = url.concat("&showAll=false");
view2.loadUrl(url);
return false;
} else {
return false;
}
} else {
view1.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layout.setVisibility(View.VISIBLE);
if (url.contains(".pdf")) {
}else {
HelloApp.parentUrl = url;
if (view2.canGoBack() && view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1B_1\")");
} else if (view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1\")");
} else if (view2.canGoBack()) {
view1.loadUrl("javascript:callBackFun(\"B_1\")");
}
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains(".pdf")) {
} else {
System.out.println("----------------" + url);
view2.loadUrl("javascript: GetHTML.getHtml(document.body.innerHTML);");
view2.loadUrl("javascript: $(\".content-pricing\").hide()");
view2.loadUrl("javascript: $(\"a[href*='mailto']\").removeAttr('href');");
System.out.println("REMOVE------------------------>>>");
view2.loadUrl("javascript:$('head').append('<style>#coverImageUrl, .content-pricing, .price-disclaimer {display : none;}</style>')");
layout.setVisibility(View.INVISIBLE);
}
}
}
public Object onMessage(String arg0, Object arg1) {
return null;
}
#Override
public void setActivityResultCallback(CordovaPlugin arg0) {
}
#Override
public void startActivityForResult(CordovaPlugin arg0, Intent arg1, int arg2) {
}
#JavascriptInterface
public void getHtml(String html) {
this.htmlStr = html.replace("\"", "\'").replaceAll("\n", "").replaceAll("%22", "\'").trim();
}
}
Now there is lots of update in Cordova, they also update there CordovaWebView code. After updating Cordova Android version from 2.7 to 5.1.0, app is crashed. I tried to use SystemWebView instead of CordovaWebView but still get error and crashes as some of methods are missing in SystemWebView.
Please help how can I update previous WebView code or create new multiple WebView in Cordova 5.1.0.
Thanks!!
This is how I implemented new Cordova library in my existing project.
public class MyWebViewFragment extends Fragment{
private Activity mActivity;
private SystemWebView syswvPhoneWebview;
private CordovaWebView wvPhoneWebview;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (mView == null) {
mView = inflater.inflate(R.layout.fragment_web_view, null);
setLayoutViews(mView);
}
return mView;
}
private void setLayoutViews(View mView) {
syswvPhoneWebview = (SystemWebView) mView.findViewById(R.id.wvPhoneWebview);
wvPhoneWebview = new CordovaWebViewImpl(new SystemWebViewEngine(syswvPhoneWebview));
wvPhoneWebview.init((CordovaInterface) getParentFragment(), parser.getPluginEntries(), parser.getPreferences());
syswvPhoneWebview.setWebContentsDebuggingEnabled(true);
syswvPhoneWebview.getSettings().setLoadsImagesAutomatically(true);
syswvPhoneWebview.getSettings().setJavaScriptEnabled(true);
syswvPhoneWebview.getSettings().setDomStorageEnabled(true);
syswvPhoneWebview.getSettings().setBuiltInZoomControls(true);
syswvPhoneWebview.getSettings().setSupportZoom(true);
wvPhoneWebview.loadUrl("www.google.com");
SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) wvPhoneWebview.getEngine();
syswvPhoneWebview.setWebViewClient(new DocumentViewClient(systemWebViewEngine, mActivity));
}
}
now webviewclient code.
public class DocumentViewClient extends SystemWebViewClient {
private final Activity activity;
public DocumentViewClient(SystemWebViewEngine parentEngine, Activity activity) {
super(parentEngine);
this.activity = activity;
}
}
I am migrating search view Item provided in action bar using support library .Here I have done as mentioned in doc but still it is giving error while creating options menu.Please tell me where I have done wrong.Here is my code.
contacts_list_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.utteru.ui="http://schemas.android.com/apk/res-auto"
xmlns:yourapp="http://schemas.android.com/tools">
<!-- The search menu item. Honeycomb and above uses an ActionView or specifically a SearchView
which expands within the Action Bar directly. Note the initial collapsed state set using
collapseActionView in the showAsAction attribute. -->
<group
android:id="#+id/main_menu_group">
<item
android:id="#+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
<group
android:id="#+id/refresh_group">
<item
android:id="#+id/refresh"
android:icon="#android:drawable/ic_popup_sync"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
</menu>
ContactsListFragment.java
import android.accounts.Account;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Photo;
import android.support.v4.BuildConfig;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ContactsListFragment extends ListFragment {
private static final String TAG = "ContactsAccessFragment";
private static final String STATE_PREVIOUSLY_SELECTED_KEY =
"com.Utteru.ui.SELECTED_ITEM";
ArrayList<AccessContactDto> allcontacts;
ArrayList<AccessContactDto> databasecontacts;
TextView textempty;
public Context mContext;
private AccessContactAdapter mAdapter;
private ImageLoader mImageLoader; // Handles loading the contact image in a background thread
// Stores the previously selected search item so that on a configuration change the same item
// can be reselected again
private int mPreviouslySelectedSearchItem = 0;
// Whether or not the search query has changed since the last time the loader was refreshed
private boolean mSearchQueryChanged;
// Whether or not this fragment is showing in a two-pane layout
private boolean mIsTwoPaneLayout;
// Whether or not this is a search result view of this fragment, only used on pre-honeycomb
// OS versions as search results are shown in-line via Action Bar search from honeycomb onward
private boolean mIsSearchResultView = false;
/**
* Fragments require an empty constructor.
*/
public ContactsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIsTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
getActivity().setTitle("");
if (savedInstanceState != null) {
// If we're restoring state after this fragment was recreated then
// retrieve previous search term and previously selected search
// result.
mPreviouslySelectedSearchItem =
savedInstanceState.getInt(STATE_PREVIOUSLY_SELECTED_KEY, 0);
}
mImageLoader = new ImageLoader(getActivity(), CommonUtility.getListPreferredItemHeight(getActivity())) {
#Override
protected Bitmap processBitmap(Object data) {
// This gets called in a background thread and passed the data from
// ImageLoader.loadImage().
return loadContactPhotoThumbnail((String) data, getImageSize());
}
};
// Set a placeholder loading image for the image loader
mImageLoader.setLoadingImage(R.drawable.ic_contact_picture_holo_light);
// Add a cache to the image loader
mImageLoader.addImageCache(getActivity().getSupportFragmentManager(), 0.1f);
mContext = getActivity().getBaseContext();
new loadData().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the list fragment layout
View all_contacts_view = inflater.inflate(R.layout.contact_list_fragment, container, false);
textempty = (TextView)all_contacts_view.findViewById(android.R.id.empty);
textempty.setText("No contacts found");
return all_contacts_view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
AccessContactDto cdto = (AccessContactDto) l.getItemAtPosition(position);
Log.e("number on click",""+cdto.getMobile_number());
cdto=UserService.getUserServiceInstance(mContext).getAccessConDataByNumber(cdto.getMobile_number());
if(cdto==null)
cdto = (AccessContactDto) l.getItemAtPosition(position);
else
Log.e("mumber not mull from db","number not null from db");
Intent detailsActivity = new Intent(mContext, ContactDetailActivity.class);
detailsActivity.putExtra("selected_con", cdto);
startActivity(detailsActivity);
getActivity().overridePendingTransition(R.anim.animation1, R.anim.animation2);
super.onListItemClick(l, v, position, id);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Let this fragment contribute menu items
setHasOptionsMenu(true);
// Set up ListView, assign adapter and set some listeners. The adapter was previously
// created in onCreate().
setListAdapter(mAdapter);
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause image loader to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.setPauseWork(true);
} else {
mImageLoader.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
if (mIsTwoPaneLayout) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mPreviouslySelectedSearchItem == 0) {
}
}
#Override
public void onPause() {
super.onPause();
mImageLoader.setPauseWork(false);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.contact_list_menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
menu.setGroupVisible(R.id.main_menu_group, true);
if (mIsSearchResultView) {
searchItem.setVisible(false);
}
if (Utils.hasHoneycomb()) {
final SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("on query text change ","on query text change");
if (newText != null && !newText.equals(""))
{
ArrayList<AccessContactDto> filterList = new ArrayList<AccessContactDto>();
for (AccessContactDto a : allcontacts) {
if (a.getDisplay_name().toLowerCase().startsWith(newText.toLowerCase())) {
filterList.add(a);
continue;
}
getListView().setAdapter(new AccessContactAdapter(filterList, getActivity(), mImageLoader));
}
return true;
}
else{
getListView().setAdapter(new AccessContactAdapter(allcontacts, getActivity(), mImageLoader));
return true;
}
}
});
}
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!Utils.hasHoneycomb()) {
getActivity().onSearchRequested();
}
break;
case R.id.refresh:
if (CommonUtility.isNetworkAvailable(getActivity())) {
final Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle);
mAdapter.notifyDataSetChanged();
// new CountDownTimer(5000, 1000) {
// #Override
// public void onTick(long millisUntilFinished) {
// }
//
// #Override
// public void onFinish() {
//
// }
// }.start();
} else {
Toast.makeText(getActivity(), "Internet Connection Required!!", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
if (!isAdded() || getActivity() == null) {
return null;
}
AssetFileDescriptor afd = null;
try {
Uri thumbUri;
if (Utils.hasHoneycomb()) {
thumbUri = Uri.parse(photoData);
} else {
final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
}
afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
FileDescriptor fileDescriptor = afd.getFileDescriptor();
if (fileDescriptor != null) {
return ImageLoader.decodeSampledBitmapFromDescriptor(
fileDescriptor, imageSize, imageSize);
}
} catch (FileNotFoundException e) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
+ ": " + e.toString());
}
} finally {
if (afd != null) {
try {
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public ArrayList<AccessContactDto> readContactsNew() {
ArrayList<AccessContactDto> list = new ArrayList<AccessContactDto>();
AccessContactDto adto;
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photouri= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
String contact_id= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
Uri con_uri= Contacts.getLookupUri(phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)), phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY)));
adto = new AccessContactDto(contact_id, name, null, phoneNumber, null, photouri, con_uri.toString(),null,null,null);
list.add(adto);
}
phones.close();
return list;
}
public class loadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void aVoid) {
mAdapter = new AccessContactAdapter(allcontacts, getActivity(), mImageLoader);
if(getActivity()!=null)
getListView().setAdapter(mAdapter);
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... params) {
allcontacts = readContactsNew();
// databasecontacts = UserService.getUserServiceInstance(mContext).getAllAccessContacts();
// allcontacts.removeAll(databasecontacts);
// allcontacts.addAll(databasecontacts);
Collections.sort(allcontacts, new Comparator<AccessContactDto>() {
#Override
public int compare(AccessContactDto lhs, AccessContactDto rhs) {
return lhs.getDisplay_name().compareToIgnoreCase(rhs.getDisplay_name());
}
});
return null;
}
}
}
ContactsListActivity.java
import android.accounts.AccountManager;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import com.viewpagerindicator.IconPagerAdapter;
public class ContactsListActivity extends ActionBarActivity {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
private ContactDetailFragment mContactDetailFragment;
private boolean isTwoPaneLayout;
AccountManager mAccountManager;
Boolean checkAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(R.color.purple));
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
pagerTabStrip.setTextSpacing(0);
pagerTabStrip.setPadding(0, 0, 0, 10);
pagerTabStrip.setTextSize(1, 20);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.remove("android:support:fragments");
}
#Override
public void onBackPressed() {
startActivity(new Intent(ContactsListActivity.this, MenuScreen.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK));
this.finish();
overridePendingTransition(R.anim.card_rotate_in, R.anim.card_rotate_out);
}
#Override
protected void onDestroy() {
if(CommonUtility.dialog!=null){
CommonUtility.dialog.dismiss();
}
super.onDestroy();
}
#Override
public boolean onSearchRequested() {
boolean isSearchResultView = false;
return !isSearchResultView && super.onSearchRequested();
}
public static class DemoCollectionPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[]{"All Contacts", "Access Contacts"};
protected final int[] ICONS = new int[]{
R.drawable.all_contact,
R.drawable.access_contacts
};
private int mCount = CONTENT.length;
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// All Contacts Fragment
return new ContactsListFragment();
case 1:
// Access Contacts Fragment
return new ContactsAccessFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return DemoCollectionPagerAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
}
Error Log:
java.lang.NullPointerException
at com.hello.ContactsListFragment.onPrepareOptionsMenu(ContactsListFragment.java:236)
at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1882)
at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:2020)
at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:459)
at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:280)
at android.support.v7.app.ActionBarActivityDelegate$1.onPreparePanel(ActionBarActivityDelegate.java:84)
at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:1006)
at android.support.v7.app.ActionBarActivityDelegateBase.doInvalidatePanelMenu(ActionBarActivityDelegateBase.java:1182)
at android.support.v7.app.ActionBarActivityDelegateBase.access$100(ActionBarActivityDelegateBase.java:79)
at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:115)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
I have many customview in the scrollview. I have implemented swipe feature on the the customview . When I swipe customview to left , scrollview also move vertical. I don't want scroll view to be moved vertical while swiping. I thing Action_Cancel event of touch is going to scrollview which I have to stop. I tried to stop it but it is not working .
Below is the
package com.AA.KK.customui;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.AA.ax4mobile.AAPreferences;
import com.AA.ax4mobile.Constants;
import com.AA.ax4mobile.Session;
import com.AA.ax4mobile.Utils;
import com.AA.ax4mobile.network.Network;
import com.AA.ax4mobile.network.NetworkResponseListener;
import com.AA.KK.R;
import com.AA.KK.activities.KKBaseActivity;
import com.AA.KK.activities.PDFViewerActivity;
public class MailLayout extends RelativeLayout implements OnClickListener, OnTouchListener,
GestureDetector.OnGestureListener {
private CheckBox checkBox;
private TextView title;
private TextView fileSize;
private ImageView fileIcon;
private ImageView tray;
private String url;
private String fileId;
private ViewGroup swipeView;
private boolean isPreview;
private boolean isSelected = true;
private GestureDetectorCompat mDetector;
private static final int SWIPE_OFFSET = 20;
private static final int ANIMATION_OFFSET= 30;
public MailLayout(Context context) {
super(context);
init(context);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.activity_mail_layout, this);
LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(linLayoutParam);
swipeView = (RelativeLayout) findViewById(R.id.swipe);
swipeView.setOnTouchListener(this);
title = (TextView) findViewById(R.id.file_name);
fileIcon = (ImageView) findViewById(R.id.file_image);
fileSize = (TextView) findViewById(R.id.file_size);
tray = (ImageView) findViewById(R.id.clickme);
tray.setOnClickListener(this);
checkBox = (CheckBox) findViewById(R.id.chk_checkBox);
mDetector = new GestureDetectorCompat(Utils.getInstance().getContext(), this);
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public boolean isPreview() {
return isPreview;
}
public void setPreview(boolean isPreview) {
this.isPreview = isPreview;
}
public ViewGroup getSwipeView() {
return swipeView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public void setTitleText(String text) {
title.setText(text);
}
public String getTitleText() {
return (String) title.getText();
}
public void setFileSize(String text) {
fileSize.setText(text);
}
public void setChecked(boolean checked) {
checkBox.setChecked(checked);
}
public boolean getChecked() {
return checkBox.isChecked();
}
public void setFileIcon(String fileName) {
if (fileName.contains(".pdf") || fileName.contains(".PDF")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_pdf_selected);
} else if (fileName.contains(".docx") || fileName.contains(".DOCX")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_docx_selected);
} else if (fileName.contains(".doc") || fileName.contains(".DOC")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_doc_selected);
} else if (fileName.contains(".ppt") || fileName.contains(".PPT")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_ppt_selected);
} else if (fileName.contains(".pptx") || fileName.contains(".PPTX")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_pptx_selected);
} else if (fileName.contains(".png") || fileName.contains(".PNG")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_png_selected);
} else if (fileName.contains(".gif") || fileName.contains(".GIF")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_gif_selected);
} else if (fileName.contains(".csv") || fileName.contains(".CSV")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_csv_selected);
} else if (fileName.contains(".bmp") || fileName.contains(".BMP")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_bmp_selected);
} else if (fileName.contains(".txt") || fileName.contains(".TXT")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_txt_selected);
} else if (fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".JPG")
|| fileName.contains(".JPEG")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_jpg_selected);
} else if (fileName.contains(".xls") || fileName.contains(".XLS")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_xls_selected);
} else if (fileName.contains(".xlsx") || fileName.contains(".XLXS")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_xlsx_selected);
} else {
fileIcon.setBackgroundResource(R.drawable.ic_file_selected);
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener) {
checkBox.setOnCheckedChangeListener(listener);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickme:
doAddToTray(getFileId());
break;
}
}
public void setFileId(String fileId) {
this.fileId = fileId;
// TODO Auto-generated method stub
}
public String getFileId() {
return fileId;
}
public static void dismissProgress() {
Message msg = new Message();
msg.what = Constants.UIMSG_HIDE_PROGRESSDIALOG;
Bundle data = new Bundle();
data.putStringArray("caller", Utils.getInstance().getStackTraceArray());
msg.setData(data);
Session.getInstance().getMsgHandler().sendMessage(msg);
}
public static void showProgress() {
String message = Utils.getInstance().getContext().getString(R.string.loading);
Message msg = new Message();
msg.what = Constants.UIMSG_SHOW_PROGRESSDIALOG;
Bundle data = new Bundle();
data.putString("message", message);
data.putStringArray("caller", Utils.getInstance().getStackTraceArray());
msg.setData(data);
Session.getInstance().getMsgHandler().sendMessage(msg);
}
public static void doAddToTray(final String ids) {
AAPreferences settings = AAPreferences.getPreferences(Utils.getInstance().getContext());
String accToken = settings.getString(Constants.REQUEST_KEY_ACCESS_TOKEN, null);
String servername = settings.getString(Constants.REQUEST_KEY_SERVERNAME, null);
JSONObject req = new JSONObject();
Network net = Network.getInstance();
try {
req.accumulate(Constants.REQUEST_KEY_ACCESS_TOKEN, accToken);
req.accumulate(Constants.REQUEST_KEY_SERVERNAME, servername);
req.accumulate(Constants.REQUEST_KEY_ID, ids);
req.accumulate(Constants.REQUEST_KEY_PARENT_ID, "");
showProgress();
NetworkResponseListener listener = new NetworkResponseListener() {
#Override
public void handleSuccessResponse(List<NameValuePair> request, JSONObject response, boolean cancelflag) {
dismissProgress();
Toast.makeText(Utils.getInstance().getContext(), R.string.file_added_to_move_tray,
Toast.LENGTH_LONG).show();
String count = null;
try {
JSONObject json = response.getJSONObject("payload");
count = json.getString("total_count");
if (!TextUtils.isEmpty(count))
Utils.getInstance().saveTrayCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(Constants.ACTION_UPDATE_TRAY);
LocalBroadcastManager.getInstance(Utils.getInstance().getContext()).sendBroadcast(intent);
}
#Override
public void handleErrorResponse(List<NameValuePair> request, JSONObject response, boolean cancelflag) {
dismissProgress();
String count = null;
try {
JSONObject json = response.getJSONObject("payload");
count = json.getString("total_count");
Utils.getInstance().saveTrayCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(Constants.ACTION_UPDATE_TRAY);
LocalBroadcastManager.getInstance(Utils.getInstance().getContext()).sendBroadcast(intent);
Message msg = Network.defaultErrorManager(request, response);
if (msg != null) {
KKBaseActivity.defaultUIHandler.sendMessage(msg);
}
}
};
net.linkTray(req, listener);
} catch (JSONException e) {
e.printStackTrace();
}
};
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// TODO Auto-generated method stub
Log.e("onFling", "event"+e1.getAction());
if (swipeView.getX() > -(tray.getWidth() + SWIPE_OFFSET)) {
swipeView.animate().translationX(0).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
} else {
if (isPreview) {
swipeView.animate().translationX(0).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
} else {
swipeView.animate().translationX(-(tray.getWidth() + SWIPE_OFFSET)).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
}
}
return false;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// TODO Auto-generated method stub
if (isSelected) {
if (swipeView.getX() <= 0)
swipeView.setX(e2.getX() - e1.getX() + swipeView.getX());
}
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
String s = getUrl();
if (getUrl() == "" || getUrl() == null || getUrl().equalsIgnoreCase("null")) {
Toast.makeText(Utils.getInstance().getContext(), "File is not viewable", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(Utils.getInstance().getContext(), PDFViewerActivity.class);
intent.putExtra("filename", getTitleText());
intent.putExtra("view_url", getUrl());
intent.putExtra("preview_from_notification", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Utils.getInstance().getContext().startActivity(intent);
}
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("onTouch", "event"+event.getAction());
boolean flag;
if (isPreview) {
tray.setVisibility(View.INVISIBLE);
} else {
tray.setVisibility(View.VISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
flag = onFling(event, event, 0f, 0f);
} else {
flag = mDetector.onTouchEvent(event);
}
return flag;
}
/* #Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.e("onTouchEvent", "event"+event.getAction());
return super.onTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev){
Log.e("dispatchTouchEvent", "event"+ev.getAction());
if(ev.getAction()== 3)
return false;
else
return super.dispatchTouchEvent(ev);
}*/
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
Log.e("onInterceptTouchEvent", "event"+ev.getAction());
return true;
}
}
in your onScroll()
put this -
ViewParent parent = getParent();
if(parent!= null){
parent.requestDisallowOnInterceptTouchEvent(true);
}