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);
}
}
Related
I'm developing a application when which every 4,5 seconds the client checks whether the server responds "OK".
It's even working, But if I turn on/off the internet sometimes it stops working, it is inconsistent and I need to check the messages accurately.
And service stop like in example I gave and it re-operate outside the specified range of seconds (4.5)
I'm developing a chat, and I need to know this precisely, I need to be professional.
Start.java
public class Start extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Intent serviceIntent = new Intent(getBaseContext(), BackExec.class);
getBaseContext().startService(serviceIntent);
}
#Override
protected void onResume()
{
super.onResume();
Intent serviceIntent = new Intent(getApplicationContext(), BackExec.class);
startService(serviceIntent);
}}
BackExec.java
public class BackExec extends Service {
static Timer t;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
}
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
return START_STICKY;
}
public static String getData(){
URL site = null;
try {
site = new URL("http://192.168.0.10:8080/example/server.php");
URLConnection urlConn = site.openConnection();
urlConn.setRequestProperty("Cookie", CookieManager.getInstance().getCookie("http://192.168.0.10:8080/example"));
urlConn.setDoOutput(true);
PrintStream enviarInfos = new PrintStream(urlConn.getOutputStream());
enviarInfos.print("pac=pac");
urlConn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine;
String out = "";
while ((inputLine = in.readLine()) != null)
out = out + inputLine;
in.close();
return out;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public void onStart(Intent intent, int startId) { } // TO DO
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {} }
I developed an android app using android download manager and Broadcast receiver, after completed downloading I am passing success response to BroadcastReceiver class but that not calling. What I did wrong?
public class MobuleDownloadManager {
private boolean isReaname = false;
private ProgressDialog mProgressDialog;
private Activity activity;
private DownloadFile mDownloadClas;
private String TAG = "MobuleDownloadManager", URL, mFileName, mDisplayName_;
private AlertDialog alert;
private DownloadManager downloadManager;
private long enqueue, id;
SharedPreferences preferenceManager;
final String strPref_Download_ID = "PREF_DOWNLOAD_ID";
public static BroadcastReceiver downloadReceiver = null;
final Timer myTimer = new Timer();
Cursor cursorMain, cursorTimer;
private SharedPreferences.Editor PrefEdit;
int bytes_total;
public MobuleDownloadManager(final Activity activity_, String mFilePath_,
final String mFileName_, final String mDisplayName) {
super();
this.URL = mFilePath_;
fileDownloadManager(URL);
FileInputStream in = null;
try {
in = activity.openFileInput(mFileName);
// file is alredy exist so no need too download again just open file
myTimer.cancel();
OnHttpResponseDownloadFile callBack = (OnHttpResponseDownloadFile) activity;
callBack.onSuccessDownloadFile(mFileName, mDisplayName_);
fileDownloadManager(URL);
} catch (FileNotFoundException e1) {
try {
fileDownloadManager(URL);
}
}
private void fileDownloadManager(String url) {
preferenceManager = PreferenceManager.getDefaultSharedPreferences(activity);
downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
id = downloadManager.enqueue(request);
mProgressDialog = new ProgressDialog(activity);
mProgressDialog.setTitle("Downloading");
mProgressDialog.setMessage("Downloading, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Cancel", new DialogInterface.OnClickListener() {
// Set a click listener for progress dialog cancel
// button
#Override
public void onClick(DialogInterface dialog, int which) {
try {
myTimer.cancel();
downloadManager.remove(id);
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
mProgressDialog.show();
PrefEdit = preferenceManager.edit();
PrefEdit.putLong(strPref_Download_ID, id);
PrefEdit.commit();
myTimer.schedule(new TimerTask() {
public void run() {
try {
DownloadManager.Query q;
q = new DownloadManager.Query();
q.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
cursorTimer = downloadManager.query(q);
if (cursorTimer.moveToFirst() && cursorTimer != null) {
Log.e("bytes_total", "cursorTimer");
int bytes_downloaded = cursorTimer.getInt(cursorTimer.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
bytes_total = cursorTimer.getInt(cursorTimer.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
final int dl_progress = (int) ((double) bytes_downloaded / (double) bytes_total * 100f);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.setProgress(dl_progress);
}
});
if (bytes_total == bytes_downloaded) {
Log.e(TAG, "run block 1");
myTimer.cancel();
mProgressDialog.dismiss();
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
activity.registerReceiver(downloadReceiver, intentFilter);
Log.e(TAG, "run block 2");
}
} else {
}
} catch (Exception e) {
Log.e(TAG, "Exception:" + e.getMessage());
} finally {
Log.e(TAG, "finally");
cursorTimer.close();
}
}
}, 0, 1000);
try {
Log.e(TAG, "BroadcastReceiver ");
downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "BroadcastReceiver onReceive");
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
cursorMain = downloadManager.query(query);
Log.e(TAG, "BroadcastReceiver " + cursorMain.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (cursorMain.moveToFirst()) {
int columnIndex = cursorMain.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursorMain.getInt(columnIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
ParcelFileDescriptor file;
try {
file = downloadManager.openDownloadedFile(preferenceManager.getLong(strPref_Download_ID, 0));
InputStream fileStream = new FileInputStream(file.getFileDescriptor());
FileOutputStream newOS = null;
if (isReaname) {
newOS = activity.openFileOutput("encrypted$" + mFileName, Context.MODE_PRIVATE);
} else {
newOS = activity.openFileOutput(mFileName, Context.MODE_PRIVATE);
}
byte[] buffer = new byte[1024];
int length;
while ((length = fileStream.read(buffer)) > 0) {
newOS.write(buffer, 0, length);
}
newOS.flush();
fileStream.close();
newOS.close();
downloadManager.remove(id);
activity.unregisterReceiver(downloadReceiver);
PrefEdit.clear();
OnHttpResponseDownloadFile callBack = (OnHttpResponseDownloadFile) activity;
callBack.onSuccessDownloadFile(mFileName, mDisplayName_);
} catch (Exception e) {
}
} else {
downloadManager.remove(id);
activity.unregisterReceiver(downloadReceiver);
}
}
}
};
} catch (Exception e) {
} finally {
}
}
}
declaration:
public static DownloadReciver downloadReceiver = new DownloadReciver();
Now this is my reciver class
public static class DownloadReciver extends BroadcastReceiver {
public DownloadReciver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
}
}
I am calling like this:
if (bytes_total == bytes_downloaded) {
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
activity.registerReceiver(downloadReceiver, intentFilter);
}
this is my manifest:
<receiver android:name="com.mobule.lms.connection.MobuleDownloadManager$DownloadReciver" >
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
I got Exception:
java.lang.RuntimeException: Unable to start receiver com.mobule.lms.connection.MobuleDownloadManager$DownloadReciver: java.lang.NullPointerException
Did you declare BroadcastReceiver in your Manifest?
Declare Receiver in Manifest, Check Android 6.0 Marshmallow Permissions given or not and Check uses-permissions provided or not.
For Inner Class also we can Declare in Manifest:
The receiver android:name attribute should look like .path.to.class.MyClass$MyInnerClass
You Should Register your broadcast receiver as the following
<receiver android:name=".path.to.your.downloadReciever" >
<intent-filter>
<action android:name="your filter" />
</intent-filter>
</receiver>
I am uploading image to Amazon S3 from gallery via android app.
it showing java.lang.IllegalStateException: Content has been consumed error
I have added my code below ,please help me solve it.
Error i am Getting like this
06-17 17:23:22.908: W/System.err(27214): java.lang.IllegalStateException: Content has been consumed
06-17 17:23:22.909: W/System.err(27214): at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
06-17 17:23:22.909: W/System.err(27214): at com.amazonaws.http.AmazonHttpClient.executeHelper(Unknown Source)
06-17 17:23:22.910: W/System.err(27214): at com.amazonaws.http.AmazonHttpClient.execute(Unknown Source)
06-17 17:23:22.910: W/System.err(27214): at com.amazonaws.services.s3.AmazonS3Client.invoke(Unknown Source)
06-17 17:23:22.910: W/System.err(27214): at com.amazonaws.services.s3.AmazonS3Client.uploadPart(Unknown Source)
06-17 17:23:22.911: W/System.err(27214): at com.readystatesoftware.simpl3r.Uploader.start(Uploader.java:162)
06-17 17:23:22.911: W/System.err(27214): at com.readystatesoftware.simpl3r.example.UploadService.onHandleIntent(UploadService.java:103)
06-17 17:23:22.911: W/System.err(27214): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
06-17 17:23:22.911: W/System.err(27214): at android.os.Handler.dispatchMessage(Handler.java:99)
06-17 17:23:22.912: W/System.err(27214): at android.os.Looper.loop(Looper.java:153)
06-17 17:23:22.912: W/System.err(27214): at android.os.HandlerThread.run(HandlerThread.java:60)
UploadService.java
public class UploadService extends IntentService {
public static final String ARG_FILE_PATH = "file_path";
public static final String UPLOAD_STATE_CHANGED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_STATE_CHANGED_ACTION";
public static final String UPLOAD_CANCELLED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_CANCELLED_ACTION";
public static final String S3KEY_EXTRA = "s3key";
public static final String PERCENT_EXTRA = "percent";
public static final String MSG_EXTRA = "msg";
private static final int NOTIFY_ID_UPLOAD = 1337;
private AmazonS3Client s3Client;
private Uploader uploader;
private NotificationManager nm;
public UploadService() {
super("simpl3r-example-upload");
}
#Override
public void onCreate() {
super.onCreate();
s3Client = new AmazonS3Client(
new BasicAWSCredentials(getString(R.string.s3_access_key), getString(R.string.s3_secret)));
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
IntentFilter f = new IntentFilter();
f.addAction(UPLOAD_CANCELLED_ACTION);
registerReceiver(uploadCancelReceiver, f);
}
#Override
protected void onHandleIntent(Intent intent) {
String filePath = intent.getStringExtra(ARG_FILE_PATH);
File fileToUpload = new File(filePath);
final String s3ObjectKey = md5(filePath);
String s3BucketName = getString(R.string.s3_bucket);
final String msg = "Uploading " + s3ObjectKey + "...";
// create a new uploader for this file
uploader = new Uploader(this, s3Client, s3BucketName, s3ObjectKey, fileToUpload);
/* File theFile = new File(filePath);
PutObjectRequest putObjectRequest = new PutObjectRequest(amazonFileUploadLocationOriginal, keyName, theFile);
putObjectRequest.withMetadata(objectMetadata);*/
// listen for progress updates and broadcast/notify them appropriately
uploader.setProgressListener(new UploadProgressListener() {
#Override
public void progressChanged(ProgressEvent progressEvent,
long bytesUploaded, int percentUploaded) {
Notification notification = buildNotification(msg, percentUploaded);
nm.notify(NOTIFY_ID_UPLOAD, notification);
broadcastState(s3ObjectKey, percentUploaded, msg);
}
});
// broadcast/notify that our upload is starting
Notification notification = buildNotification(msg, 0);
nm.notify(NOTIFY_ID_UPLOAD, notification);
broadcastState(s3ObjectKey, 0, msg);
try {
String s3Location = uploader.start(); // initiate the upload
broadcastState(s3ObjectKey, -1, "File successfully uploaded to " + s3Location);
} catch (UploadIterruptedException uie) {
broadcastState(s3ObjectKey, -1, "User interrupted");
} catch (Exception e) {
e.printStackTrace();
broadcastState(s3ObjectKey, -1, "Error: " + e.getMessage());
}
}
#Override
public void onDestroy() {
nm.cancel(NOTIFY_ID_UPLOAD);
unregisterReceiver(uploadCancelReceiver);
super.onDestroy();
}
private void broadcastState(String s3key, int percent, String msg) {
Intent intent = new Intent(UPLOAD_STATE_CHANGED_ACTION);
Bundle b = new Bundle();
b.putString(S3KEY_EXTRA, s3key);
b.putInt(PERCENT_EXTRA, percent);
b.putString(MSG_EXTRA, msg);
intent.putExtras(b);
sendBroadcast(intent);
}
private Notification buildNotification(String msg, int progress) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setWhen(System.currentTimeMillis());
builder.setTicker(msg);
builder.setContentTitle(getString(R.string.app_name));
builder.setContentText(msg);
builder.setSmallIcon(R.drawable.ic_stat_uploading);
builder.setOngoing(true);
builder.setProgress(100, progress, false);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentIntent(contentIntent);
return builder.build();
}
private BroadcastReceiver uploadCancelReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (uploader != null) {
uploader.interrupt();
}
}
};
private String md5(String s) {
try {
// create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
MainActivity.java
public class MainActivity extends Activity {
private static final int FILE_SELECT_CODE = 0;
Button select;
Button interrupt;
ProgressBar progress;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
select = (Button) findViewById(R.id.btn_select);
interrupt = (Button) findViewById(R.id.btn_interrupt);
progress = (ProgressBar) findViewById(R.id.progress);
status = (TextView) findViewById(R.id.status);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start file chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(
Intent.createChooser(intent, "Select a file to upload"),
FILE_SELECT_CODE);
}
});
interrupt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// interrupt any active upload
Intent intent = new Intent(UploadService.UPLOAD_CANCELLED_ACTION);
sendBroadcast(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
IntentFilter f = new IntentFilter();
f.addAction(UploadService.UPLOAD_STATE_CHANGED_ACTION);
registerReceiver(uploadStateReceiver, f);
}
#Override
protected void onStop() {
unregisterReceiver(uploadStateReceiver);
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILE_SELECT_CODE) {
if (resultCode == RESULT_OK) {
// get path of selected file
Uri uri = data.getData();
String path = getPathFromContentUri(uri);
Log.d("S3", "uri=" + uri.toString());
Log.d("S3", "path=" + path);
// initiate the upload
Intent intent = new Intent(this, UploadService.class);
intent.putExtra(UploadService.ARG_FILE_PATH, path);
startService(intent);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private String getPathFromContentUri(Uri uri) {
String path = uri.getPath();
if (uri.toString().startsWith("content://")) {
String[] projection = { MediaStore.MediaColumns.DATA };
ContentResolver cr = getApplicationContext().getContentResolver();
Cursor cursor = cr.query(uri, projection, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
path = cursor.getString(0);
}
} finally {
cursor.close();
}
}
}
return path;
}
private BroadcastReceiver uploadStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
status.setText(b.getString(UploadService.MSG_EXTRA));
int percent = b.getInt(UploadService.PERCENT_EXTRA);
progress.setIndeterminate(percent < 0);
progress.setProgress(percent);
}
};
}
It looks like you are running a sample from Github https://github.com/jgilfelt/android-simpl3r. The SDK version 1.4.3 is released 3 years ago. It uses Android's built-in Apache HttpClient which is very buggy and has been deprecated by Android. The 'Content has been consumed' issue can occur sometimes.
Please update the SDK to the latest version v2.2.2. It should be backward compatible. Check it out at http://aws.amazon.com/mobile/sdk/.
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'm creating a Fake Camera/Gallery app that just automatically return a random image. I tied it to the ACTION_PICK & IMAGE_CAPTURE intent filters.
However for the Gallery (PICK) code, after calling finish, it doesn't seem to be returning to the calling app.
Here's my code:
public class MainActivity extends Activity {
final static int[] photos = { R.drawable.android_1, R.drawable.android_2,
R.drawable.android_3 };
static int lastPhotoIndex = -1;
private final static String TAG = "FakeCameraGallery";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if (action.contains("PICK")) {
//Act as Gallery
InputStream in = getResources().openRawResource(getNextPhoto());
Bitmap bm = BitmapFactory.decodeStream(in);
Bundle extras = new Bundle();
extras.putParcelable("data", bm);
Intent result = getIntent().putExtras(extras);
if (getParent() == null) {
setResult(Activity.RESULT_OK, result);
} else {
getParent().setResult(Activity.RESULT_OK, result);
}
} else {
//act as Camera
prepareToSnapPicture();
}
finish();
}
private void prepareToSnapPicture() {
checkSdCard();
Intent intent = getIntent();
if (intent.getExtras() != null) {
snapPicture(intent);
setResult(RESULT_OK);
} else {
Log.i(TAG, "Unable to capture photo. Missing Intent Extras.");
setResult(RESULT_CANCELED);
}
}
private void checkSdCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
Toast.makeText(this, "External SD card not mounted",
Toast.LENGTH_LONG).show();
Log.i(TAG, "External SD card not mounted");
}
}
private void snapPicture(Intent intent) {
try {
this.copyFile(getPicturePath(intent));
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.i(TAG, "Can't copy photo");
e.printStackTrace();
}
}
private File getPicturePath(Intent intent) {
Uri uri = (Uri) intent.getExtras().get(MediaStore.EXTRA_OUTPUT);
return new File(uri.getPath());
}
private void copyFile(File destination) throws IOException {
InputStream in = getResources().openRawResource(getNextPhoto());
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
if (in != null) {
Log.i(TAG, "Input photo stream is null");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
}
out.close();
}
private int getNextPhoto() {
if (lastPhotoIndex == photos.length - 1) {
lastPhotoIndex = -1;
}
return photos[++lastPhotoIndex];
}
}
Your code looks fine: are you calling it using startActivityForResult?