我希望我的服务即使在申请完成后也能正常工作。它继续支持工作,并且不会重新启动。我知道这可以在很多应用程序中实现同时下载文件,服务都继续流畅运行,我也想实现
示例代码清楚地说明什么是危险的
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();
}
}