以下は私のコードです。曲をダウンロードしながらプロセスを表示したい。このコードはSamsungTabとGrandで機能しますが、SamsungAcePlusでは機能しません。私を助けてください。前もって感謝します。
private void Notification() {
Intent in = new Intent(this, DownloadSong.class);
final NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this);
mBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_launcher);
// Start a lengthy operation in a background thread
new Thread(new Runnable() {
@Override
public void run() {
int incr;
// Do the "lengthy" operation 20 times
for (progress = 0; progress <= 100; progress += 5) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, progress, false);
// Displays the progress bar for the first time.
mNotifyManager.notify(0, mBuilder.build());
// Sleeps the thread, simulating an operation
// that takes time
try {
// Sleep for 5 seconds
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
Log.d(TAG, "sleep failure");
}
}
// When the loop is finished, updates the notification
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(1001, mBuilder.build());
}
}
// Starts the thread by calling the run() method in its Runnable
).start();
}
以下は、サービスを使用した私のダウンロードコードです。プログレスダイアログの更新と通知領域でのダウンロードを関連付けたいのですが、正しいコードを実行していますか?
public class DownloadService extends IntentService {
String urlPath;
int next = -1;
private int result = Activity.RESULT_CANCELED;
public DownloadService() {
super("DownloadService");
}
// Will be called asynchronously be Android
@Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
final 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());
while ((next = reader.read()) != -1) {
fos.write(next);
}
// Sucessful 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();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}