Download service and update another activity - android

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

Related

android app install programmatically targetSDK 24 , compileSDK 28 , minSDK 19

I have implemented autoUpdate functionality which downloads the new app if update available and removes the old app and installs a new app. but After target SDK 24 or updating Phone os above API Level 2 this functionality not working Whenever I install it shows package parsing error. because of an old app is already there and we are trying to install a new app.
public class UpdateActivity extends AppCompatActivity implements
AppConstants {
public static final String TAG = UpdateActivity.class.getSimpleName();
private String appName = "demo.apk";
private int UNINSTALL_REQUEST_CODE = 1;
private final Handler mHideHandler = new Handler();
private View mContentView;
private BiColoredProgress numberProgressBar;
private Runnable backgroundRunnable;
private Runnable finishRunnable;
private Handler handler;
private static final int INSTALL = 1;
private static final int DOWNLOAD = 0;
private static int flag = 0;
private String updateUrl = "";
private class BackgroundDownloadRunnable implements Runnable {
BackgroundDownloadRunnable() {
}
public void run() {
DownloadFileFromURL d = new DownloadFileFromURL();
d.execute();
return;
}
}
private class FinishDownloadRunnable implements Runnable {
FinishDownloadRunnable() {
}
public void run() {
uninstallApp();
}
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
flag = getIntent().getIntExtra("flag", 0);
updateUrl = getIntent().getStringExtra("updateUrl");
StrictMode.setThreadPolicy(new
StrictMode.ThreadPolicy.Builder().permitAll().build());
handler = new Handler();
mContentView = findViewById(R.id.fullscreen_content);
mHideHandler.post(mHidePart2Runnable);
finishRunnable = new BackgroundDownloadRunnable();
backgroundRunnable = new FinishDownloadRunnable();
numberProgressBar = findViewById(R.id.numberbar8);
try {
if (flag == DOWNLOAD) {
DownloadFileFromURL d = new DownloadFileFromURL();
d.execute();
flag = 1;
} else if (flag == INSTALL) {
installApp();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, Integer,
String> {
DownloadFileFromURL() {
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... f_url) {
try {
HttpURLConnection c = (HttpURLConnection) new
URL(updateUrl).openConnection();
c.setRequestMethod("POST");
c.setDoOutput(false);
c.connect();
int lengthOfFile = c.getContentLength();
File file = new
File(Environment.getExternalStorageDirectory().getPath() + "/Download/");
file.mkdirs();
File outputFile = new File(file, appName);
if (outputFile.exists()) {
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] data = new
byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
long total1 = 0;
while (true) {
int count = is.read(data);
if (count == -1) {
break;
}
total1 += (long) count;
Integer[] strArr = new Integer[1];
strArr[0] = DOWNLOAD_COUNT + ((int) ((100 * total1) /
((long) lengthOfFile)));
publishProgress(strArr);
fos.write(data, 0, count);
}
fos.close();
is.close();
installApp();
new Thread(backgroundRunnable, "VersionChecker").start();
//uninstallApp();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
try {
if (progress[0] > 0 && progress[0] <= 20) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#d63232"));
}
if (progress[0] > 20 && progress[0] <= 40) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#F1E84B"));
}
if (progress[0] > 40 && progress[0] <= 60) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#2CACE3"));
}
if (progress[0] > 60 && progress[0] <= 80) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#4CBB17"));
}
if (progress[0] > 80 && progress[0] <= 100) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#39FF14"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPostExecute(String file_url) {
numberProgressBar.setVisibility(View.GONE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == this.UNINSTALL_REQUEST_CODE && resultCode != -1) {
if (resultCode == 0) {
super.onBackPressed();
startActivity(intent);
} else if (resultCode == 1) {
super.onBackPressed();
}
}
}
private void uninstallApp() {
Intent intentDEl = new Intent("android.intent.action.DELETE");
intentDEl.setData(Uri.parse("package:com.demo"));
startActivityForResult(intentDEl, UNINSTALL_REQUEST_CODE);
}
private void installApp() {
File apkFile = new
File(Environment.getExternalStorageDirectory().getPath() + "/Download/",
appName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}

LocalBroadcastManager sends data more than once

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")){
//
}

Call Function from android service

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

taking picture at a specific time of the day

My application should take pictures in background at a specific time of the day. I am going to use AlarmManager but I am wondering whether the class which implements the behavior of my application (i.e., taking a picture) should extend Service or BroadcastReceiver. What do you think?
You should use IntentSerivce with AlaramManger and define the BroadcastReceiver on your activity.
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService() {
super("DownloadService");
}
// Will be called asynchronously be Android
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
public class MainActivity extends Activity {
private TextView textView;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String string = bundle.getString(DownloadService.FILEPATH);
int resultCode = bundle.getInt(DownloadService.RESULT);
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this,
"Download complete. Download URI: " + string,
Toast.LENGTH_LONG).show();
textView.setText("Download done");
} else {
Toast.makeText(MainActivity.this, "Download failed",
Toast.LENGTH_LONG).show();
textView.setText("Download failed");
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
public void onClick(View view) {
Intent intent = new Intent(this, DownloadService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
}
}

Activity with ProgressBar -> Service -> AsyncTask for downloading - but how to update the progress?

this is the current state/situation: I have an Activity which binds a Service which creates AsyncTasks which downloads various web resources. That works well, but of course the ProgressBar shows nothing.
Previously i had an Activity which created an AsyncTask which downloaded some stuff. The AsyncTask got the View which holds the ProgressBar. So i could update the progress using onProgressUpdate and publishProgress. Obviously this doesn't work any longer because I have no reference to the ProgressBar.
So, do you have any idea on how to update the progress?
Thanks in advance.
Very nice explained indeed just missing the example :)
I went throw it and here it is.
public class Detail extends Activity {
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
mProgressDialog.setProgress(intent.getFlags());
}
}
};
// Flag if receiver is registered
private boolean mReceiversRegistered = false;
// Define a handler and a broadcast receiver
private final Handler mHandler = new Handler();
#Override
protected void onResume() {
super.onResume();
// Register Sync Recievers
IntentFilter intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
mReceiversRegistered = true;
}
#Override
public void onPause() {
super.onPause();
// Make sure you unregister your receivers when you pause your activity
if(mReceiversRegistered) {
unregisterReceiver(mIntentReceiver);
mReceiversRegistered = false;
}
}
}
public class DownloadService extends Service {
private static final String CLASS_NAME = DownloadService.class.getSimpleName();
private List<Download> downloads = new ArrayList<Download>();
private int currentPosition;
public static final String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
private Context ctx;
#Override
public IBinder onBind(Intent arg0) {
ctx = getApplicationContext();
return mBinder;
}
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... _url) {
Log.d(Constants.LOG_TAG, CLASS_NAME + " Start the background GetNewsTask \nURL :" + _url[0]);
int count;
File finalFile = new File(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
try {
if (!finalFile.exists()) {
Log.i(Constants.LOG_TAG, CLASS_NAME + " Donwloading apk from the Web");
URL url = new URL(_url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
File dir = new File(sdcardPath + Constants.APK_LOCAL_PATH);
if (!dir.exists())
dir.mkdirs();
OutputStream output = new FileOutputStream(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
Log.i(Constants.LOG_TAG, CLASS_NAME + " Apk in SDcard");
publishProgress(100);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
Intent i = new Intent();
i.setAction(CUSTOM_INTENT);
i.setFlags(progress[0]);
ctx.sendBroadcast(i);
}
}
private String splitName(String url) {
String[] output = url.split("/");
return output[output.length - 1];
}
public static final String CUSTOM_INTENT = "es.tempos21.sync.client.ProgressReceiver";
private final IDownloadService.Stub mBinder = new IDownloadService.Stub() {
public void downloadAsynFile(String url) throws DeadObjectException {
try {
DownloadFile d = new DownloadFile();
d.execute(url);
} catch (Exception e) {
Log.e(Constants.LOG_TAG, CLASS_NAME + " " +e.getMessage()); }
}
}
};
interface IDownloadService {
void downloadAsynFile(String url);
}
Have the Service notify the then-running Activity about the progress from onProgressUpdate(). That could be via a broadcast Intent, or via a callback object registered by the Activity (and unregistered when the Activity is destroyed, such as on a screen rotation).
You can show progress just as easily via a Toast, which obviates all of the UI concerns:
public class foo extends Service {
private Toast toast;
#SuppressLint("ShowToast")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
ctxt = getApplicationContext();
toast = Toast.makeText(ctxt, "", Toast.LENGTH_SHORT);
...
}
public void functionCalledByYourAsyncWithUpdates(String progress){
toast.setText (progress);
toast.show;
}
}

Categories

Resources