-1

我希望我的服务即使在申请完成后也能正常工作。它继续支持工作,并且不会重新启动。我知道这可以在很多应用程序中实现同时下载文件,服务都继续流畅运行,我也想实现

示例代码清楚地说明什么是危险的

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();
}

}

4

1 回答 1

-1

即使您的应用程序已关闭,您的服务也会继续运行。服务在自己的进程中运行,您不需要新的线程。您应该将方法 toDownLoad() 的代码放在 Service 的 doInBackground() 方法中。看看文档:http: //developer.android.com/reference/android/app/Service.html

于 2014-12-28T00:43:24.503 回答