I have a fragment where when a User inputs a link and hits the button, a service is initiated which processes the link and grabs image or videos if there are any on the url...
But my problem is that the same is downloaded more than once like 2 to 3 times..
here is the fragment -
public class FragmentTwo extends Fragment {
FloatingActionButton btn;
EditText et1;
String profilname;
ProgressDialog pd;
private ArrayList<Long> mDownloadIds = new ArrayList<>();
public FragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two,container, false);
getActivity().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(myReceiver, new IntentFilter(Constants.BROADCAST_ACTION));
FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.button1);
EditText et1 = (EditText) rootView.findViewById(R.id.editText1);
pd = new ProgressDialog(getActivity());
pd.setMessage("Let us Check");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText et1 = (EditText)
getView().findViewById(R.id.editText1);
profilname = et1.getText().toString();
((InputMethodManager) getActivity().getSystemService("input_method")) .hideSoftInputFromWindow(et1.getWindowToken(), 0);
profilname.replace("https://www.instagram.com/","https://instagram.com/");
if (profilname.trim().equals("")){
Toast.makeText(getActivity(), "Link is Blank!", 0)
.show();
}
else if(isNetworkAvailable()){
Toast.makeText(getActivity(), profilname, 0)
.show();
DownloaderService.startActionFoo(getActivity(), profilname);
pd.show();
}
else{
Toast.makeText(getActivity(), "Network Error", 0)
.show();
}
}
});
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ContentValues contentValues = intent.getParcelableExtra(Constants.MEDIA_INFO);
String mediaUrl = contentValues.getAsString(Constants.MEDIA_URL);
String mediaName = contentValues.getAsString(Constants.MEDIA_NAME);
pd.dismiss();
download(mediaUrl, mediaName);
EditText et1 = (EditText)
getView().findViewById(R.id.editText1);
et1.setText("");
}
};
private BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long enqueueId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mDownloadIds.contains(enqueueId)) {
/* if (mBtnDownload.getVisibility() == View.VISIBLE) {
mBtnDownload.setVisibility(View.GONE);
}*/
getActivity().getLoaderManager().getLoader(0);
}
}
};
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(myReceiver);
getActivity().unregisterReceiver(onComplete);
super.onDestroy();
}
private void download(String url, String fileName) {
File root = Environment.getExternalStorageDirectory();
File myDir = new File(root + "/MCD/");
myDir.mkdirs();
DownloadManager mDownloadManager = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
if (!doesRequestExist(mDownloadManager, url)) {
/* boolean allowedOverMetered = mSettings.getBoolean(PREF_KEY_NETWORK, true);*/
int networkType = NETWORK_WIFI | NETWORK_MOBILE;
/* if (allowedOverMetered) {
networkType = NETWORK_WIFI | NETWORK_MOBILE;
}*/
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(root + "/MCD/", fileName);
request.setAllowedNetworkTypes(networkType);
long id = mDownloadManager.enqueue(request);
mDownloadIds.add(id);
}
}
private boolean doesRequestExist(DownloadManager downloadManager, String url) {
boolean result = false;
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL
| DownloadManager.STATUS_PENDING
| DownloadManager.STATUS_RUNNING);
Cursor cursor = downloadManager.query(query);
while (cursor.moveToNext()) {
int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
String uri = cursor.getString(uriIndex);
if (uri.equals(url)) {
result = true;
break;
}
}
cursor.close();
return result;
}
}
here's the Downloader Service -
public class DownloaderService extends IntentService {
private static final String ACTION_FOO = "com.parrotainment.media.downloader.action.FOO";
private static final String EXTRA_URL = "com.parrotainment.media.downloader.extra.URL";
public DownloaderService() {
super("DownloaderService");
}
public static void startActionFoo(Context context, String url) {
Intent intent = new Intent(context, DownloaderService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_URL, url);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String url = intent.getStringExtra(EXTRA_URL);
handleActionFoo(url);
}
}
}
private void handleActionFoo(String urlStr) {
try {
ContentValues mediaInfo = new ContentValues();
Document doc = Jsoup.connect(urlStr).timeout(5000).get();
Document content = Jsoup.parse(doc.toString());
String videoUrl = content.getElementsByAttributeValue("property","og:video")
.attr("content");
String title = content.getElementsByAttributeValue("property","og:title")
.attr("content").replaceAll("[^a-zA-Z0-9\\u4E00-\\u9FA5\\s]","");
if (!videoUrl.isEmpty()) {
String videoName = title + ".mp4";
mediaInfo.put(Constants.MEDIA_NAME, videoName);
mediaInfo.put(Constants.MEDIA_URL, videoUrl);
} else {
String imgUrl = content.getElementsByAttributeValue("property","og:image").attr("content");
String imgName = title + ".jpg";
mediaInfo.put(Constants.MEDIA_NAME, imgName);
mediaInfo.put(Constants.MEDIA_URL, imgUrl);
}
Intent intent = new Intent(Constants.BROADCAST_ACTION);
intent.putExtra(Constants.MEDIA_INFO, mediaInfo);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
& the Constants -
public final class Constants {
public static final String BROADCAST_ACTION = "com.parrotainment.media.downloader.BROADCAST";
public static final String MEDIA_INFO = "com.parrotainment.media.downloader.MEDIA_INFO";
public static final String MEDIA_NAME = "com.parrotainment.media.downloader.MEDIA_NAME";
public static final String MEDIA_URL = "com.parrotainment.media.downloader.MEDIA_URL";
}
just checking data in your oReceive may help. like this:
if(intent.getAction() != null && intent.getAction().equals("your_constant_item")){
//
}
Related
I'm creating an Android app that manages screenshot folders in the gallery.
One of the functions of the app is to automatically delete screenshot images, and to do this, I created two classes: DeleteActivity and MyJobService. MyJobService class is doing background work with JobScheduler.So I'm going to send uri from the DeleteActivity class to MyJobService class and delete pictures from the screenshot folder with the uri, but this is the code I've worked on so far, but there's no error, and nothing happens. What's the problem? Is there a way to automatically delete pictures other than using uri? Please let me know if there's a good way.
DeleteAcitivity.class
public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 42;
private static final int JOB_REQUEST_CODE = 43;
public static final String PREFS_NAME = "MyPrefsFile";
private static final int DELETE_JOB_KEY = 123;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("LastSetting", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
final int spinnerSelected = sharedPreferences.getInt("LastClick", 0);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final View txt1 = findViewById(R.id.txt1);
final View txt2 = findViewById(R.id.txt2);
final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("switchkey", false);
Switch deleteSwitch = findViewById(R.id.switchdel);
deleteSwitch.setChecked(silent);
deleteSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
txt1.setEnabled(true);
spinner.setEnabled(true);
txt2.setEnabled(true);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, JOB_REQUEST_CODE);
} else {
txt1.setEnabled(false);
spinner.setEnabled(false);
txt2.setEnabled(false);
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(DELETE_JOB_KEY);
Log.d(TAG, "Job cancelled");
}
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("switchkey", isChecked).commit();
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.days_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(spinnerSelected);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
editor.putInt("LastClick", position).commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String txtSpinner = spinner.getSelectedItem().toString();
Button picture = (Button) findViewById(R.id.btnfind);
picture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == READ_REQUEST_CODE && resultCode == RESULT_OK) {
try {
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
}
Bitmap img = getBitmapFromUri(uri);
DocumentsContract.deleteDocument(getContentResolver(), uri);
} // try
catch (Exception e) {
} // catch
} // if
if(requestCode == JOB_REQUEST_CODE)
{
if(resultData != null) {
ComponentName componentName = new ComponentName(MainActivity.this, MyJobService.class);
PersistableBundle bundle = new PersistableBundle();
bundle.putString("imageUri", resultData.getData().toString());
JobInfo.Builder builder = new JobInfo.Builder(DELETE_JOB_KEY, componentName)
.setExtras(bundle)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.setPeriodic(15 * 60 * 1000);
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.schedule(builder.build());
}
}
} // onActivityResult()
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
MyJobService.class
public class MyJobService extends JobService {
private static final String TAG = "MyJobService";
private boolean jobCancelled = false;
private JobParameters jobParameters;
private DeleteAsyncTask deleteAsyncTask;
#Override
public boolean onStartJob(JobParameters params) {
this.jobParameters = params;
PersistableBundle persistableBundle = params.getExtras();
String strUri = persistableBundle.getString("imageUri");
Uri uri = Uri.parse(strUri);
deleteAsyncTask = (DeleteAsyncTask) new DeleteAsyncTask().execute(uri);
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "onStopJob: Job cancelled before completion");
if(null != deleteAsyncTask){
if(!deleteAsyncTask.isCancelled())
deleteAsyncTask.cancel(true);
}
return true;
}
private class DeleteAsyncTask extends AsyncTask<Uri, Integer, String>{
#Override
protected String doInBackground(Uri... uris) {
try {
DocumentsContract.deleteDocument(getContentResolver(), uris[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return "Job Finished!";
}
#Override
protected void onProgressUpdate(Integer... values){
super.onProgressUpdate(values);
Log.d(TAG, "onProgressUpdate: i was: " + values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute: message: " + s);
jobFinished(jobParameters, true);
}
}
}
Hi Hello to everyone i am developing one app where i am using service to upload multipal images to server for uploading multipal images even if app is closed from background.
But i want to call one function but i am unable to call that function please help me.
UploadPhotos.java
public class UploadPhotos extends AppCompatActivity {
UploadService mBoundService;
boolean mServiceBound = false;
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type,album_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
ProgressBar pb;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
OrderId orderidsession;
AlertDialog dialog;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
NotificationManager manager;
Notification.Builder builder;
ArrayList<CustomGallery> dataT;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
orderidsession=new OrderId(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
Log.d("Orderid Session", ""+abc);
abc="EPP"+abc;
orderidsession.CreateOrderId(abc);
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
//AlertDialog dialog;;
dialog = new SpotsDialog(UploadPhotos.this);
dialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
Intent in = new Intent(UploadPhotos.this, UploadService.class);
in.putExtra("listof",dataT);
in.putExtra("strsize",strSize);
in.putExtra("strtype",strType);
in.putExtra("user_mail",user_mail);
in.putExtra("strmrp",strMRP);
in.putExtra("strprice",strPrice);
in.putExtra("strlab",strlab);
in.putExtra("strcity",strcity);
in.putExtra("strdel_type",strdel_type);
in.putExtra("strusername",str_username);
in.putExtra("foldername",abc);
startService(in);
bindService(in, mServiceConnection, Context.BIND_AUTO_CREATE);
// doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
totalprice=0;
}
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
selectedAdapter.getItem(position);
// selectedAdapter.Pbbar(view );
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
//selectedAdapter.changeSelection(view, position);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_upload_photos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
UploadService.MyBinder myBinder = (UploadService.MyBinder) service;
mBoundService = myBinder.getService();
mServiceBound = true;
}
};
}
SelectedAdapter_Test.java
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
ProgressBar pb;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
public void Pbbar(View v) {
((ViewHolder)v.getTag()).pb.setVisibility(View.VISIBLE);
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.pb=(ProgressBar)convertView.findViewById(R.id.pb_image_upload);
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty = 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
and here is the service
public class UploadService extends Service {
private static String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i=0;
ImageLoader imageLoader;
NotificationManager manager;
Notification myNotication;
String response_str=null;
long totalprice=0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;
String strsize,strtype,usermail,total,strmrp,strprice,strlab,strcity,abc,strdel_type,struname,imageName;
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
strsize = intent.getStringExtra("strsize");
strtype = intent.getStringExtra("strtype");
usermail = intent.getStringExtra("user_mail");
strmrp = intent.getStringExtra("strmrp");
strprice = intent.getStringExtra("strprice");
strlab = intent.getStringExtra("strlab");
strcity = intent.getStringExtra("strcity");
struname = intent.getStringExtra("strusername");
strdel_type = intent.getStringExtra("strdel_type");
abc = intent.getStringExtra("foldername");
// selectedAdapter.Pbbar(view);
Intent intn = new Intent("com.dhruva.eprintpost.digitalPrinting");
PendingIntent pendingIntent = PendingIntent.getActivity(UploadService.this, 1, intn, 0);
builder = new Notification.Builder(UploadService.this);
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setContentTitle("Uploading Photos");
builder.setContentText("Uploading PhotoPrinting Images");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
for( i = 0 ; i<listOfPhotos.size();i++) {
try {
File f = new File(listOfPhotos.get(i).sdcardPath.toString());
//Toast.makeText(UploadService.this, "aa "+listOfPhotos.get(i).sdcardPath, Toast.LENGTH_SHORT).show();
int j=i+1;
builder.setSubText("Uploading " + j + " of " + listOfPhotos.size() + " image"); //API level 16
j++;
Toast.makeText(UploadService.this, "i is = "+i, Toast.LENGTH_SHORT).show();
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
imageName = f.getName();
totalprice = totalprice + Long.parseLong(strprice);
total = String.valueOf(totalprice);
Log.v("Abhijit", "" + totalprice);
String responseString = null;
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://abcdefg.com/abcd/UploadFile?foldername=" + abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
Toast.makeText(UploadService.this, "aa "+sourceFile.getName(), Toast.LENGTH_SHORT).show();
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strsize));
entity.addPart("type",
new StringBody(strtype));
entity.addPart("username",
new StringBody(usermail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strmrp));
entity.addPart("price",
new StringBody(strprice));
entity.addPart("lab",
new StringBody(strlab));
Toast.makeText(UploadService.this, "aa Ky Ho raha hai bhai", Toast.LENGTH_SHORT).show();
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag = String.valueOf(i + 1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(struname));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
responseString = e.toString();
Toast.makeText(UploadService.this, "Exception Occured2 ", Toast.LENGTH_SHORT).show();
}catch(Exception e)
{
Toast.makeText(UploadService.this, "Exception Occured 3", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Service.START_NOT_STICKY;
}
public class MyBinder extends Binder {
UploadService getService() {
return UploadService.this;
}
}
}
Here i want to call pbbar function from adapter class but i am unable to send view parameter to function from server.
Please help me i am new to android
another problem is that the value in notification is not changing it take last value of i throughout the execuation.
i want to update the value of i according to the successful upload image
So I have a map fragment for my application for Google maps. I want to pass the value from the marker (lat/lng) to the String holding the location and then I want to pass that value to the TextField in another application. That textfield will then be stored to the SQLite database that I have built.
My current map activity is as follows
public class MapActivity extends FragmentActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
Serializable {
GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final int EDITOR_REQUEST_CODE = 1001;
public static final String LOCAT_KEY = "location";
private GoogleApiClient mLocationClient;
private Marker marker;
Bundle bundle;
String value;
private static final double
CITY_LAT = 53.3478,
CITY_LNG = -6.2597;
Circle shape;
public String lat;
public String lng;
public String location;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if enabled and if not send user to the GSP settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Getting reference to Button
Button btnDraw = (Button) findViewById(R.id.btn_draw);
if (servicesOK()) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (initMap()) {
gotoLocation(CITY_LAT, CITY_LNG, 12);
mMap.setMyLocationEnabled(true);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
bundle = new Bundle();
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String location = lat + "," + lng;
// Checks, whether location is captured
((TextView) findViewById(R.id.editLocation)).setText(location);
}
});
}
Note I have only added code down to the actual button that is activated.
My code for the button that is clicked in my XML file is as follows:
<Button
android:id="#+id/btn_draw"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/save_location_btn"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="mapLocationClick"/>
And finally my code for the editor class is as follows:
public class EditorActivity extends AppCompatActivity {
public static final String KEY_ID = "id";
public static final String KEY_TIME = "time" ;
public static final String KEY_LOCAT = "location";
private String action;
private EditText editor;
private EditText editorDate;
private EditText editorTime;
private EditText editorLocation;
private ImageButton dateButton;
private ImageButton timeButton;
private ImageButton locationButton;
private String noteFilter;
private String oldText;
private String oldDate;
private String oldTime;
private String oldLocation;
String value = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
editor = (EditText) findViewById(R.id.editText);
editorDate = (EditText) findViewById(R.id.editDate);
editorTime = (EditText) findViewById(R.id.editTime);
editorLocation = (EditText) findViewById(R.id.editLocation);
dateButton = (ImageButton) findViewById(R.id.imgButtonCal);
timeButton = (ImageButton) findViewById(R.id.imgButtonClock);
locationButton = (ImageButton) findViewById(R.id.imgButtonMap);
//enableEdit = (FloatingActionButton) findViewById(R.id.fabEdit);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
action = Intent.ACTION_INSERT;
setTitle(getString(R.string.new_note));
}
else {
long id = extras.getLong(KEY_ID);
if (id == 0){
action = Intent.ACTION_INSERT;
setTitle(getString(R.string.new_note));
long time = intent.getLongExtra(KEY_TIME, 0);
if (time != 0) {
Date d = new Date(time);
String dateString= DateFormat.format("yyyy-MM-dd", `d).toString();`
editorDate.setText(dateString);
}
}
else {
action = Intent.ACTION_EDIT;
setTitle(getString(R.string.edit_note));
Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
noteFilter = DBOpenHelper.NOTE_ID + "=" + uri.getLastPathSegment();
Cursor cursor;
cursor = getContentResolver().query(uri,
DBOpenHelper.ALL_COLUMNS, noteFilter, null, null);
cursor.moveToFirst();
oldText = cursor.getString(cursor.getColumnIndex(NOTE_TEXT));
oldDate = cursor.getString(cursor.getColumnIndex(NOTE_DATE));
oldTime = cursor.getString(cursor.getColumnIndex(NOTE_TIME));
oldLocation = cursor.getString(cursor.getColumnIndex(NOTE_LOCATION));
editor.setText(oldText);
editor.setEnabled(false);
editorDate.setText(oldDate);
editorDate.setEnabled(false);
dateButton.setEnabled(false);
editorTime.setText(oldTime);
editorTime.setEnabled(false);
timeButton.setEnabled(false);
editorLocation.setText(oldLocation);
editorLocation.setEnabled(false);
locationButton.setEnabled(false);
//saveButton.setEnabled(false);
editor.requestFocus();
//enableEdit.setEnabled(true);
//enableSave.setEnabled(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (action.equals(Intent.ACTION_EDIT)){
getMenuInflater().inflate(R.menu.menu_editor, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
finishEditing();
break;
case R.id.action_delete:
deleteNote();
break;
case R.id.action_edit:
enableFields();
break;
}
return true;
}
private void enableFields(){
if(NotesProvider.CONTENT_URI != null) {
editor.setEnabled(true);
editorDate.setEnabled(true);
dateButton.setEnabled(true);
editorTime.setEnabled(true);
timeButton.setEnabled(true);
editorLocation.setEnabled(true);
locationButton.setEnabled(true);
}
}
private void deleteNote() {
getContentResolver().delete(NotesProvider.CONTENT_URI,
noteFilter,null);
Toast.makeText(this, R.string.note_deleted,
Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
private void finishEditing(){
String newText = editor.getText().toString().trim();
String newDate = editorDate.getText().toString().trim();
String newTime = editorTime.getText().toString().trim();
String newLocation = editorLocation.getText().toString().trim();
switch (action) {
case Intent.ACTION_INSERT:
if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0){
setResult(RESULT_CANCELED);
} else{
insertNote(newText, newDate, newTime, newLocation);
}
break;
case Intent.ACTION_EDIT:
if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0 && newLocation.length() == 0){
deleteNote();
}else if (oldText.equals(newText) && oldDate.equals(newDate) && oldTime.equals(newTime) && oldLocation.equals(newLocation)){
setResult(RESULT_CANCELED);
}else {
updateNote(newText, newDate, newTime, newLocation);
}
}
finish();
}
private void updateNote(String noteText, String noteDate, String noteTime, String noteLocation) {
ContentValues values = new ContentValues();
values.put(NOTE_TEXT, noteText);
values.put(NOTE_DATE, noteDate);
values.put(NOTE_TIME, noteTime);
values.put(NOTE_LOCATION, noteLocation);
getContentResolver().update(NotesProvider.CONTENT_URI, values, noteFilter, null);
Toast.makeText(this, R.string.note_updated, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
}
private void insertNote(String noteText, String noteDate, String noteTime, String noteLocation) {
ContentValues values = new ContentValues();
values.put(NOTE_TEXT, noteText);
values.put(NOTE_DATE, noteDate);
values.put(NOTE_TIME, noteTime);
values.put(NOTE_LOCATION, noteLocation);
getContentResolver().insert(NotesProvider.CONTENT_URI, values);
setResult(RESULT_OK);
}
#Override
public void onBackPressed() {
finishEditing();
}
public void onSaveNote(View view) { finishEditing();}
public void onButtonClicked(View v){
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void openMapFragment(View v) {
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
Anybody help me so when I click on the button it will take the value from the location and save it in the previous class that was loaded up before.
I found the answer. I created the following in my map class
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Checks, whether location is captured
Intent intent = MapActivity.this.getIntent();
intent.putExtra(LATITUDE_EXTRA, lat);
intent.putExtra(LONGITUDE_EXTRA, lng);
MapActivity.this.setResult(RESULT_OK, intent);
MapActivity.this.finish();
}
});
Then I added it to the Editor class by the following.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST_CODE && resultCode == RESULT_OK) {
String lat = data.getStringExtra(MapActivity.LATITUDE_EXTRA);
String lng = data.getStringExtra(MapActivity.LONGITUDE_EXTRA);
editorLocation.setText(lat + ", " + lng);
}
else {
Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show();
}
}
Seems I needed to add a new intent and use the onActivityResult.
I have three activities: MainActivity, DownloadServiceTest, ViewDetailDownload. Now, i want download files using Service (IntentService).
Corporeality :
MainActivity have buttons. When i click button_1 it to start a service (DownloadServiceTestextends IntentSerive ) perform download and I want when click button_2 it will startup ViewDetailDownload and update progress.
But when i start ViewDetailDownload i don't receive data(percent download, speed ) from DownloadServiceTest
My code here.
class MainActivity :
public class MainActivity extends Activity implements OnClickListener {
private final String LINK_MP3 = "http://data.chiasenhac.com/downloads/1471/5/1470643-c6ef1a26/320/Vo%20Hinh%20Trong%20Tim%20Em%20-%20Mr%20Siro%20%5BMP3%20320kbps%5D.mp3";
Activity activity;
Button btnDownload_1, btnDownload_2, btnDownload_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_control);
activity = MainActivity.this;
btnDownload_1 = (Button) findViewById(R.id.btn_startdownload_1);
btnDownload_2 = (Button) findViewById(R.id.btn_startdownload_2);
btnDownload_3 = (Button) findViewById(R.id.btn_startdownload_3);
btnDownload_1.setOnClickListener(this);
btnDownload_2.setOnClickListener(this);
btnDownload_3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_startdownload_1) {
Intent intent = new Intent(activity, DownloadServiceTest.class);
intent.putExtra(DownloadServiceTest.REQUEST_STRING, LINK_MP3);
startService(intent);
}
if (v.getId() == R.id.btn_startdownload_2) {
Intent intent = new Intent(MainActivity.this,
ViewDetailDownload.class);
startActivity(intent);
}
}
}
class DownloadServiceTest :
public class DownloadServiceTest extends IntentService {
public static final String REQUEST_STRING = "REQUEST_LINK";
public static final String PROGRESS_UPDATE_ACTION = DownloadServiceTest.class
.getName() + ".progress_update";
private LocalBroadcastManager mLocalBroadcastManager;
private String mUrl_mp3;
public DownloadServiceTest(String name) {
super(name);
}
public DownloadServiceTest() {
super("DownloadService");
}
#Override
public void onCreate() {
mLocalBroadcastManager = LocalBroadcastManager
.getInstance(DownloadServiceTest.this);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onHandleIntent(Intent intent) {
mUrl_mp3 = intent.getStringExtra(REQUEST_STRING);
DownloadTask task = new DownloadTask();
if (mUrl_mp3 != null) {
task.execute(mUrl_mp3);
}
}
private void onProgressUpdateReceiver(int progress, int speed) {
Intent intent = new Intent();
intent.setAction(PROGRESS_UPDATE_ACTION);
intent.putExtra("progress", progress);
intent.putExtra("speed", speed);
Log.i("", "abc onProgressUpdateReceiver progress "+progress);
Log.i("", "abc onProgressUpdateReceiver speed "+speed);
mLocalBroadcastManager.sendBroadcast(intent);
}
private class DownloadTask extends AsyncTask<String, Void, Void> {
String filename;
int mProgress;
int mSpeed;
private int checkExist;
File SDCardRoot;
private FileOutputStream fileOut;
private InputStream fileIn;
File file;
#Override
protected void onPreExecute() {
filename = mUrl_mp3.substring(mUrl_mp3.lastIndexOf("/") + 1);
try {
filename = URLDecoder.decode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
int contentLengh = 0;
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (HttpURLConnection.HTTP_OK == urlConnection
.getResponseCode()) {
contentLengh = urlConnection.getContentLength();
Log.i("", "abc " + contentLengh);
fileIn = urlConnection.getInputStream();
SDCardRoot = Environment.getExternalStorageDirectory();
file = new File(Environment.getExternalStorageDirectory()
+ "/Blog Radio");
boolean success = true;
if (!file.exists()) {
success = file.mkdir();
}
String getTypeFile = filename.substring(filename
.indexOf("."));
if (success) {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
} else {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
}
fileOut = new FileOutputStream(file);
int downloadSize = 0;
byte[] buffer = new byte[8192];
long tempTotal = 0;
long startTime = System.currentTimeMillis();
int bufferLengh = 0;
while ((bufferLengh = fileIn.read(buffer)) != -1) {
long interval = System.currentTimeMillis() - startTime;
if (isCancelled()) {
fileIn.close();
}
if (contentLengh > 0) {
downloadSize += bufferLengh;
tempTotal += bufferLengh;
mProgress = (int) ((downloadSize * 100L) / contentLengh);
if (interval >= 1000) {
Log.i("now = ", String.valueOf(System
.currentTimeMillis()));
Log.i("last = ", String.valueOf(startTime));
Log.i("currentDump = ",
String.valueOf(tempTotal));
mSpeed = (int) (tempTotal * 1000 / interval / 1024);
startTime = System.currentTimeMillis();
tempTotal = 0;
}
fileOut.write(buffer, 0, bufferLengh);
onProgressUpdateReceiver(mProgress, mSpeed);
}
}
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
class ViewDetailDownload :
public class ViewDetailDownload extends Activity {
TextView tv_Title, tv_Info;
ProgressBar progressBar;
ImageView img;
MyRequestReceiver receiver;
IntentFilter intentToReceiveFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_service_layout);
img = (ImageView) findViewById(R.id.img);
tv_Title = (TextView) findViewById(R.id.title);
tv_Info = (TextView) findViewById(R.id.info);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter
.addAction(DownloadServiceTest.PROGRESS_UPDATE_ACTION);
receiver = new MyRequestReceiver();
}
#Override
protected void onResume() {
registerReceiver();
super.onResume();
}
private void registerReceiver() {
this.registerReceiver(receiver, intentToReceiveFilter);
}
#Override
protected void onPause() {
unregisterReceiver();
super.onPause();
}
protected void onProgressUpdate(int progress, int speed) {
progressBar.setProgress(progress);
tv_Info.setText(speed);
}
protected void onProgressUpdateOneShot(int progresses, int speeds) {
int progress = progresses;
int speed = speeds;
onProgressUpdate(progress, speed);
}
private void unregisterReceiver() {
this.unregisterReceiver(receiver);
}
public class MyRequestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
DownloadServiceTest.PROGRESS_UPDATE_ACTION)) {
int progresses = intent.getIntExtra("progress", -1);
int speeds = intent.getIntExtra("speed", -1);
Log.i("", "abc progresses onReceive" + progresses);
Log.i("", "abc speeds onReceive" + speeds);
onProgressUpdateOneShot(progresses, speeds);
}
}
}
}
I need help !
If you know... please give example.
Thanks all
add this in DownloadServiceTest.java in onCreate() method.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String mname =(String) b.getString("LINK_MP3");
}
Now you can use this string mname anywhere in your DownloadServiceTest
I am new to android programming,I got a chance to work with (wifi printers).In my application I have a pdf file which needs to be taken a printout by using wifi printer
I didnt have much idea on this,but after doing a research I got that,there are 3 things to be done for doing this
1)getting the list of devices which are connected to wifi network which my mobile is using right now.
2) Then,select a device and make a connection with that device.
3) Transfer data to a printer
I hope these are the steps which I need to use.
I worked on first point,but I am getting the (Wifi networks like Tata communications,vonline etc) but not the devices which are connecting to that networks.
Here is the code I used.........
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
checkWifi();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
private void checkWifi(){
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager =
(WifiManager)this.getSystemService(Context.WIFI_SERVICE);;
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d("wifi","Open Wifimanager");
String scanList = wifiManager.getScanResults().toString();
Log.d("wifi","Scan:"+scanList);
}
},filter);
wifiManager.startScan();
}
}
please suggest for the solution
Thanks in advance friends
Refer this Android-wifi-print - Github, Which contains a demo application I created for the same.
Edit :
As #NileshThakkar said. we may lost connection to that link in future so, I am posting code here.. with flow.
checks connectivity.
If connected in WiFi.. am storing that WiFi configuration.
Now checking whether I already have printer's information (WiFi configuration of WiFi printer) is available or not. If available, I'll scan and get list of WiFi ScanResults and connects to that else.. It'll showing list of WiFi and clicking on that, user will connect to printer and stores that WiFi configuration for future printing jobs.
After print job completes, I'm connecting to my previous WiFi or Mobile data connection.
Now going back to 2nd step.
If user connected in Mobile data, I'm just enabling WiFi and following 3rd step.
After Print job completes, I'm just disabling WiFi. so that, We'll be connected back to Mobile data connection. (That is android default).
Libraries : gson-2.2.4, itextpdf-5.4.3
MyActivity.java
public class MyActivity extends Activity implements PrintCompleteService {
private Button mBtnPrint;
private WifiConfiguration mPrinterConfiguration, mOldWifiConfiguration;
private WifiManager mWifiManager;
private List<ScanResult> mScanResults = new ArrayList<ScanResult>();
private WifiScanner mWifiScanner;
private PrintManager mPrintManager;
private List<PrintJob> mPrintJobs;
private PrintJob mCurrentPrintJob;
private File pdfFile;
private String externalStorageDirectory;
private Handler mPrintStartHandler = new Handler();
private Handler mPrintCompleteHandler = new Handler();
private String connectionInfo;
private boolean isMobileDataConnection = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(externalStorageDirectory, Constants.CONTROLLER_RX_PDF_FOLDER);
pdfFile = new File(folder, "Print_testing.pdf");
} catch (Exception e) {
e.printStackTrace();
}
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiScanner = new WifiScanner();
mBtnPrint = (Button) findViewById(R.id.btnPrint);
mBtnPrint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connectionInfo = Util.connectionInfo(MyActivity.this);
if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
isMobileDataConnection = true;
if (mWifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "Enabling WiFi..", Toast.LENGTH_LONG).show();
mWifiManager.setWifiEnabled(true);
}
mWifiManager.startScan();
printerConfiguration();
} else if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
Util.storeCurrentWiFiConfiguration(MyActivity.this);
printerConfiguration();
} else {
Toast.makeText(MyActivity.this, "Please connect to Internet", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
registerReceiver(mWifiScanner, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(mWifiScanner);
} catch (Exception e) {
e.printStackTrace();
}
}
private void printerConfiguration() {
mPrinterConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_PRINTER);
if (mPrinterConfiguration == null) {
showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
} else {
boolean isPrinterAvailable = false;
mWifiManager.startScan();
for (int i = 0; i < mScanResults.size(); i++) {
if (mPrinterConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
isPrinterAvailable = true;
break;
}
}
if (isPrinterAvailable) {
connectToWifi(mPrinterConfiguration);
doPrint();
} else {
showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
}
}
}
private void connectToWifi(WifiConfiguration mWifiConfiguration) {
mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
}
private void showWifiListActivity(int requestCode) {
Intent iWifi = new Intent(this, WifiListActivity.class);
startActivityForResult(iWifi, requestCode);
}
#Override
public void onMessage(int status) {
mPrintJobs = mPrintManager.getPrintJobs();
mPrintCompleteHandler.postDelayed(new Runnable() {
#Override
public void run() {
mPrintCompleteHandler.postDelayed(this, 2000);
if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_COMPLETED) {
for (int i = 0; i < mPrintJobs.size(); i++) {
if (mPrintJobs.get(i).getId() == mCurrentPrintJob.getId()) {
mPrintJobs.remove(i);
}
}
switchConnection();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
} else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_FAILED) {
switchConnection();
Toast.makeText(MyActivity.this, "Print Failed!", Toast.LENGTH_LONG).show();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
} else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_CANCELED) {
switchConnection();
Toast.makeText(MyActivity.this, "Print Cancelled!", Toast.LENGTH_LONG).show();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
}
}
}, 2000);
}
public void switchConnection() {
if (!isMobileDataConnection) {
mOldWifiConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_WIFI);
boolean isWifiAvailable = false;
mWifiManager.startScan();
for (int i = 0; i < mScanResults.size(); i++) {
if (mOldWifiConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
isWifiAvailable = true;
break;
}
}
if (isWifiAvailable) {
connectToWifi(mOldWifiConfiguration);
} else {
showWifiListActivity(Constants.REQUEST_CODE_WIFI);
}
} else {
mWifiManager.setWifiEnabled(false);
}
}
public void printDocument(File pdfFile) {
mPrintManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
String jobName = getString(R.string.app_name) + " Document";
mCurrentPrintJob = mPrintManager.print(jobName, new PrintServicesAdapter(MyActivity.this, pdfFile), null);
}
public void doPrint() {
mPrintStartHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d("PrinterConnection Status", "" + mPrinterConfiguration.status);
mPrintStartHandler.postDelayed(this, 3000);
if (mPrinterConfiguration.status == WifiConfiguration.Status.CURRENT) {
if (Util.computePDFPageCount(pdfFile) > 0) {
printDocument(pdfFile);
} else {
Toast.makeText(MyActivity.this, "Can't print, Page count is zero.", Toast.LENGTH_LONG).show();
}
mPrintStartHandler.removeCallbacksAndMessages(null);
} else if (mPrinterConfiguration.status == WifiConfiguration.Status.DISABLED) {
Toast.makeText(MyActivity.this, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
mPrintStartHandler.removeCallbacksAndMessages(null);
}
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CODE_PRINTER && resultCode == Constants.RESULT_CODE_PRINTER) {
mPrinterConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_PRINTER);
doPrint();
}
}
public class WifiScanner extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mScanResults = mWifiManager.getScanResults();
Log.e("scan result size", "" + mScanResults.size());
}
}
}
WiFiListActivity.java
public class WifiListActivity extends Activity implements View.OnClickListener {
private ListView mListWifi;
private Button mBtnScan;
private WifiManager mWifiManager;
private WifiAdapter adapter;
private WifiListener mWifiListener;
private List<ScanResult> mScanResults = new ArrayList<ScanResult>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_list);
mBtnScan = (Button) findViewById(R.id.btnNext);
mBtnScan.setOnClickListener(this);
mListWifi = (ListView) findViewById(R.id.wifiList);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (mWifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "wifi is disabled.. making it enabled", Toast.LENGTH_LONG).show();
mWifiManager.setWifiEnabled(true);
}
mWifiListener = new WifiListener();
adapter = new WifiAdapter(WifiListActivity.this, mScanResults);
mListWifi.setAdapter(adapter);
mListWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
connectToWifi(i);
}
});
}
#Override
public void onClick(View view) {
mWifiManager.startScan();
Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
try {
registerReceiver(mWifiListener, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(mWifiListener);
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectToWifi(int position) {
final ScanResult item = mScanResults.get(position);
String Capabilities = item.capabilities;
if (Capabilities.contains("WPA")) {
AlertDialog.Builder builder = new AlertDialog.Builder(WifiListActivity.this);
builder.setTitle("Password:");
final EditText input = new EditText(WifiListActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.preSharedKey = "\"" + m_Text + "\"";
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
int res = mWifiManager.addNetwork(wifiConfiguration);
boolean b = mWifiManager.enableNetwork(res, true);
finishActivity(wifiConfiguration, res);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (Capabilities.contains("WEP")) {
AlertDialog.Builder builder = new AlertDialog.Builder(WifiListActivity.this);
builder.setTitle("Title");
final EditText input = new EditText(WifiListActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.wepKeys[0] = "\"" + m_Text + "\"";
wifiConfiguration.wepTxKeyIndex = 0;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
int res = mWifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = mWifiManager.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
finishActivity(wifiConfiguration, res);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int res = mWifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = mWifiManager.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
finishActivity(wifiConfiguration, res);
}
}
private void finishActivity(WifiConfiguration mWifiConfiguration, int networkId) {
mWifiConfiguration.networkId = networkId;
Util.savePrinterConfiguration(WifiListActivity.this, mWifiConfiguration);
Intent intent = new Intent();
setResult(Constants.RESULT_CODE_PRINTER, intent);
finish();
}
public class WifiListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mScanResults = mWifiManager.getScanResults();
Log.e("scan result size ", "" + mScanResults.size());
adapter.setElements(mScanResults);
}
}
}
WifiAdapter.java
public class WifiAdapter extends BaseAdapter {
private Activity mActivity;
private List<ScanResult> mWifiList = new ArrayList<ScanResult>();
public WifiAdapter(Activity mActivity, List<ScanResult> mWifiList) {
this.mActivity = mActivity;
this.mWifiList = mWifiList;
}
#Override
public int getCount() {
return mWifiList.size();
}
#Override
public Object getItem(int i) {
return mWifiList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_wifi_list_item, null);
TextView txtWifiName = (TextView) view.findViewById(R.id.txtWifiName);
txtWifiName.setText(mWifiList.get(i).SSID);
return view;
}
public void setElements(List<ScanResult> mWifis) {
this.mWifiList = mWifis;
notifyDataSetChanged();
}
}
PrintCompleteService.java
public interface PrintCompleteService {
public void onMessage(int status);
}
PrintServiceAdapter.java
public class PrintServicesAdapter extends PrintDocumentAdapter {
private Activity mActivity;
private int pageHeight;
private int pageWidth;
private PdfDocument myPdfDocument;
private int totalpages = 1;
private File pdfFile;
private PrintCompleteService mPrintCompleteService;
public PrintServicesAdapter(Activity mActivity, File pdfFile) {
this.mActivity = mActivity;
this.pdfFile = pdfFile;
this.totalpages = Util.computePDFPageCount(pdfFile);
this.mPrintCompleteService = (PrintCompleteService) mActivity;
}
#Override
public void onLayout(PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle metadata) {
myPdfDocument = new PrintedPdfDocument(mActivity, newAttributes);
pageHeight =
newAttributes.getMediaSize().getHeightMils() / 1000 * 72;
pageWidth =
newAttributes.getMediaSize().getWidthMils() / 1000 * 72;
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder(pdfFile.getName())
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
#Override
public void onWrite(final PageRange[] pageRanges,
final ParcelFileDescriptor destination,
final CancellationSignal cancellationSignal,
final WriteResultCallback callback) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(pdfFile);
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee) {
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
#Override
public void onCancel() {
mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
}
});
}
#Override
public void onFinish() {
mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_COMPLETED);
}
}
Util.java
public class Util {
public static String connectionInfo(Activity mActivity) {
String result = "not connected";
ConnectivityManager cm = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
if (ni.isConnected()) {
result = Constants.CONTROLLER_WIFI;
break;
}
} else if (ni.getTypeName().equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
if (ni.isConnected()) {
result = Constants.CONTROLLER_MOBILE;
break;
}
}
}
return result;
}
public static void saveWifiConfiguration(Activity mActivity, WifiConfiguration mWifiConfiguration) {
Gson mGson = new Gson();
Type mType = new TypeToken<WifiConfiguration>() {
}.getType();
String sJson = mGson.toJson(mWifiConfiguration, mType);
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
mSharedPrefs.edit().putString(Constants.CONTROLLER_WIFI_CONFIGURATION, sJson).commit();
}
public static void savePrinterConfiguration(Activity mActivity, WifiConfiguration mPrinterConfiguration) {
Gson mGson = new Gson();
Type mType = new TypeToken<WifiConfiguration>() {
}.getType();
String sJson = mGson.toJson(mPrinterConfiguration, mType);
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
mSharedPrefs.edit().putString(Constants.CONTROLLER_PRINTER_CONFIGURATION, sJson).commit();
}
public static WifiConfiguration getWifiConfiguration(Activity mActivity, String configurationType) {
WifiConfiguration mWifiConfiguration = new WifiConfiguration();
Gson mGson = new Gson();
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
Type mWifiConfigurationType = new TypeToken<WifiConfiguration>() {
}.getType();
String mWifiJson = "";
if (configurationType.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
mWifiJson = mSharedPrefs.getString(Constants.CONTROLLER_WIFI_CONFIGURATION, "");
} else if (configurationType.equalsIgnoreCase(Constants.CONTROLLER_PRINTER)) {
mWifiJson = mSharedPrefs.getString(Constants.CONTROLLER_PRINTER_CONFIGURATION, "");
}
if (!mWifiJson.isEmpty()) {
mWifiConfiguration = mGson.fromJson(mWifiJson, mWifiConfigurationType);
} else {
mWifiConfiguration = null;
}
return mWifiConfiguration;
}
public static void storeCurrentWiFiConfiguration(Activity mActivity) {
try {
WifiManager wifiManager = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
WifiConfiguration mWifiConfiguration = new WifiConfiguration();
mWifiConfiguration.networkId = connectionInfo.getNetworkId();
mWifiConfiguration.BSSID = connectionInfo.getBSSID();
mWifiConfiguration.hiddenSSID = connectionInfo.getHiddenSSID();
mWifiConfiguration.SSID = connectionInfo.getSSID();
// store it for future use -> after print is complete you need to reconnect wifi to this network.
saveWifiConfiguration(mActivity, mWifiConfiguration);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static int computePDFPageCount(File file) {
RandomAccessFile raf = null;
int pages = 0;
try {
raf = new RandomAccessFile(file, "r");
RandomAccessFileOrArray pdfFile = new RandomAccessFileOrArray(
new RandomAccessSourceFactory().createSource(raf));
PdfReader reader = new PdfReader(pdfFile, new byte[0]);
pages = reader.getNumberOfPages();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pages;
}
}