在服务中下载文件(Android)

时间:2014-12-28 00:39:20

标签: java android service android-developer-api

我希望即使申请完成后我的服务仍然有效。它继续支持这项工作,并没有重新启动。我知道这可以在下载文件的许多应用程序中实现,服务继续顺利运行所有,我想实现相同的

示例代码,以明确利害关系

public class CacheFile extends Service {

Context context;
NotificationManager mNotificationManager;
int id = 100;

@Override
public void onCreate() {
    context = this;
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    toDownLoad();
    return super.onStartCommand(intent, flags, startId);
}


public void toDownLoad() {
    final NotificationCompat.Builder mBuilder;
    Intent deleteIntent = new Intent(this, ClickNotification.class);
    PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(android.R.drawable.ic_menu_upload)
            .setContentTitle("Uploading Media...")
            .setTicker("Starting uploads")
            .addAction(android.R.drawable.ic_menu_close_clear_cancel, "Пауза", pendingIntentCancel)
            .addAction(android.R.drawable.ic_menu_close_clear_cancel, "Отмена", pendingIntentCancel);
    Intent notificationIntent = new Intent(this, MyActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setProgress(id, 0, true);
    new Thread(
            new Runnable() {
                @Override
                public void run() {
                    int incr;
                    for (incr = 0; incr <= 100; incr+=5) {
                        mBuilder.setProgress(100, incr, false);
                        mNotificationManager.notify(id, mBuilder.build());
                        try {
                            Thread.sleep(5*1000);
                        } catch (InterruptedException e) { }
                    }
                    mBuilder.setContentText("Download complete")
                            .addAction(0, null, null)
                            .addAction(0, null, null)
                            .setProgress(0, 0, false);
                    mNotificationManager.notify(id, mBuilder.build());
                }
            }
    ).start();
    mNotificationManager.notify(id, mBuilder.build());
}

@Override
public void onDestroy() {
    mNotificationManager.cancelAll();
    super.onDestroy();
}

}

1 个答案:

答案 0 :(得分:-1)

即使您的应用程序已关闭,您的服务仍会继续运行。服务在自己的流程中运行,您不需要新的线程。您应该将方法的代码放在服务的doInBackground()方法中的toDownLoad()中。请查看文档:{​​{3}}